Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a question about `boost::shared_ptr<T>`.
There are lots of thread.
```
using namespace boost;
class CResource
{
// xxxxxx
}
class CResourceBase
{
public:
void SetResource(shared_ptr<CResource> res)
{
m_Res = res;
}
shared_ptr<CResource> GetResource()
{
return m_Res;
}
private:
shared_ptr<CResource> m_Res;
}
CResourceBase base;
//----------------------------------------------
// Thread_A:
while (true)
{
//...
shared_ptr<CResource> nowResource = base.GetResource();
nowResource.doSomeThing();
//...
}
// Thread_B:
shared_ptr<CResource> nowResource;
base.SetResource(nowResource);
//...
```
## Q1
If **Thread\_A** do not care the `nowResource` is the newest, will this part of code have problem?
I mean when **Thread\_B** do not `SetResource()` completely, **Thread\_A** get a wrong smart point by `GetResource()`?
## Q2
What does thread-safe mean?
If I do not care about whether the resource is newest, will the `shared_ptr<CResource> nowResource` crash the program when the `nowResource` is released or will the problem destroy the `shared_ptr<CResource>`? | From the boost [documentation](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety):
> `shared_ptr` objects offer the same
> level of thread safety as built-in
> types. A `shared_ptr` instance can be
> "read" (accessed using only const
> operations) simultaneously by multiple
> threads. *Different* `shared_ptr`
> instances can be "written to"
> (accessed using mutable operations
> such as `operator=` or reset)
> simultaneously by multiple threads
> (even when these instances are copies,
> and share the same reference count
> underneath.)
>
> Any other simultaneous accesses result in undefined behavior.
So your usage is not safe, since it uses simultaneous read and write of `m_res`. *Example 3* in the boost documentation also illustrates this.
You should use a separate [mutex](http://www.boost.org/doc/libs/1_38_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types) that guards the access to `m_res` in `SetResource`/`GetResource`. | `boost::shared_ptr<>` offers a certain level of thread safety. The reference count is manipulated in a thread safe manner (unless you configure boost to disable threading support).
So you can copy a `shared_ptr` around and the ref\_count is maintained correctly. What you cannot do safely in multiple threads is modify the actual `shared_ptr` object instance itself from multiple threads (such as calling `reset()` on it from multiple threads). So your usage is not safe - you're modifying the actual `shared_ptr` instance in multiple threads - you'll need to have your own protection.
In my code, `shared_ptr`'s are generally locals or parameters passed by value, so there's no issue. Getting them from one thread to another I generally use a thread-safe queue.
Of course none of this addresses the thread safety of accessing the object pointed to by the `shared_ptr` - that's also up to you. | Is boost shared_ptr <XXX> thread safe? | [
"",
"c++",
"boost",
"thread-safety",
"shared-ptr",
"boost-smart-ptr",
""
] |
I have two questions.They both are concerning a void in C++,which I am trying to translate in C#.
C++ code
```
void Func_X_2(LPBYTE stream, DWORD key, BYTE keyByte)
{
stream[0] ^= (stream[0] + LOBYTE(LOWORD(key)) + keyByte);
stream[1] ^= (stream[1] + HIBYTE(LOWORD(key)) + keyByte);
stream[2] ^= (stream[2] + LOBYTE(HIWORD(key)) + keyByte);
stream[3] ^= (stream[3] + HIBYTE(HIWORD(key)) + keyByte);
stream[4] ^= (stream[4] + LOBYTE(LOWORD(key)) + keyByte);
stream[5] ^= (stream[5] + HIBYTE(LOWORD(key)) + keyByte);
stream[6] ^= (stream[6] + LOBYTE(HIWORD(key)) + keyByte);
stream[7] ^= (stream[7] + HIBYTE(HIWORD(key)) + keyByte);
}
```
First question:
DWORD is UInt32,BYTE is byte,but what is LPBYTE? How to use it as an array?
Second question:
How to use LOBYTE,HIBYTE,LOWORD,HIWORD in C#?
**EDIT**
This is how the function is being called:
C++ code
```
Func_X_2((LPBYTE)keyArray, dwArgs[14], keyByte);
```
keyArray is a DWORD(UInt32),dwArgs is an array of dword.KeyByte is a byte.
Thanks in advance. | LPBYTE is a pointer to a byte array. The equivalent in C# would be a variable of type byte[]. So you could translate your function like so:
```
public static void Func_X_2(byte[] stream, int key, byte keyByte)
{
stream[0] ^= (byte)(stream[0] + BitConverter.GetBytes(LoWord(key))[0]);
stream[1] ^= (byte)(stream[1] + BitConverter.GetBytes(LoWord(key))[1]);
stream[2] ^= (byte)(stream[2] + BitConverter.GetBytes(HiWord(key))[0]);
stream[3] ^= (byte)(stream[3] + BitConverter.GetBytes(HiWord(key))[1]);
stream[4] ^= (byte)(stream[4] + BitConverter.GetBytes(LoWord(key))[0]);
stream[5] ^= (byte)(stream[5] + BitConverter.GetBytes(LoWord(key))[1]);
stream[6] ^= (byte)(stream[6] + BitConverter.GetBytes(HiWord(key))[0]);
stream[7] ^= (byte)(stream[7] + BitConverter.GetBytes(HiWord(key))[1]);
}
public static int LoWord(int dwValue)
{
return (dwValue & 0xFFFF);
}
public static int HiWord(int dwValue)
{
return (dwValue >> 16) & 0xFFFF;
}
``` | LPBYTE stands for Long Pointer to Byte, so it's effectively a Byte array.
If you have an uint32, u (have to be careful shifting signed quantities):
```
LOWORD(u) = (u & 0xFFFF);
HIWORD(u) = (u >> 16);
```
assumes only bottom 16 bits set (ie. top 16 bits zero):
```
LOBYTE(b) = (b & 0xFF);
HIBYTE(b) = (b >> 8);
``` | How to pass an array of bytes as a Pointer in C# | [
"",
"c#",
"lpbyte",
""
] |
```
#include "stdafx.h"
#include <windows.h>
#include <winsock.h>
#include <stdio.h>
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR IpCmdLine,int nCmdShow)
{
WSADATA ws;
char buf[100];
WSAStartup(0x0101,&ws);
sprintf(buf,"%d.%d",HIBYTE(ws.wVersion),LOBYTE(ws.wVersion));
MessageBox(0,buf,"info",0);
WSACleanup();
return 0;
}
```
This program is for getting information of available wsock version in the computer.
I cannot understand why "stdafx.h" is included in program.
What's the significance of APIENTRY? Can't we use \_stdcall instead?
I also can't compile it in VC++. What's the problem with the code?
Below are the errors when executing program there are no errors during compiling.
```
--------------------Configuration: sa - Win32 Debug--------------------
Linking...
sa.obj : error LNK2001: unresolved external symbol _WSACleanup@0
sa.obj : error LNK2001: unresolved external symbol _WSAStartup@8
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/sa.exe : fatal error LNK1120: 3 unresolved externals
Error executing link.exe.
sa.exe - 4 error(s), 0 warning(s)
``` | 1. `stdafx` is used to implement [precompiled headers](http://msdn.microsoft.com/en-us/library/szfdksca.aspx) in VC++. You can put your library headers like windows.h and winsock.h, etc.. in there and they will only be compiled once each time you modify stdafx.h.
2. APIENTRY is usually just a define for \_\_stdcall, but sometimes it is defined blank (if \_\_stdcall is not supported for example). It's to make your code more portable.
3. Without the actual errors you are getting, I'm not going to be able to help much. But my first guess is that you have unicode on in your build and it's complaining that MessageBoxW doesn't take a char[100] as an argument. In this case, either use wide chars everywhere, or turn off unicode, or use MessageBoxA to explicitly use the ASCII version.
Edit:
Now with the errors, it's easy. Under Project properties -> Linker -> Input -> Additional Dependencies, add ws2\_32.lib. So you can get the Winsock functions linked in.
The missing \_main indicates that you are building the app as a console app, and not a windows app. Go back to project Properties -> Linker -> System and set SubSystem to Windows (/Subsystem:Windows) instead of Console. Or else, just rename WinMain to `int main()` (Make sure you drop the APIENTRY).
Also, if you're using MSVC++ you might as well use the safer sprintf\_s:
```
sprintf_s(buf,100,"%d.%d",HIBYTE(ws.wVersion),LOBYTE(ws.wVersion));
``` | As for the errors: you need to link against ws2\_32.lib library. You can do this in two ways:
1. Add it in Project properties -> Linker -> Input -> "additional libraries" (don't forget to do this for both Debug and Release configurations).
2. In your header add this compiler directive:
#pragma comment(lib, "ws2\_32.lib")
I prefer the second method because the changes you make are visible in the source instead of being hidden deep in project options.
As for APIENTRY and similar defines - it's merely a convenience like returning NULL instead of 0 to point out that you're returning nothing instead of a number zero. Makes code easier to read and understand. | problem with socket programming in c\c++ | [
"",
"c++",
"c",
"sockets",
"winsock",
""
] |
I'm working through a wide variety of procs that have a WHERE clauses that look like this:
```
WHERE ... AND ( ( myTbl.myValue = 1234)
or (myTbl.myValue = 1235) )-- Value = No
```
I've talked this over with some colleagues and this sort of code seems unavoidable. I think it's a good idea to put this sort of code into one (and only one) place. That might be a view, it might be a table etc. I'm thinking a view that selects from the underlying table and has a bit field that says value of 1234 or 1235 is a 0. Or a 'N', etc. That way I can add 'No' values at will without having to change any code. I wouldn't use a UDF for this, too many function calls if you use it in a join.
What are some other options for dealing with special values in your database? Are views a good solution for this? Are there any ways to avoid this sort of thing altogether? I'm thinking that if that value needs to change for whatever reason I don't want to deal with changing hundreds of procs. On the other hand, extra join so it's a performance hit.
Update: if anyone has strategies for just getting rid of the damn things that'd be great too. Like I said, talked it over with colleagues and these things seem unavoidable in organizations that have a lot of business logic in the db layer.
PS: I saw some magic number questions, but nothing specific to a database. | How many magic numbers are we talking about? If it's less than a few thousand, put them in a table and do a join. If they're frequently used in WHERE clauses as a consistent grouping (like the 1234 and 1235 in your example), assign a category column and use IN or EXISTS. (Neither of those will be a meaningful performance hit with a small amount of magic numbers and an appropriate index.)
I detest hard-coded numeric values like those in your example for anything except ad hoc SQL statements. It makes maintenance a real PITA later on. | On Oracle you can set up [deterministic functions](http://download.oracle.com/docs/cd/B12037_01/appdev.101/b10807/08_subs.htm#sthref992) this kind of functions that notice the RDBMS that only is need to be called once.
```
create or replace package MAGIC is
function magic_number return number DETERMINISTIC;
end;
/
create or replace package body MAGIC is
function magic_number return number DETERMINISTIC
is
begin
return 123;
end;
end;
/
SELECT MAGIC_DATE
FROM MAGIC_TABLE
WHERE MAGIC_ID = magic.magic_number;
``` | what are some good strategies for dealing with magic numbers in your database? | [
"",
"sql",
"database-design",
""
] |
for a programming assignment I have been asked to implement a solution to the Dining Philosopher problem. I must do so in two ways:
1. Use the wait() and notifyAll() mechanism
2. Using an existing concurrent data structure provided in the Java API
I have already complete the first implementation. Which concurrent data structure is my professor talking about for step two? I don't remember her mentioning anything. I don't need any source code, just a pointer in the right direction. | You might want to look at the [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html) Javadoc page to get some ideas. These are not the only concurrent data structures (some of the java.util data structures also have built-in concurrency support) but this is a good starting point.
`Collections.synchronizedList` is not what I would call "an existing concurrent data structure" -- it is a wrapper for data structures that do not support concurrency. | Perhaps she meant wrapping Java collections in synchronized wrappers, e.g. using `Collections.synchronizedList()`, or the always synchronized data structures in `java.util.concurrent`, e.g. `CopyOnWriteArrayList`. | Another way to solve the Dining Philosopher (need a point in the right direction) | [
"",
"java",
"multithreading",
"dining-philosopher",
""
] |
A base project contains an abstract base class Foo. In separate client projects, there are classes implementing that base class.
I'd like to serialize and restore an instance of a concrete class by calling some method on the base class:
```
// In the base project:
public abstract class Foo
{
abstract void Save (string path);
abstract Foo Load (string path);
}
```
It can be assumed that at the time of deserialization, all needed classes are present. If possible in any way, the serialization should be done in XML. Making the base class implement IXmlSerializable is possible.
I'm a bit stuck here. If my understanding of things is correct, then this is only possible by adding an `[XmlInclude(typeof(UnknownClass))]` to the base class for every implementing class - but the implementing classes are unknown!
Is there a way to do this? I've got no experience with reflection, but i also welcome answers using it.
**Edit:** The problem is **De**serializing. Just serializing would be kind of easy. :-) | You can also do this at the point of creating an `XmlSerializer`, by providing the additional details in the constructor. Note that it doesn't re-use such models, so you'd want to configure the `XmlSerializer` once (at app startup, from configuration), and re-use it repeatedly... note many more customizations are possible with the `XmlAttributeOverrides` overload...
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
static class Program
{
static readonly XmlSerializer ser;
static Program()
{
List<Type> extraTypes = new List<Type>();
// TODO: read config, or use reflection to
// look at all assemblies
extraTypes.Add(typeof(Bar));
ser = new XmlSerializer(typeof(Foo), extraTypes.ToArray());
}
static void Main()
{
Foo foo = new Bar();
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, foo);
ms.Position = 0;
Foo clone = (Foo)ser.Deserialize(ms);
Console.WriteLine(clone.GetType());
}
}
public abstract class Foo { }
public class Bar : Foo {}
``` | You don't have to put the serialization functions into any base class, instead, you can add it to your Utility Class.
e.g. ( the code is for example only, rootName is optional )
```
public static class Utility
{
public static void ToXml<T>(T src, string rootName, string fileName) where T : class, new()
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
serializer.Serialize(writer, src);
writer.Flush();
writer.Close();
}
}
```
Simply make call to
```
Utility.ToXml( fooObj, "Foo", @"c:\foo.xml");
```
Not only Foo's family types can use it, but all other serializable objects.
EDIT
OK full service... (rootName is optional)
```
public static T FromXml<T>(T src, string rootName, string fileName) where T : class, new()
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
TextReader reader = new StreamReader(fileName);
return serializer.Deserialize(reader) as T;
}
``` | Serializing and restoring an unknown class | [
"",
"c#",
"xml-serialization",
"abstract-class",
""
] |
Working on improving performance of our decision center, one of the bottlenecks we identify is the DB.
So I wonder, does oracle compiles an Execution Plan for it's views?
Lets hypothetically assume I have a defined query being used `10000` times during a request.
The query looks something like :
```
select A, B, C
from aTbl, bTbl left join cTbl on bTbl.cTblID = cTbl.objectkey
where aTbl.objectkey = bTbl.parentkey
```
In the code I would like to fetch the result of the query above with additional filtering parameter, for example: `WHERE aTbl.flag1 = <<NUMBER>>`
Now I have 2 options:
1. Creating a prepared statement using the above `SQL`, then reusing the object.
2. Putting the above `select (aTbl, bTbl, cTbl)` into a `VIEW`, then creating a prepared statement on this view, thus benefiting the from execution plan precompiled b Oracle.
What would you suggest? | `Oracle` *may* push predicate into a view if it thinks it will improve the plan.
If you want to avoid this, you may use either of the following:
1. Add a `/*+ NO_MERGE */` or `/*+ NO_PUSH_PRED */` hint into the view definition
2. Add a `/*+ NO_MERGE (view) */` or `/*+ NO_PUSH_PRED (view) */` hint into the query that uses the view.
If you want to force this, use their couterparts `/*+ PUSH_PRED */` and `/*+ MERGE */`
As long as performance is concerned, there is no difference between using a defined view (if it's not a `MATERIALIZED VIEW` of course) or an inline view (i. e. subquery).
`Oracle` compiles plans not for views, but for exact `SQL` texts.
That is, for the following statements:
```
SELECT A, B, C
FROM aTbl, bTbl
LEFT JOIN cTbl ON
bTbl.cTblID = cTbl.objectkey
WHERE aTbl.objectkey = bTbl.parentkey
AND aTbl.flag1 = :NUMBER
SELECT *
FROM
(
SELECT A, B, C, flag1
FROM aTbl, bTbl
LEFT JOIN cTbl ON
bTbl.cTblID = cTbl.objectkey
WHERE aTbl.objectkey = bTbl.parentkey
)
WHERE flag1 = :NUMBER
/*
CREATE VIEW v_abc AS
SELECT A, B, C, flag1
FROM aTbl, bTbl
LEFT JOIN cTbl ON
bTbl.cTblID = cTbl.objectkey
WHERE aTbl.objectkey = bTbl.parentkey
*/
SELECT A, B, C
FROM v_abc
WHERE flag1 = :NUMBER
```
the plan will:
1. Be the same (if `Oracle` will choose to push the predicate, which is more than probable);
* Be compiled when first called;
* Be reused when called again. | A view isn't really what you want here.
What you want to do is use [bind variables](http://www.akadia.com/services/ora_bind_variables.html) for your flag condition; that way you can compile the statement once, and execute multiple times for different flags.
Just as a stylistic note -- you should decide how you specify joins, and go with that, for consistency and readability. As is, you have the explicit join condition for atbl and btbl, and the "left join" syntax for btbl and ctbl.. doesn't really matter in the scheme of things, but looks and reads a little strange.
Good luck! | Can using a VIEW for SELECT operations improve performance? | [
"",
"sql",
"performance",
"oracle",
""
] |
I recently read about <http://php.net/pcntl> and was woundering how good that functions works and if it would be smart to use multithreading in PHP since it isn't a core function of PHP.
I would want to trigger events that don't require feedback through it like fireing a cronjob execution manually.
All of it is supposed to run in a web app written with Zend Framework | The pcntl package works quite fine - it just uses the according [unix functions](http://linux.die.net/man/2/fork). The only shortage is that you can't use them if php is invoked from a web server context. i.e. you can use it in shell scripts, but not on web pages - at least not without using a hack like [calling a forking script with exec](http://joseph.randomnetworks.com/archives/2005/10/21/fake-fork-in-php/) or similar.
[edit]
I just found a page explaining [why mod\_php cannot fork](http://www.mail-archive.com/php-bugs@lists.php.net/msg95558.html). Basically it's a security issue.
[/edit] | This is not thread control, this is process control. The library for the threads is [pthreads (POSIX threads)](http://en.wikipedia.org/wiki/POSIX_Threads) and it's not included in PHP, so there are no multi-threading functions in PHP.
As of multiprocessing, you cannot use that in mod\_php, as that would be a giant security hole (spawned process would have all the web-server's privileges). | Multithreading in PHP | [
"",
"php",
"multithreading",
""
] |
I have generated an image using [PIL](http://www.pythonware.com/products/pil/). How can I save it to a string in memory?
The `Image.save()` method requires a file.
I'd like to have several such images stored in dictionary. | You can use the [`BytesIO`](https://docs.python.org/3.7/library/io.html#io.BytesIO) class to get a wrapper around strings that behaves like a file. The `BytesIO` object provides the same interface as a file, but saves the contents just in memory:
```
import io
with io.BytesIO() as output:
image.save(output, format="GIF")
contents = output.getvalue()
```
You have to explicitly specify the output format with the `format` parameter, otherwise PIL will raise an error when trying to automatically detect it.
If you loaded the image from a file it has a [`format`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.format) property that contains the original file format, so in this case you can use `format=image.format`.
In old Python 2 versions before introduction of the `io` module you would have used the [`StringIO`](https://docs.python.org/2/library/stringio.html) module instead. | For Python3 it is required to use BytesIO:
```
from io import BytesIO
from PIL import Image, ImageDraw
image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")
byte_io = BytesIO()
image.save(byte_io, 'PNG')
```
Read more: <http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image> | How to write PNG image to string with the PIL? | [
"",
"python",
"python-imaging-library",
""
] |
I'm pretty confused! with this:
```
...
<div id="main">
<div id="content">
<div class="col1">
...COLUMN1 CONTENT GOES HERE...
</div>
<div class="col2">
...COLUMN2 CONTENT GOES HERE...
</div>
</div><!-- #content -->
</div><!-- #main -->
...
```
there are columns as you see, and I want to set their container element's height to the maximum size of both columns(plus 130px). so by using Prototype framework:
```
//fixing column height problem
Event.observe(window,"load",function(){
if(parseInt($('col1').getStyle('height')) > parseInt($('col2').getStyle('height')))
$('main').setStyle({'height' : parseInt($('col1').getStyle('height'))+130+'px'});
else
$('main').setStyle({'height' : parseInt($('col2').getStyle('height'))+130+'px'});
});//observe
```
It working nice in Firefox, Opera, Safari & Chrome but it fails to return the actual height of columns. in IE7+ (not tested in IE6) it returns **NaN** as columns height.
I've managed to find out that's because of this:
```
.col1,.col2{"height:auto;"}
```
I've also used "$('col1').offsetHeight" and it's returning 0 as the height value of each column.
the HTML is styled in this way:
```
#main{
height: 455px;
background: #484848 url(../images/mainbg.png) repeat-x;
}
#content{
/*height:80%;*/
width: 960px;
direction: rtl;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
position: relative;
}
.col1,.col2{
width: 33%;
text-align: right;
margin-left:3px;
padding-right:3px;
line-height:17px;
}
.col1{padding-top:20px;}
.col1 ul{
margin:0;
padding:0;
list-style: url(../images/listBullet.gif);
}
.col1 ul li{
margin-bottom:20px;
}
.col2{
top: 0;
right: 70%;
position: absolute;
}
```
any idea on the issue please?!
**update**/ It tooks three days to solve, and I was at the very risk of making a bounty!
for the solution please take a look at [this question/answer](https://stackoverflow.com/questions/697271/javascript-event-hierarchy-in-prototype-framework). | As a completion for Marc's answer; There's an equal for jQuery's *height()* in Prototype:
```
$('col1').getDimensions().height //or .width ofcourse
```
And here's the docs: <http://prototypejs.org/api/element/getDimensions>
**Update:** I agree with [crescentfresh](https://stackoverflow.com/questions/692523/getting-actual-height-of-an-auto-heighted-element-in-ie/692670#692670) below. Since I had the absolute same problem in the past, I've searched all possible methods to find the dimension properties but I failed as you will. please take a look at this:
```
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
```
As you see, the function [has been written](http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/) to get the *computed rendered current style of an element*, but in our case even this method will fail, I guess. (worth a try)
So, as crescentfresh [said](https://stackoverflow.com/questions/692523/getting-actual-height-of-an-auto-heighted-element-in-ie/692670#692670), you have to find the problem in your CSS positioning method while not wasting your time seeking for a proper javascript function which could be able to do the magic. let's begin by removing that *#content* DIV and letting the *#main* to be the only wrapper of said columns, and then styling the remain to achieve the desired goal. | Since IE wants to give you a hard time, you can give it some special attention and use a property that I believe it will recognize...
```
var height;
if(document.all) { //This means it is IE
height = document.getElementById('col1').offsetHeight;
}
else {
height = //Use what is working in other browsers now
}
``` | Getting actual height of an auto-heighted element in IE | [
"",
"javascript",
"html",
"css",
"internet-explorer",
"internet-explorer-7",
""
] |
When I send `");--` from an input field to my localhost PHP server, it AUTOMATICALLY converts it to
> \");--
It seems great, except that I don't know how trustworthy this behavior is.
Although it seems to avoid SQL injections, my development environment is not the same as the production environment and I'm afraid that the production environment may not have this sort of protection automatically activated...
Why does PHP does this(convert the input without having to use `mysql_real_escape_string`)? Does it *always* do it or only with certain extensions? Is it safe to rely on this behavior to prevent SQL injections? | It seems that you have [Magic Quotes](http://docs.php.net/manual/en/security.magicquotes.php) enabled. But you better disable this option or revert them. `mysql_real_escape_string` is more secure. | This "feature" of PHP is known as "magic quotes". As 'magic' as they may be, it is extremely bad practice to use them, as they do little more than give a false sense of security. Thankfully they have been removed from PHP 6 (in development).
A more detailed list of criticisms can be found in this [Wikipedia article](http://en.wikipedia.org/wiki/Magic_quotes#Criticism).
The PHP manual describes various ways to [disable magic quotes](http://www.php.net/manual/en/security.magicquotes.disabling.php). | PHP protecting itself from SQL injections? | [
"",
"php",
"security",
"sql-injection",
""
] |
Any one know how can I apply Yahoo Compressor (YUI compressor) on my website? | Here is the [README](http://www.julienlecomte.net/yuicompressor/README) on the YUI Compressor. And here is the [How To use](http://developer.yahoo.com/yui/compressor/#using) from their site. | You need to use the YUI compressor to compress your `.js` and `.css` files before putting them on the server. Since the compressor is written in Java, you need to run the java file for compression. This is copied from [YUI web](http://developer.yahoo.com/yui/compressor/):
Using the YUI Compressor from the command line
```
$ java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]
```
The following command line (x.y.z represents the version number):
```
java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js
```
will minify the file `myfile.js` and output the file `myfile-min.js`. For more information on how to use the YUI Compressor, please refer to the documentation included in the archive. | Yahoo Compressor | [
"",
"javascript",
"yui",
"yui-compressor",
""
] |
I have a few simple pages which have no database data, and are just statically loaded from the controller. I have set everything possible to `UTF-8` encoding. I have checked headers, which result to `UTF-8`. However, it still parses wrong showing these characters: ���.
**Controller**:
```
function index(){
$this->load->view('french/header_view');
$this->load->view('french/homepage_view');
$this->load->view('french/footer_view');
}
```
**Config File**:
```
$config['charset'] = "UTF-8";
```
**Header View**:
```
<? header("Content-Type: text/html; charset=UTF-8"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
....
```
**Characters Used in Body View**:
> géniales - à - époustouflant
**Characters generated**:
> � se g�niales !
Where have I gone wrong? Thanks for your help! | It seems that the data is not encoded in UTF-8. Have you checked the encoding settings of your editor? | Old but still relevant:
<http://philsturgeon.co.uk/blog/2009/08/UTF-8-support-for-CodeIgniter> | Codeigniter Character Encoding Issues | [
"",
"php",
"codeigniter",
"character-encoding",
""
] |
I have a file. When I open it in Notepad I see charachters in a single line. However, if I open that file in any other application like [WordPad](http://en.wikipedia.org/wiki/WordPad) or [Notepad++](http://en.wikipedia.org/wiki/Notepad++). I can see irregular line breaks between charachters and they appear in multiple lines. These line breaks also appears if I do `reader.Readline()`. How can I perform Notepad like line read in C#? | Sorry for second answer from me, but I just realised that you could use peek to get next character and check if current and next are \r\n, like so:
```
var path = "c:/test.txt";
File.WriteAllText(path, "a\nb\r\nc");
using (var stream = File.OpenRead(path))
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
var lineBuilder = new StringBuilder();
string line;
char currentChar;
int nextChar;
while (!reader.EndOfStream)
{
currentChar = (char)reader.Read();
nextChar = reader.Peek();
if (!(currentChar == '\r' && nextChar == '\n'))
{
lineBuilder.Append(currentChar);
}
if((currentChar == '\r' && nextChar == '\n') || nextChar == -1)
{
line = lineBuilder.ToString();
Console.WriteLine(line);
lineBuilder = new StringBuilder();
reader.Read();
}
}
}
``` | Such differences are usually because of ambiguity over which encoding the file uses. If you want the file top parse correctly, you'll need to use the right encoding. What characters are causing problems? Also - if the bytes aren't legal in the encoding used, all bets are off ;-p
You can specify the encoding when creating (for example) a `StreamReader` over the file:
```
using (Stream stream = File.OpenRead(path))
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
```
---
With the base-64 posted, the problem is the `\r` in the middle of the line. To read this as a basic string, you could use:
```
byte[] data = File.ReadAllBytes(path);
string txt = Encoding.UTF8.GetString(data);
```
or just:
```
string text = File.ReadAllText("foo.txt");
```
However, you'll always have difficulty displaying this. You can now `Split` on your **chosen** line ending (crlf presumably). `StreamReader` is splitting on anything that looks *like* a line ending.
```
string[] lines = s.Split(new string[] {"\r\n"}, StringSplitOptions.None);
``` | C# notepad alike file read | [
"",
"c#",
""
] |
Is there a simple way in, say Microsoft SQL Server Management Studio to run a saved .sql script on a list of databases? | You could execute the script against multiple databases using a batch file to execute the script using [SQLCMD](http://msdn.microsoft.com/en-us/library/ms180944.aspx) | Yout didn't specify what version, but this is also supported natively in SQL 2008 Management Studio by right clicking on a server group in the Registered Servers window and selecting "New Query". This works against pervious version of SQL as well and mixed groups (e.g. SQL 2000, 2005 and 2008 all at once).
Red-Gate also has a tool you can purchase that does this called SQL Multi Script: <http://www.red-gate.com/products/SQL_Multi_Script/index.htm>. I've never used it though. | Simple way to run same .sql script on multiple databases at once? | [
"",
"sql",
""
] |
I've read Joel's article on [Unicode](http://www.joelonsoftware.com/articles/Unicode.html) and I feel that I have at least a basic grasp of internationalization from a character set perspective. In addition to reading [this question](https://stackoverflow.com/questions/898/internationalization-in-your-projects), I've also done some of my own research on internationalization in regards to design considerations, but I can't help but suspect that there is a lot more out there that I just don't know or don't know to ask.
**Some of the things I've learned:**
* Some languages read right-to-left
instead of left-to-right.
* Calendar, dates, times, currency, and
numbers are displayed differently
from language to language.
* Design should be flexible enough to
accommodate a lot more text because
some languages are far more verbose
than others.
* Don't take icons or colors for
granted when it comes to their
semantic meaning as this can vary
from culture to culture.
* Geographical nomenclature varies from
language to language.
**Where I'm at:**
* My design is flexible enough to
accommodate a lot more text.
* I automatically translate each
string, including error messages and help dialogs.
* I haven't come to a point yet where
I've needed to display units of time,
currency or numbers, but I'll be
there shortly and will need to
develop a solution.
* I'm using the UTF-8 character set
across the board.
* My menus and various lists in the application are sorted
alphabetically for each language for easier reading.
* I have a tag parser that extracts
tags by filtering out stop words. The
stop words list is language specific
and can be swapped out.
**What I'd like to know more about:**
* I'm developing a downloadable PHP web application,
so any specific advice in regards to
PHP would be greatly appreciated.
I've developed my own framework and
am not interested in using other
frameworks at this time.
* I know very little about non-western
languages. Are there specific
considerations that need to be taken
into account that I haven't mentioned
above? Also, how do PHP's array
sorting functions handle non-western
characters?
* Are there any specific gotchas that
you've experienced in practice? I'm looking in terms of both the GUI and the application code itself.
* Any specific advice for working with
date and time displays? Is there a
breakdown according to region or
language?
* I've seen a lot of projects and sites
let their communities provide
translation for their applications
and content. Do you recommend this
and what are some good strategies for
ensuring that you have a good
translation?
* This question is basically the extent
of what I know about
internationalization. What don't I
know that I don't know that I should
look into further?
**Edit**: I added the bounty because I would like to have more real-world examples from experience. | Our game [Gemsweeper](http://www.lobstersoft.com/gemsweeper/index.php) has been translated to 8 different languages. Some things I have learned during that process:
* **If the translator is given single sentences to translate, make sure that he knows about the context that each sentence is used in.** Otherwise he might provide one possible translation, but not the one you meant.
Tools such as [Babelfish](http://babelfish.yahoo.com/) translate without understanding the context, which is why the result is usually so bad. Just try translating any non-trivial text from English to German and back and you'll see what I mean.
* **Sentences that should be translated must not be broken into different parts for the same reason.** That's because you need to maintain the context (see previous point) and because some languages might have the variables at the beginning or end of the sentence. Use placeholders instead of breaking up the sentence. For example, instead of
> "This is step" "of our 15-step
> tutorial"
Write something like:
> "This is step %1 of our 15-step tutorial"
and replace the placeholder programmatically.
* **Don't expect the translator to be funny or creative.** He usually isn't motivated enough to do it unless you name the particular text passages and pay him extra. For example, if you have and word jokes in your language assets, tell the translator in a side note not to try to translate them, but to leave them out or replace them with a more somber sentence instead. Otherwise the translator will probably translate the joke word by word, which usually results in complete nonsense. In our case we had one translator and one joke writer for the most critical translation (English).
* **Try to find a translator who's first language is the language he is going to translate your software to, not the other way round.** Otherwise he is likely to write a text that might be correct, but sounds odd or old-fashioned to native speakers. Also, he should be living in the country you are targeting with your translation. For example a German-speaking guy from Switzerland would not be a good choice for a German translation.
* **If any possible, have one of your public beta test users who understands the particular translation verify translated assets and the completed software.** We've had some very good and very bad translations, depending on the person who provided it. According to some of our users, the Swedish translation was total gibberish, but it was too late to do anything about it.
* **Be aware that, for every updated version with new features, you will have to have your languages assets translated.** This can create some serious overhead.
* **Be aware that end users will expect tech support to speak their language if your software is translated.** Once again, Babelfish will most probably not do.
**Edit - Some more points**
* **Make switching between localizations as easy as possible.** In Gemsweeper, we have a hotkey to switch between different languages. It makes testing much easier.
* **If you are going to use exotic fonts, make sure these include special characters.** The fonts we chose for Gemsweeper were fine for English text, but we had to add quite a few characters by hand which only exist in German, French, Portughese, Swedish,...
* **Don't code your own localization framework.** You're probably much better off with an open source framework like [Gettext](http://www.gnu.org/software/gettext/). Gettext supports features like variables within sentences or pluralization and is rock-solid. Localized resources are compiled, so nobody can tamper with them. Plus, you can use tools like [Poedit](http://www.poedit.net/) for translating your files / checking someone else's translation and making sure that all strings are properly translated and still up to date in case you change the underlying source code. I've tried both rolling my own and using Gettext instead and I have to say that Gettext plus PoEdit were way superior.
**Edits - Even More Points**
* **Understand that different cultures have different styles of number and date formats.** Numbering schemes are not only different per culture, but also per purpose within that culture. In EN-US you might format a number '-1234'; '-1,234' or (1,234) depending on what the purpose of the number is. Understand other cultures do the same thing.
* **Know where you're getting your globalization information from.** E.g. Windows has settings for CurrentCulture, UICulture, and InvariantCulture. Understand what each one means and how it interacts with your system (they're not as obvious as you might think).
* **If you're going to do east Asian translating, really do your homework.** East-Asian languages have quite a few differences from languages here. In addition to having multiple alphabets that are used simultaneously, they can use different layout systems (top-down) or grid-based. Also numbers in east Asian languages can be very different. In the en-US you only change systems for limited conditions (e.g. 1 versus 1st), there are additional numeric considerations besides just comma and period. | > * My menus and various lists in the
> application are sorted alphabetically
> for each language for easier reading.
lists should be sorted, menus shouldn't. keep in mind that a given user might want to use your application in more than one language, he should still find everywhere in the same place.
the same with shortcuts, if you have any: *do not translate them*.
also, remember that internationalization and translation are two very different things, manage them separately. | Design considerations for internationalization | [
"",
"php",
"internationalization",
"locale",
""
] |
I've never been a fan of Hungarian notation, I've always found it pretty useless unless you're doing some really low level programming, but in every C++ project I've worked on some kind of Hungarian notation policy was enforced, and with it the use of some 'not-really-Hungarian' prefixes as m\_ for fields, s\_ for statics, g\_ for globals and so on.
Soon I realized how much useless it was in C# and gradually started to drop all of my old habits... but the 'm\_' thing. I still use the m\_ prefix on private fields because I really find it very useful to being able to distinguish between parameters, locals and fields.
The [naming conventions for fields page at MSDN](https://msdn.microsoft.com/en-us/library/ta31s3bc%28v=VS.71%29.aspx) says I shouldn't, but it does not say why (the way e.g. Google's conventions generally tend to rationalize their prescriptions).
Are there reasons why I shouldn't or is it only a matter of style. If it is the latter, are prefixes generally considered a bad style and can I expect negative reactions from other people working on the codebase? | I like the underbar prefix for member fields. Mostly I like it because that way, all of my member fields are shown alphabetically before my methods in the wizard bar at the top of the screen.
 | When you should:
* When your project coding guidelines say you should
When you shouldn't:
* When your project coding guidelines say you shouldn't
If you don't have any guidelines yet, you're free to choose whatever you or your team want and feel most comfortable with. Personally when coding C++ I tend to use `m_` for members, it does help. When coding in other languages, particularly those without true classes (like Javascript, Lua) I don't.
In short I don't believe there is a "right" and a "wrong" way. | Why shouldn't I prefix my fields? | [
"",
"c#",
"field",
"naming-conventions",
"hungarian-notation",
""
] |
I'm tasked with trying creating a site which will create custom HTML templates. The customizations are based-up customized upon user input. I'm currently using tomcat / JSP for the rest of the front end. What I want to do is create the HTML templates in JSP to output conditional HTML code, but instead of display this HTML output to the user, I'd like to save this code to several files (which will then be zipped up and delivered to the user, along with images, css files, js files). I need to know how to create a fake container that will execute a JSP file (process includes and evaluate variables).
I read about using server filters to intercept the output of JSP code, but I am not sure this will work because a) I need to create several HTML files and b) I need to display different content to the user ( i.e. here's ur zip file, download it) not the output of the JSP being processed.
Thanks! | Here is an idea. Create a servlet to accept the input from the user, from the servlet use java.net.HttpURLConnection to pass the input to the JSP page and to get the result.
```
URL urlPage = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlPage.openConnection();
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//then loop through lines of webpage with br.readLine();
```
Then in your servlet you can zip all the files you pull and return it to the user | You could have a servlet that calls to the JSP by opening a URLConnection and then reading in the output into a temp file or a buffer. It would then zip it and write the zip out. | Capture JSP output, save to file | [
"",
"java",
"jsp",
""
] |
I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB.
In general, all changes are stored in DB as history, but I want the recent change duplicated in memory.
So the problem is: i want one variable to be stored in memory instead of DB. | You can use the cache system:
<http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache> | Unfortunately I don't believe you can do this unless you only have one instance of Python running, in which case you can use a global variable. With most web implementations you have a threaded server so this would not work. You would have to do a fetch from the database to get the latest copy of the record.
If this is a very high-usage situation, you may want to look into [memcached](http://www.danga.com/memcached/) (or similar) as a way of lowering the performance overhead of hitting the database for each request. | Store last created model's row in memory | [
"",
"python",
"django",
""
] |
I personally find that makes the life of a developer who has recently joined the project a very sad one. Without almost perfect understanding of the framework mechanisms it makes developing and debugging like a torture, since whenever I get an error or an unexpected behavior I have not a slightest idea where to look. In some rare cases Ctrl+F through the solution helps, but in most cases I either have to ask the senior guy or use try & error approach. In many cases there is no way to test whether it's working save and nice, testers and sadly customers have to check it.
I think that putting queries in stored procedures or at least in one place in code could help.
Is this dynamic approach to queries a standard practice in business applications? I'm personally quite discomfortable with it. | If its a nightmare to debug, then you already have your answer: its not a best practice, and the pattern should be avoided in the future.
For what its worth, dynamic SQL is not necessarily a bad thing, and its extremely common in large business applications. When its done right, it can improve the maintainability of code:
* Most ORMs like Hibernate make database access transparent to the programmer. For example, when you request an object like `User.GetByID(12)`, the ORM will dynamically construct the SQL, execute it, map the fields to your object, and return it. As a programmer, a huge amount of your time is freed up because you don't need to write SQL queries anymore, you can just focus on writing your application. **You can query the database without seeing, touching, or smelling a hardcoded SQL string anywhere in your application, so that you maintain a hard separation between business logic and your data access layer without writing stored procedures.**
* If your dynamically constructed SQL is well-abstracted, then you can swap out databases without changing your data access logic. NHibernate, for example, generates correct SQL based on whatever database vendor is listed in your config file, and it simply just works. **You can, in principle, use the same data access logic with any database vendor.**
* I've seen applications which contain 1000s of stored procedures representing trivial queries (i.e. simple selects, inserts, updates, and deletes). Maintaining these databases is beyond cumbersome, especially when your database schema changes frequently. With well-written dynmamic SQL, you can represent 1000s of equivalent queries in just a few functions (i.e. a function where you pass a tablename and some params). ORMs already provide this abstraction for you, so changes to your database schema do not require changes to your application code (unless you want to add that new field to your business object, of course). **You can change your database schema (add new fields, change datatypes of columns, etc) without changing your application code or data access logic.**
* There are some smaller benefits as well:
+ Regardless of whatever whatever policies there are which require programmers or CMs to copy stored procedures into source control, we forget. If SQL is built up programmatically, its always in source control.
* There are lots of myths about the advantages of stored procedures over dynamic SQL:
+ "Dynamic SQL is prone to SQL injection, stored procedures are not" - simply not true. Dynamic SQL is trivial to parameterize, and in fact parameterized dynamic SQL is easier to write than dynamic SQL which uses excessive string concats. Even still, if you work with a programmer who is so negligent that he writes unsafe dynamic SQL, then chances are he'll write stored procedures just as badly (see [this as a case study](https://stackoverflow.com/questions/434414/what-is-the-most-evil-code-you-have-ever-seen-in-a-production-enterprise-environm/434562#434562)).
+ "Stored procedures are pre-compiled, so they run faster. SQL Server can't cache the execution plan of dynamic SQL" - at least with SQL Server, this is absolutely wrong. Since SQL Server 7.0, "[a stored procedure is compiled at execution time, like any other Transact-SQL statement. SQL Server 2000 and SQL Server 7.0 retain execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans.](http://msdn.microsoft.com/en-us/library/aa174792.aspx)"
+ "Stored procedures let you change SQL without redeploying an application." - this is true for very trivial tweaks, but in 95% of cases, changes to the database require application changes anyway.
Dynamic SQL isn't bad *per se*, but there are lots of warning signs which indicate when you're doing it wrong:
* You should *never* see regex to dissect an SQL statement.
* You should *never* pass chunks of SQL to your data access layer. For example, a method with the signature `User GetUser(string whereclause)` is very fragile. If your database schema changes, your application logic changes as well.
* Data access should be typesafe. You should never pass around untyped datasets or strings -- or if you do, you need to wrap these objects in a typed object before returning them to the user.
* Always consider using an existing ORM before rolling your own.
You've probably noticed I've talked a lot about ORMs in this post. That's because, in general, hard-coding SQL strings is a *bad thing*. The correct way to use dynamic SQL is to have a tool which generates SQL on-the-fly, which is exactly what many ORMs can and already do. | One of the big problems I see with this approach is that there is no clear separation of responsibility. With multiple layers owning different parts of the logic that creates a SQL query you have an application that will not scale well and will be difficult to modify. | SQL queries not in one place but assembled dynamically while passing through several system layers. Is this a good practice? | [
"",
"asp.net",
"sql",
""
] |
I'm building something that requires a simple HTML frontend for editing some properties in CSS. However, I need to get the value specified by a CSS file.
The only parser I can find is [CSS Parser Project](http://cssparser.sourceforge.net/) , and it is in Java. It implements both [Document Object Model Level 2 Style](http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113) & [SAC: The Simple API for CSS](http://www.w3.org/Style/CSS/SAC/) API. It should work, but we have not tried. Any tutorial on this project or the API's?
Another solution my team can think of is to push that responsibility to the client's browser + [jQuery](http://jquery.com/). However, it doesn't seem very reliable and efficient.
Regular expression does not seem to be the right tool for fishing out properties from CSS.
Anyone has a better/simpler solution? Thanks! | <http://sourceforge.net/projects/cssparser/> | [Ben Nadel](http://www.bennadel.com) has created a [CSS parser in ColdFusion](http://www.bennadel.com/projects/css-rule.htm) - it's not fully featured yet, but it might be good enough?
He's also been doing a lot of other CSS-related stuff recently, so if you need more things take a poke around his blog. | CSS Parser in ColdFusion or Java? | [
"",
"java",
"css",
"coldfusion",
"parsing",
"sac",
""
] |
I have a large MFC C++ application that I would be very keen to port into AutoCAD and IntelliCAD. AutoDesk offer Object ARX for this purpose, which replaces the older and slower ADS technology. IntelliCAD, afaik only supports ADS. Has anyone out there done this, and if so which tools did you use and what pitfalls did you encounter?
I'm specifically interested in resources that will simplify the transition, and allow me to maintain seperate CAD based and standalone versions going forward. | Have a look at my answers to a couple of previous AutoCAD questions
[Open source cad drawing (dwg) library in C#](https://stackoverflow.com/questions/169390/open-source-cad-drawing-dwg-library-in-c/206456#206456)
[.Net CAD component that can read/write dxf/ dwg files](https://stackoverflow.com/questions/298622/-net-cad-component-that-can-read-write-dxf-dwg-files/300824#300824)
If you were looking for the same code base to work both inside and outside of AutoCAD then the RealDWG approach may work for you since the code is the same - RealDWG doesn't need AutoCAD as a host application. The open Design Alliance libraries are for making stand-alone applications. Both have supported C++ for years & can be considered stable - well, as stable as CAD gets.
This blog (<http://through-the-interface.typepad.com/>) is a good one for RealDWG | One option to consider is to target AutoCAD and Bricscad. Supporting AutoCAD and IntelliCAD requires essentially two versions of code. Bricscad's goal is to be completely compatible with ObjectARX, and in my experience they are pretty close.
This at least simplifies the problem from supporting three instances (your standalone version, AutoCAD, and IntelliCAD) to supporting two instances (your standalone version and AutoCAD/Bricscad). | Moving an engineering application from standalone to internal to CAD | [
"",
"c++",
"mfc",
"cad",
""
] |
I'm a mostly-newbie Javascript'er and I'm trying it on a webpage which, upon pressing a button, pops up a window which shows a cyclic "movie" with the images from the main window. From what I've tried Googling around I can sense I'm pretty close, but something is eluding me.
I know what follows results in two separate questions, which merit two separate posts. But I figure because both are related with the same problem/objective, maybe this belongs in a single (albeit long) post. So I hope the size of it doesn't enfuriate people too much ... ;-)
Anyway, here's a snapshot of what I think is the relevant code:
```
<html>
<head>
<script language="javascript">
function wait() {}
function anim() {
var timeout; var next;
var popuptitle='Movie';
var main=parent;
var popup=parent.open("","",
"width="+main.document.images[0].width+",height="+(main.document.images[0].height+40)+
"toolbar=no,location=no,directories=no,status=no,"+
"menubar=no,scrollbars=no,copyhistory=no,resizable=no");
popup.document.write('<html><head><title>'+popuptitle+'</title></head><body>'+
'<p align="center"><img name="anim" width="100%" alt=""></p>'+
'<p align="center"><button name="close" onclick="javascript:window.close();">Close</button></p>'+
'</body></html>');
/*while(true)*/
for(i=0; i<main.document.images.length; i++) {
next=main.document.images[i].src;
popup.document.images[0].src=next;
timeout=setTimeout('wait();',500);
}
}
</script>
</head>
<body><h1>Pictures + animation</h1>
<p><button name="exec" onclick="javascript:anim();">Animate (popup)</button></p>
<p><img src="img1.jpg"></p>
....
<p><img src="img16.jpg"></p>
</body>
</html>
```
I typed/adapted this for relevancy; I hope I didn't make any typos...
I'm working with the Debian Etch's *Iceweasel* (Firefox 2.x rebrand); I haven't tried this with other browsers. In Iceweasel, what happens is:
1. The popup show up as is supposed to, but it seems the cycle goes straight to the last picture. `setTimeout` seems to have no effect in "pausing" between pictures.
2. The last picture is shown, and the popup's status bar shows its progress bar midway, suggesting something is loading.
So my questions are:
1. How exactly am I supposed to use the `setTimeout` call here? I've tried to make it call an "empty" function, so it works as a "pause" in the cycle having the `setTimeout()`, where the cycle updates the popup single image from the main window's images array.
2. I find that, if I load the popup by loading the HTML code from an external file (`anim.html`), the statusbar seems to show from the "progress bar" that the window keeps expecting a reload. I'm still going to try if it's from somewhere else, but what I want to know if it is important/relevant that I load the HTML page from an external file with the `window.open()`, versus loading an empty window and doing a writeln to it to "write" the HTML.
3. I've commented the `while(true)` in the cycle, because otherwise the browser stops responding and the computer goes to 100% CPU. I could make an `if` in the `for` cycle to set the counter back to zero before the last item, but is there another "elegant" or "more appropriate" way to make this an infinite cycle -- or does the `while(true)` do just fine?
I appretiate your comments in advance, and if possible a pointer to existing bibliography describing similar solutions. | I do not think this means what you think it means:
```
timeout=setTimeout('wait();',500);
```
Apparently, you're trying to `sleep()` with this. That's not how the JS [timeouts](https://developer.mozilla.org/en/DOM/window.setTimeout) work - this happens `onclick` in your code: you loop through the images array, immediately switch images from 0th to 1st ... to last; *also,* on every switch, you say "run the `wait()` function, 500 ms from now".
`window.setTimeout(foo,bar,baz)` does this: it sets a timer for `bar` milliseconds and returns. Code execution continues with the next statement. After `bar` milliseconds, function `foo(baz)` is automagically called. The 3rd and following arguments for `setTimeout` are optional and will be passed to the function in 1st argument.
What you could do:
```
function anim() {
var timeout; var next;
var popuptitle='Movie';
var main=parent;
var popup=parent.open("","",
"width="+main.document.images[0].width+",height="+
(main.document.images[0].height+40)+
"toolbar=no,location=no,directories=no,status=no,"+
"menubar=no,scrollbars=no,copyhistory=no,resizable=no");
popup.document.write('<html><head><title>'+popuptitle+
'</title></head><body>'+
'<p align="center"><img name="anim" width="100%" alt=""></p>'+
'<p align="center"><button name="close" ' +
'onclick="javascript:window.close();">Close</button></p>'+
'</body></html>');
// *changed below*
// start the animation with the 0th image
next_image(0,main.document.images,popup.document.images[0]);
}
function next_image(index,source_image_array,target_image) {
// if not at end of array
if (source_image_array.length < index) {
next=source_image_array[index].src;
target_image.src=next;
// do this again in 500 ms with next image
window.setTimeout(next_image,500, index+1 ,
source_image_array,target_image);
}
}
```
This way, at the end of your `anim()` function, you call `next_image(0)`, which sets the image to the 0th in array and sets a timer to call `next_image(1)` in 500 ms; when that happens, the image will be set to the 1st and a timer will be set to call `next_image(2)` in another 500 ms, and so on, until there are no more images in the array. | This isn't a direct answer to your question, but by using the JavaScript framework [jQuery](http://jquery.com/) and a [plugin](http://plugins.jquery.com/), you can easily have a image slideshow. I think it's great that you want to learn JavaScript from the grounds up, but going the jQuery+plugin route can save you many, many hours. Heck, even if you want to DIY, I would still recommend using jQuery because it makes DOM manipulation so much easier. | Javascript: Popup with movie from images in main window | [
"",
"javascript",
"image",
"timeout",
"popup",
"cycle",
""
] |
### Duplicate:
> [Cross-platform gui toolkit for deploying Python applications](https://stackoverflow.com/questions/520015/cross-platform-gui-toolkit-for-deploying-python-applications)
I want to create a GUI application in python. Which library is best one? | From the question [Cross-platform gui toolkit for deploying Python applications](https://stackoverflow.com/questions/520015/cross-platform-gui-toolkit-for-deploying-python-applications):
> # [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro)
>
> It's build on top of [Qt](http://qt.nokia.com/), a C++
> framework. It's quite advanced and has
> some good tools like the Qt Designer
> to design your applications. You
> should be aware though, that it
> doesn't feel like Python 100%, but
> close to it.
>
> This framework is really good. It's
> being actively developed by Trolltech,
> who is owned by Nokia. The bindings
> for Python are developed by Riverbank.
>
> Nokia announced that they'd start to
> use LGPL for the Qt-Framework starting
> with Qt 4.5 (to be released in April,
> I think), but it's not yet sure if
> Riverbank follows this and releases
> the bindings for Python under LGPL
> too. (They have a commercial and a GPL
> licence at the moment.)
>
> Qt is not only a GUI-framework but has
> a lot of other classes too, one can
> create an application by just using Qt
> classes. (Like SQL, networking…)
>
> Qt doesn't use native GUI elements,
> but wikipedia mentions that in recent
> versions [Qt uses native
> widgets](http://en.wikipedia.org/wiki/Qt_toolkit#Use_of_native_UI-rendering_APIs) where
> possible. I haven't found evidence in
> [the documentation but for Mac OS
> X](http://doc.qt.nokia.com/4.4/qtmac-as-native.html).
>
> # [wxPython](http://www.wxpython.org/)
>
> wxPython is a binding for Python using
> the [wxWidgets](http://www.wxwidgets.org/)-Framework.
> This framework is under the LGPL
> licence and is developed by the open
> source community.
>
> What I'm really missing is a good tool
> to design the interface, they have
> about 3 but none of them is usable.
>
> One thing I should mention is that I
> found a bug in the tab-view despite
> the fact that I didn't use anything
> advanced. (Only on Mac OS X) I think
> [wxWidgets](http://www.wxwidgets.org/) isn't as
> polished as [Qt](http://qt.nokia.com/).
>
> wxPython is really only about the
> GUI-classes, there isn't much else.
>
> wxWidgets uses native GUI elements.
>
> # Others
>
> I haven't got any experience with
> other GUI frameworks, maybe someone
> else has. | wxWidgets (the Python flavor is called [wxPython](http://wxpython.org)) is currently your best option IMHO, they have support for multi platform (Mac, Window, Linux) and the framework is pretty easy to work with.
[From the site](http://www.wxwidgets.org):
*wxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature. Why not give it a try, like* | What library is best for GUI in python? | [
"",
"python",
"user-interface",
""
] |
I need to measure the time it takes for a function to complete in Java. How can I do that?
### Note:
I want to measure the **function**'s time consumption, not that of the full program. | ```
long start = System.nanoTime();
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
``` | Here is how can compute the elapsed time.
```
// Get current time
long start = System.currentTimeMillis();
// Do something ...
// Get elapsed time in milliseconds
long elapsedTimeMillis = System.currentTimeMillis()-start;
// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;
// Get elapsed time in minutes
float elapsedTimeMin = elapsedTimeMillis/(60*1000F);
// Get elapsed time in hours
float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);
// Get elapsed time in days
float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);
``` | How can I count the time it takes a function to complete in Java? | [
"",
"java",
"profiling",
""
] |
Assuming I'm not using the lock statement, is this a bad practice?
```
public static class Foo
{
public static string Bar()
{
bool working;
while (working)
{
// Loop until ready to run.
}
working = true;
// Do stuff here.
working = false;
return "done."
}
}
```
Edit -
After trying something like this, I realize it's not feasible for several reasons. I was just curious.. The example I posted doesn't even work. | Loop is a CPU consuming process.
I mean if everything you do is just waiting. It is not a good. | First off, working is private to the method, so it will have no effect. 2 threads calling this will each have their own "working". You'd need to make it a static field to have an effect.
Even then, you can get race conditions. 2 threads can hit this at the same time, pass through the while(working) condition, and then set working = true; and be doing things at the same time.
Using a lock or a semaphore will help solve this. | Is this a bad practice with static classes and thread safety? | [
"",
"c#",
"thread-safety",
""
] |
Can somebody tell me what I am doing wrong really? I am going nuts, the following code works perfect on localhost/WIN and when I try it on the webhost/linux it gives warnings:
```
$lines = file('english.php');
foreach($lines as $line) {
$matches=array();
if (preg_match('/DEFINE\(\'(.*?)\',\s*\'(.*)\'\);/i', $line, $matches)) {
$keys[] = $matches[1];
$values[] = $matches[2];
}
}
$lang = array_combine($keys, $values);
```
When I test on webhost:
```
Warning: array_combine() expects parameter 1 to be array, null given in /home/xx/public_html/xx on line 616
```
But on local server (windows xp) it works perfect. I do not know what I am doing wrong, please help me resolve this nightmare :(
Thanks. | I don't see anything obviously wrong with your code, but I'm curious why you're building separate arrays and then combining them rather than just building a combined array:
```
// Make sure this file is local to the system the script is running on.
// If it's a "url://" path, you can run into url_fopen problems.
$lines = file('english.php');
// No need to reinitialize each time.
$matches = array();
$lang = array();
foreach($lines as $line) {
if (preg_match('/DEFINE\(\'([^\']*)\',\s*\'([^\\\\\']*(?:\\.[^\\\\\']*)*)\'\);/i', $line, $matches)) {
$lang[$matches[1]] = $matches[2];
}
}
```
(I've also changed your regex to handle single quotes.) | Are the php versions the same?
And are you sure you have transfered all your files to the webhost? | Need a php script diagnosis for a small snippet of code | [
"",
"php",
"regex",
"arrays",
""
] |
Why is it not possible to do something equivalent to this in PHP:
```
(Array(0))[0];
```
This is just for sake of argument, but it seems strange it does not allow access of anonymous objects. I would have to do something like the following:
```
$array = Array(0);
$array[0];
```
Any ideas why this is the behavior of PHP? | I read something somewhat detailed about this once and I regret not bookmarking it because it was quite insightful. However, it's something along the lines of
"Because the array does not exist in memory until the current statement (line) executes in full (a semicolon is reached)"
So, basically, you're only defining the array - it's not actually created and readable/accessible until the next line.
I *hope* this somewhat accurately sums up what I only vaguely remember reading many months ago. | This language feature hasn’t been inplemented yet but [will come in PHP 6](http://wiki.php.net/rfc/functionarraydereferencing). | Problem with PHP Array | [
"",
"php",
""
] |
```
if (condition) { /* do something */ }
else { /* do something */ }
if (condition)
/* do something */
else
/* do something */
```
I was told that the first instance wasn't a good idea. I have no idea whether this is really this case (or for the second one either); does it not shorten the amount to type? Or is it because it just makes a mess? | The best practice is to write code that others can read and update easily.
Your first form is questionable because it doesn't follow the forms that most PHP developers are used to:
```
if (condition) {
// code
} else {
// code
}
// ... or ...
if (condition)
{
// code
}
else
{
// code
}
// ... or ...
if (condition) { /* short code */ } else { /* short code */ }
// ... or ...
condition ? /* short code */ : /* short code */;
```
Note that this is entirely about standard practice, and doesn't necessarily make sense—it's only about what other developers are used to seeing.
Your second form, more importantly, isn't so good because it makes it easy for another programmer to make this mistake:
```
if (condition)
// code A
else
// code B
// code C (added by another programmer)
```
In this example, the other programmer added `code C`, but forgot to wrap the whole `else` block in braces. This will cause problems. You can defend against this by simply wrapping your `if` and `else` blocks in braces. | My preference if for consistency... so:
```
if(...)
{
statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}
```
is no different than:
```
if(...)
{
statement 1;
}
else
{
statement 1;
}
```
So I always use them because it is consistent and it avoids problems forgetting to add them in later.
However other people will look at my code and think that it is stupid to put in the { and }. They have their reasons, I have mine... I happen to like my reasons more than I like theirs :-) | Are singleline if statements or if statements without braces bad practice? | [
"",
"php",
"c",
"coding-style",
""
] |
I have pasted some code from Jon Skeet's C# In Depth site:
```
static void Main()
{
// First build a list of actions
List<Action> actions = new List<Action>();
for (int counter = 0; counter < 10; counter++)
{
actions.Add(() => Console.WriteLine(counter));
}
// Then execute them
foreach (Action action in actions)
{
action();
}
}
```
<http://csharpindepth.com/Articles/Chapter5/Closures.aspx>
Notice the line:
actions.Add( ()
What does the () mean inside the brackets?
I have seen several examples of lambda expressions, delegates, the use of the Action object, etc but I have seen no explanation of this syntax. What does it do? Why is it needed? | This is shorthand for declaring a lambda expression which takes no arguments.
```
() => 42; // Takes no arguments returns 42
x => 42; // Takes 1 argument and returns 42
(x) => 42; // Identical to above
``` | That's a lambda expression without parameters. | What does () mean in a lambda expression when using Actions? | [
"",
"c#",
"lambda",
""
] |
When I write Java webapps, I usually use JSTL tags. I think that these tags are great, except for one thing that pisses me off: while the expression language allow you to access bean properties, it does not allow you to call its methods.
In release 1.0, it was not even possible to obtain the length of a string or the number of elements in a collection. As of release 1.1, the fn:length function has been added, so you can do things such as this:
```
...
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:if test="${fn:length(str) > 10}">
...
</c:if>
...
```
Which is more verbose and more ugly (IMHO that is) than:
```
...
<c:if test="${str.length() > 10}">
...
</c:if>
...
```
It seams that JSTL 2.0 will allow you to define new functions, but you will need to write a class specifically for that purpose, in which you will define your (static) methods, and you will also need to write a TLD file that will be included in every jsp that will use these functions.
Whether you define custom function or you use another workaround, you have a lot of additional code to write.
I have read somewhere that the JCP had voluntarily disallow the calling of methods from the expression language.
Can anyone of you help me understand why the hell is the JCP doing this to us? | The feature you want is defined in [JSR 245](http://jcp.org/en/jsr/detail?id=245) ([more here](http://blogs.oracle.com/kchung/entry/jsr_245_mr_part_i)). If you want it now, go download it from the [UEL project](https://uel.dev.java.net/) or an alternative implementation (e.g. [JUEL](http://juel.sourceforge.net/)). If you need to wait for it to be part of the standard, it will be included in JEE6. Until then... well, you already know your options. | > Can anyone of you help me understand why the hell is the JCP doing this to us?
It's part of the [bondage and discipline](http://www.catb.org/~esr/jargon/html/B/bondage-and-discipline-language.html) mindset of a certain subset of Java programmers that knows The One True Way that everyone should author applications.
You can't be trusted have a full-powered language at your disposal when writing templates, because you might abuse it to mix together business logic and presentation like those awful, uncouth PHP coders do. Eurgh, imagine!
The programmer is the enemy, and must be prevented from doing Evil. It might turn out that the programmer is actually just you trying to debug something, or put a quick hack in to get the app running temporarily. Or it might turn out that there is such a thing as presentation logic, and making you move that stuff out into a bunch of tag and bean classes in your application is just as unpleasant as the other way around.
But it doesn't matter! It's well worth inconveniencing you to serve the purpose of defending Java's chastity.
[Sorry for the snark, but it was already quite a ranty question eh.]
PS. There's always Groovy I suppose. | Method calls in EL | [
"",
"java",
"jsp",
"jstl",
""
] |
Is there any difference in meaning of `AtomicIntegerArray` and `AtomicInteger[]`?
And which one is faster to use?
(only thing that I noticed is that first is taking much less space, but that means that each recheck is checking boundaries of array, so that would make it slower?)
Edit: In a scenario where array is pre-initialized. | `AtomicInteger[]` will require an object per element. `AtomicIntegerArray` just requires the `AtomicIntegerArray` object and an array object. So use the latter if possible.
The cost of bounds checking is quite small even for normal arrays. What might be significant is that access to data in the same cache line from multiple processors can cause significant performance issues. Therefore separate objects, or deliberately avoiding close elements of an array, can help. | * AtomicInteger[] is an array of thread safe integers.
* AtomicIntegerArray is a thread-safe array of integers. | AtomicIntegerArray vs AtomicInteger[] | [
"",
"java",
"concurrency",
"atomic-values",
""
] |
Is there any way to combine the following two lines into a single statement?
```
Func<XmlNode> myFunc = () => { return myNode; };
XmlNode myOtherNode = myFunc();
```
I've been trying things like the below but can't get it to work and can't determine from the documentation whether it should work or not?
```
XmlNode myOtherNode = ((Func<XmlNode>) () => { return myNode; })();
``` | I'm not sure why you are looking to do this but ..
```
XmlNode myOtherNode = new Func<XmlNode>( () => { return myNode; } )();
```
should do the trick. | The 'trick' is that you need to create an instance of a delegate in order for it to work, which in your example is implicity done when you do the assignment (myFunc = ...). Also, you can express your function as () => myNode to make it shorter.
```
XmlNode myOtherOne = new Func<XmlNode>( () => myNode )();
``` | Is it possible to declare and use an anonymous function in a single statement? | [
"",
"c#",
"lambda",
""
] |
Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ?
Clarification :
The primary goal is to wait for a **particular** string to appear in a given amount of time. Except for IO error, the possible outcome is True (the string did appear) or False
The secondary goal is to get the entire output, because there might be information that I would like to parse for before the actual answer that is looked for. I thought may be I could combine the primary and secondary goal in one return value.
```
def MyFunc(s, timeout) :
test = get_some_input(timeout)
if test.endswith(s)
return test
else
return False
```
Edit : Another proposed answer is to raise an exception. I don't think it is a good idea, because the timeout is an expected behaviour. I mean, if there is a parameter for specifying a timeout, then a timeout is a possible outcome, and not an exception.
Edit 2 :
Since I need to store the input, maybe using a class is the right solution. The wait for function has a clear return value, yet the entire string that was read until timeout is also accessible.
```
class Parser :
def __init__(self, sport_name):
self.currentMsg = ''
self.ser = serial.Serial(sport_name, 115200)
def WaitFor(self, s, timeOut=None):
self.ser.timeout = timeOut
self.currentMsg = ''
while self.currentMsg.endswith(s) != True :
# should add a try catch here
c=self.ser.read()
if c != '' :
self.currentMsg += c
else :
print 'timeout waiting for ' + s
return False
return True
``` | It would be better to return a string AND a boolean (as in the title) instead of returning a string OR a boolean. You shouldn't have to figure out what the return value means. It should be totally explicit and orthogonal issues should be separated into different variables.
```
(okay,value) = get_some_input(blah);
if (okay): print value
```
I tend not to return tuples a lot, because it feels funny. But it's perfectly valid to do so.
Returning "None" is a valid solution, already mentioned here. | Would it not be more suitable to return a `None` instead of `False`? | Python : is it ok returning both boolean and string? | [
"",
"python",
""
] |
I have four tables:
```
- Client with PK ClientID.
- Destination with PK DestinationID.
- Language with PK LanguageID.
- DestinationDetail with PK DestinationID.
- RL-Client-Destination with PKs ClientID and DestinationID.
```
The Client may have zero or n Destinations. A destination has n DestinationDetails, each of these DestinationDetail has a language.
Ok. I need to retrieve all of DestinationDetails for a given client and a given language.
I start writing this:
```
try
{
ObjectQuery clientes =
guiaContext.Cliente;
ObjectQuery destinos =
guiaContext.Destino;
ObjectQuery idiomas =
guiaContext.Idioma;
ObjectQuery detalles =
guiaContext.DetalleDestino;
IQueryable detalleQuery =
from cliente in clientes
from destino in destinos
from idioma in idiomas
from detalleDestino in detalles
where destino.
select detalleDestino;
}
catch
{
}
}
```
Any advice?
Thanks! | Its along the lines:
```
var detalleQuery =
from client in guiaContext.Clients
where client.ID == 1
from destination in cliente.Destinations
from destinationDetail in destination.DestionationDetails
where destinationDetail.Language.Iso2Code == "es"
select destinationDetail;
``` | Have you tried doing linq joins:
[Select from multiple table using LINQ](https://stackoverflow.com/questions/32433/linq-select-with-multiple-tables) | LinQ to Entities: Query with four tables JOIN | [
"",
"c#",
"linq-to-entities",
""
] |
Using PHP, given a URL, how can I determine whether it is an image?
There is no context for the URL - it is just in the middle of a plain text file, or maybe just a string on its own.
I don't want high overhead (e.g. reading the content of the URL) as this could be called for many URLs on a page. Given this restriction, it isn't essential that all images are identified, but I would like a fairly good guess.
At the moment I am just looking at the file extension, but it feels like there should be a better way than this.
Here is what I currently have:
```
function isImage( $url )
{
$pos = strrpos( $url, ".");
if ($pos === false)
return false;
$ext = strtolower(trim(substr( $url, $pos)));
$imgExts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif"); // this is far from complete but that's always going to be the case...
if ( in_array($ext, $imgExts) )
return true;
return false;
}
```
**Edit:** In case it's useful to anybody else here is the final function using the technique from Emil H's answer:
```
function isImage($url)
{
$params = array('http' => array(
'method' => 'HEAD'
));
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp)
return false; // Problem with url
$meta = stream_get_meta_data($fp);
if ($meta === false)
{
fclose($fp);
return false; // Problem reading data from url
}
$wrapper_data = $meta["wrapper_data"];
if(is_array($wrapper_data)){
foreach(array_keys($wrapper_data) as $hh){
if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19
{
fclose($fp);
return true;
}
}
}
fclose($fp);
return false;
}
``` | You could use an [HTTP HEAD](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) request and check the content-type. This might be a good compromise. It can be done using [PHP Streams](https://www.php.net/streams). Wez Furlong has an [article](http://netevil.org/blog/2006/nov/http-post-from-php-without-curl) that shows how to use this approach to send post requests, but it can be easily adapted to send HEAD requests instead. You can retrieve the headers from an http response using [stream\_get\_meta\_data()](https://www.php.net/manual/en/function.stream-get-meta-data.php).
Of course this isn't really 100%. Some servers send incorrect headers. It will however handle cases where images are delivered through a script and the correct file extension isn't available. The only way to be really certain is to actually retrieve the image - either all of it, or the first few bytes, as suggested by thomasrutter. | ```
if(is_array(getimagesize($urlImg)))
echo 'Yes it is an image!';
``` | best way to determine if a URL is an image in PHP | [
"",
"php",
"image",
"url",
""
] |
HI
I am new to WPF and I am looking for a solution to scroll text in a WPF application,
I tried some animation but I have a clipping problem
I found a possible solution to my problem in the following place:
<http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8330696e-7715-479e-8027-8d9925579a17/>
but it is not clear to me what the variables TranslateTransformName, scrollfactor and tt should be..
Can somebody look at the code and help me to figure it out?
thanks
Wally
this is the code there:
Code Block
```
<p class=MsoNoSpacing><
<span class=SpellE>Viewbox</span>
<span class=SpellE>OpacityMask</span> ="{x
<span
class=GramE>:Null</span> }"
<span class=SpellE>HorizontalAlignment</span> ="Center"
<span class=SpellE>VerticalAlignment</span> ="Stretch"
Width="Auto" Height="Auto"
<span class=SpellE>RenderTransformOrigin</span> ="0.5,0.5"
x:Name="container" Stretch="Uniform"
<span class=SpellE>StretchDirection</span> ="Both">
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> <
<span
class=SpellE>Viewbox.RenderTransform</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> <
<span
class=SpellE>TransformGroup</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>ScaleTransform</span>
<span class=SpellE>ScaleX</span> ="1"
<span class=SpellE>ScaleY</span> ="1"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>SkewTransform</span>
<span class=SpellE>AngleX</span> ="0"
<span class=SpellE>AngleY</span> ="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>RotateTransform</span> Angle="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>TranslateTransform</span> X="640"
Y="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> </
<span
class=SpellE>TransformGroup</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> </
<span
class=SpellE>Viewbox.RenderTransform</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> <
<span
class=SpellE>TextBlock</span>
<span class=SpellE>RenderTransformOrigin</span> ="0.5
<span
class=GramE>,0.5</span> "
<span class=SpellE>HorizontalAlignment</span> ="Center"
x:Name="
<span class=SpellE>tb</span> "
<span class=SpellE>VerticalAlignment</span> ="Center"
Width="Auto" Height="Auto"
<span class=SpellE>FontSize</span> ="50"
<span class=SpellE>TextWrapping</span> ="
<span class=SpellE>NoWrap</span> "
Background="{x:Null}" Foreground="#FFFFFFFF"
Padding="0,0,0,10" Text="0">
</p>
<p class=MsoNoSpacing></p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> <
<span
class=SpellE>TextBlock.RenderTransform</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>TransformGroup</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>ScaleTransform</span>
<span class=SpellE>ScaleX</span> ="1"
<span class=SpellE>ScaleY</span> ="1"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>SkewTransform</span>
<span class=SpellE>AngleX</span> ="0"
<span class=SpellE>AngleY</span> ="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>RotateTransform</span> Angle="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> <
<span class=SpellE>TranslateTransform</span> X="640"
Y="0"/>
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'>
</span> </
<span class=SpellE>TransformGroup</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> </
<span
class=SpellE>TextBlock.RenderTransform</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> </
<span
class=SpellE>TextBlock</span> >
</p>
<p class=MsoNoSpacing>
<span style='mso-spacerun:yes'></span> </
<span
class=SpellE>Viewbox</span> >
</p>
<p class=MsoNoSpacing>
<o:p> </o:p>
</p>
<p class=MsoNoSpacing>
<o:p> </o:p>
</p>
<p class=MsoNoSpacing>
<o:p> </o:p>
</p>
<p class=MsoNoSpacing>
<o:p> </o:p>
</p>
```
Code Block
private void StartAnimation(object sender, EventArgs e)
{
tb.Text = news;
```
MainWindow.UpdateLayout();
Double timeToTake = (MainWindow.Width + tb.ActualWidth) / scrollfactor;
this.tb.RenderTransform = tt;
Storyboard sb = new Storyboard();
DoubleAnimation daX = new DoubleAnimation(MainWindow.Width, (0.0 - tb.ActualWidth), new Duration(TimeSpan.FromSeconds(timeToTake)));
daX.RepeatBehavior = RepeatBehavior.Forever;
Storyboard.SetTargetName(daX, TranslateTransformName);
Storyboard.SetTargetProperty(daX, new PropertyPath(TranslateTransform.XProperty));
sb.Children.Add(daX);
sb.Begin(this.tb);
}
``` | <http://jobijoy.blogspot.com/2008/08/wpf-custom-controls-marquee-control.html>
You can check the idea behind this Marquee control. When you say to scroll the text inside the textBlock.. think about scrolling a long textblock inside a marqueee control. This control is a ContentControl which can scroll any Content inside. | Here's a complete sample - verified that it works. I modified [source posted here by Philipsh](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/7a391faa-8607-4c2b-84d4-4ee3bf55a679/) (minor changes to control layout to make it more presentable)
I kind of skipped the animation chapter in Programming WPF . So I can't explain how it works.. the book is not at hand. I'd be guessing at best if I tried to post answers..
XAML
```
<Window x:Class="transforms.Window1"
Title="Window2" SizeToContent="WidthAndHeight">
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
<TextBox x:Name="txtTexttoScroll">Enter some text to marquee</TextBox>
<Button x:Name="button1" Click="button1_Click">Start Scrolling</Button>
</StackPanel>
<Canvas Name="canvas1" Height="32" ClipToBounds="True" Background="AliceBlue" Width="200">
<TextBlock Canvas.Left="0" Canvas.Top="0" Height="31" Name="textBlock1" Width="{Binding ElementName=canvas1, Path=ActualWidth}" Text="Have a nice day!" FontSize="18.6666666666667" TextWrapping="NoWrap" VerticalAlignment="Center">
<TextBlock.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform x:Name="rtTTransform"/>
</TransformGroup>
</TextBlock.RenderTransform>
</TextBlock>
</Canvas>
</DockPanel>
</Window>
```
Button Click Event handler
```
private void button1_Click(object sender, RoutedEventArgs e)
{
double textBoxWidth = 10;
double pixelXFactor;
double canvaswidth = this.canvas1.Width;
double negXOffSet = 0;
double fromSecValue = 0;
double equSlope = 0.022546419;
double offSetY = 10.96286472;
double stringSize;
int textLen = txtTexttoScroll.Text.Length;
//Set the width of the text box according to the width (not length) of the text in it.
System.Globalization.CultureInfo enUsCultureInfo;
Typeface fontTF;
FormattedText frmmtText;
if (textLen > 0)
{
enUsCultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-us");
fontTF = new Typeface(this.textBlock1.FontFamily, this.textBlock1.FontStyle, this.textBlock1.FontWeight, this.textBlock1.FontStretch);
frmmtText = new FormattedText(txtTexttoScroll.Text, enUsCultureInfo, FlowDirection.LeftToRight, fontTF, this.textBlock1.FontSize, this.textBlock1.Foreground);
stringSize = frmmtText.Width;
if (stringSize < 100)
pixelXFactor = 1.02;
else
pixelXFactor = 1.01;
textBoxWidth = stringSize * pixelXFactor;
this.textBlock1.Width = textBoxWidth;
negXOffSet = textBoxWidth * -1;
fromSecValue = (stringSize * equSlope) + offSetY;
this.textBlock1.Text = txtTexttoScroll.Text;
Storyboard _sb = new Storyboard();
Duration durX = new Duration(TimeSpan.FromSeconds(fromSecValue));
DoubleAnimation daX = new DoubleAnimation(canvaswidth, negXOffSet, durX);
daX.RepeatBehavior = RepeatBehavior.Forever;
Storyboard.SetTargetName(daX, "rtTTransform");
Storyboard.SetTargetProperty(daX, new PropertyPath(TranslateTransform.XProperty));
_sb.Children.Add(daX);
_sb.Begin(this.textBlock1);
}
else
{
textBoxWidth = 1;
stringSize = 0;
}
``` | How do I scroll text in WPF textBlock control? | [
"",
"c#",
"wpf",
""
] |
I am a C# programmer who started using ubuntu about 2 years ago. I'm wanting to learn GUI programming in either C or C++. I don't really like mono, it tends to crash on my system. I have a basic understanding of C++. I have never worked in C, but it looks cool. Which toolkit should I learn/use? Give Pro/Cons of each. Thanks! | Since C++ is more familiar to you, you may find GTKmm to be a better fit, since you can use idioms like RAII. Unfortunately, GTKmm is a little incomplete and is missing a few of the lesser-used parts of GTK.
GTK+ on its own, however, essentially exposes an object model similar to what you find in C++, but with only C functions. Things like construction and destruction in C++ are done explicitly in the C API and instances of widgets are handled via pointers exclusively.
Try both and see which fits your project better. | I could be accused of bias since I do help contribute to gtkmm, but I was a user first, so... In any case, I would highly recommend gtkmm if you're comfortable with C++. Memory management is much easier with gtkmm than with GTK+ because reference-counted objects are managed automatically with smart pointers. You can also instantiate objects as auto variables (e.g. on the stack) and have their lifetime determined by their scope. So in practice, it's much easier to avoid memory leaks with gtkmm than with GTK+.
Another *huge* advantage of gtkmm over GTK+ (in my opinion) is the use of a type-safe signals framework. In GTK+, you constantly need to pass things as void pointers and then cast them around to the type you think they should be. In gtkmm, you dont need to do this, and can take advantage of the compiler enforcing type-safety on your signal handlers.
Another big advantage over C/GTK+ is the ease of deriving new classes. In GTK+, you need to write a lot of boilerplate code and basically re-implement things that you get for free in C++ as part of the language (e.g. inheritance, constructors, destructors, etc). This is more tedious and error-prone.
greyfade mentioned that gtkmm is incomplete, and he's right to a certain extent -- gtkmm does not cover absolutely everything in the GTK+ API (though it gets awfully close). But in practice this is not a problem because you can always use the C/GTK+ API directly from your gtkmm code. This C compatibility is a huge advantage of C++ over something like C# or python bindings where you would have no alternatives if the binding didn't cover part of the API.
The only real reasons to choose GTK+ over gtkmm (IMO) are that gtkmm has a little additional overhead since it is a wrapper on top of the C library (but this is generally just a single function call, which is going to have negligible impact), or if you hate or can't use C++. | Should I learn GTK+ or GTKMM? | [
"",
"c++",
"c",
"user-interface",
"gtk",
"gtkmm",
""
] |
I am using Lucene in PHP (using the Zend Framework implementation). I am having a problem that I cannot search on a field which contains a number.
Here is the data in the index:
```
ts | contents
--------------+-----------------
1236917100 | dog cat gerbil
1236630752 | cow pig goat
1235680249 | lion tiger bear
nonnumeric | bass goby trout
```
**My problem**: A query for "`ts:1236630752`" returns no hits. However, a query for "`ts:nonnumeric`" returns a hit.
I am storing "ts" as a keyword field, which [according to documentation](http://framework.zend.com/apidoc/core/Zend_Search_Lucene/Document/Zend_Search_Lucene_Field.html#keyword) "is not tokenized, but is indexed and stored. Useful for non-text fields, e.g. date or url." I have tried treating it as a "text" field, but the behavior is the same except that a query for "`ts:*`" returns nothing when ts is text.
I'm using Zend Framework 1.7 (just downloaded the latest 3 days ago) and PHP 5.2.9. Here is my code:
```
<?php
//=========================================================
// Initializes Zend Framework (Zend_Loader).
//=========================================================
set_include_path(realpath('../library') . PATH_SEPARATOR . get_include_path());
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
//=========================================================
// Delete existing index and create a new one
//=========================================================
define('SEARCH_INDEX', 'test_search_index');
if(file_exists(SEARCH_INDEX))
foreach(scandir(SEARCH_INDEX) as $file)
if(!is_dir($file))
unlink(SEARCH_INDEX . "/$file");
$index = Zend_Search_Lucene::create(SEARCH_INDEX);
//=========================================================
// Create this data in index:
// ts | contents
// --------------+-----------------
// 1236917100 | dog cat gerbil
// 1236630752 | cow pig goat
// 1235680249 | lion tiger bear
// nonnumeric | bass goby trout
//=========================================================
function add_to_index($index, $ts, $contents) {
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Keyword('ts', $ts));
$doc->addField(Zend_Search_Lucene_Field::Text('contents', $contents));
$index->addDocument($doc);
}
add_to_index($index, '1236917100', 'dog cat gerbil');
add_to_index($index, '1236630752', 'cow pig goat');
add_to_index($index, '1235680249', 'lion tiger bear');
add_to_index($index, 'nonnumeric', 'bass goby trout');
//=========================================================
// Run some test queries and output results
//=========================================================
echo '<html><body><pre>';
function run_query($index, $query) {
echo "Running query: $query\n";
$hits = $index->find($query);
echo 'Got ' . count($hits) . " hits.\n";
foreach($hits as $hit)
echo " ts='$hit->ts', contents='$hit->contents'\n";
echo "\n";
}
run_query($index, 'pig'); //1 hit
run_query($index, 'ts:1236630752'); //0 hits
run_query($index, '1236630752'); //0 hits
run_query($index, 'ts:pig'); //0 hits
run_query($index, 'contents:pig'); //1 hits
run_query($index, 'ts:[1236630700 TO 1236630800]'); //0 hits (range query)
run_query($index, 'ts:*'); //4 hits if ts is keyword, 1 hit otherwise
run_query($index, 'nonnumeric'); //1 hits
run_query($index, 'ts:nonnumeric'); //1 hits
run_query($index, 'trout'); //1 hits
```
**Output**
```
Running query: pig
Got 1 hits.
ts='1236630752', contents='cow pig goat'
Running query: ts:1236630752
Got 0 hits.
Running query: 1236630752
Got 0 hits.
Running query: ts:pig
Got 0 hits.
Running query: contents:pig
Got 1 hits.
ts='1236630752', contents='cow pig goat'
Running query: ts:[1236630700 TO 1236630800]
Got 0 hits.
Running query: ts:*
Got 4 hits.
ts='1236917100', contents='dog cat gerbil'
ts='1236630752', contents='cow pig goat'
ts='1235680249', contents='lion tiger bear'
ts='nonnumeric', contents='bass goby trout'
Running query: nonnumeric
Got 1 hits.
ts='nonnumeric', contents='bass goby trout'
Running query: ts:nonnumeric
Got 1 hits.
ts='nonnumeric', contents='bass goby trout'
Running query: trout
Got 1 hits.
ts='nonnumeric', contents='bass goby trout'
``` | The find() method tokenizes the query, and with the default Analzer your numbers will be pretty much ignored. If you want to search for a number you have to [construct the query](http://framework.zend.com/manual/en/zend.search.lucene.query-api.html) or use an alternate [analyzer](http://framework.zend.com/manual/en/zend.search.lucene.extending.html#zend.search.lucene.extending.analysis) that includes numeric values..
<http://framework.zend.com/manual/en/zend.search.lucene.searching.html>
> It is important to note that the
> query parser uses the standard
> analyzer to tokenize separate parts of
> query string. Thus all transformations
> which are applied to indexed text are
> also applied to query strings.
>
> The standard analyzer may transform
> the query string to lower case for
> case-insensitivity, remove stop-words,
> and stem among other transformations.
>
> The API method doesn't transform or
> filter input terms in any way. It's
> therefore more suitable for computer
> generated or untokenized fields. | I'm used to using Lucene under Java so I can't tell if your code is correct but it seems like the field is being tokanized in a manner that is stripping out anything exept [a-zA-Z].
It may help shed light on the situation to use an index explorer tool like <http://www.getopt.org/luke/> to see exactly what is in the index. | Problem with Lucene- search not indexing numeric values? | [
"",
"php",
"zend-framework",
"lucene",
""
] |
Traditionally, the names of template types are just a single upper-case letter:
```
template<class A, class B, class C>
class Foo {};
```
But I hesitate to do this because it's non-descriptive and hard therefore to read. So, wouldn't something like this be better:
```
template<class AtomT, class BioT, class ChemT>
class Foo {};
```
I also tend to think the following would not be a bad idea:
```
template<class ATOM, class BIO, class CHEM>
class Foo {};
```
It makes them stand out (and also, it's upper-case letters again). What's your opinion? | For C++ templates I have a couple of patterns
If there is just a single template parameter, I name it T (or U,V for nested templates).
When there are multiple parameters and the use is not immediately obvious then I use descriptive names prefixed with T. For example, TKey, TValue, TIdentifiier, etc ... This makes the parameters fairly easy to spot throughout the template usage.
I would avoid the all upper case version though. Most people use all upper case identifiers in C/C++ to represent a macro definition. Repeating that pattern for a template parameter is likely to confuse people down the road. | I use convention TName for the template parameter and NameT for stored template parameter.
```
template <typename TFirst, typename TSecond>
class Templated
{
typedef TFirst FirstT;
typedef TSecond SecondT;
}
typedef Templated<int, std::string> MyTemplated;
...
const MyTemplated::FirstT size;
``` | Naming conventions for template types? | [
"",
"c++",
"templates",
"naming-conventions",
""
] |
I'd like to loop over a list of tables. For each table, I'd like to run an update query.
Psuedo code:
```
ArrayOfTablesObjects = {['tablename1','fieldname1'],['tablename2','fieldname2']......}
foreach @tablename in ArrayOfTablesObjects
UPDATE @tablename
SET @fieldname = 'xyz'
WHERE @fieldname = '123'
end foreach
``` | Thanks Harpo for your answer. I've used that idea to build the following sql statement. We have many tables 50+ that all have the same type of data (employee id) but that field name might be different. So, depending on the table name the field to be updated will be different. My actual WHERE and SET statement are more complicated than this example, but thats not important to this problem.
I first create a temporary table to store the table/fields I want to update.
I then loop over these records, and generate the SQL. For those of you who don't like, dynamic sql, you can just use a print statement and then copy paste that into another query window and execute it. Or you can call the EXEC statement.
I'd like to accept your answers, but then didn't quite answer my question, partly because I didn't explain myself fully. Either way, thanks for your help.
```
DECLARE @TableFieldDictionary TABLE
(
tablename VARCHAR(100),
fieldname varchar(100)
)
insert into @TableFieldDictionary(tablename,fieldname) values ('table1','field1');
insert into @TableFieldDictionary(tablename,fieldname) values ('table2','field2');
--put more insert statements here. In my case, I have 50 inserts
declare cursor_dictionary cursor
for select tablename, fieldname from @TableFieldDictionary
open cursor_dictionary
declare @looptablename VARCHAR(100)
declare @loopfieldname varchar(100)
fetch next from cursor_dictionary
into @looptablename,@loopfieldname
DECLARE @UpdateSql AS varchar(max)
WHILE @@FETCH_STATUS = 0
BEGIN
SET @UpdateSql = 'UPDATE ' + @looptablename +
' SET ' + @loopfieldname + ' = 123' +
' WHERE ' + @loopfieldname + ' = 456'
print @updatesql
--EXEC(@updatesql)
fetch next from cursor_dictionary
into @looptablename,@loopfieldname
END
CLOSE cursor_dictionary
DEALLOCATE cursor_dictionary
``` | You need to use dynamic SQL for this. The EXEC function will execute an ad-hoc sql statement passed in as a string.
```
DECLARE @UpdateSql AS varchar(2000)
foreach @tablename in ArrayOfTablesObjects
SET @UpdateSql = 'UPDATE ' + @tablename + ' SET ' + @fieldname ' + = ''xyz'' WHERE ' + @fieldname + ' = ''123'''
EXEC (@UpdateSql)
end foreach
``` | How do I dynamically set the table and field name in an update query? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to control an instance of the [JW FLV player](http://www.longtailvideo.com/players/jw-flv-player/) player using jquery.
What I want to do is have a series of links which when clicked load an XML playlist into the player.
By following the tutorial [here](http://home5.inet.tele.dk/nyboe/flash/mediaplayer4/JW_API_xmpl_5-2-3-0.html) I've gotten things working basically as I want them in terms of functionality, but even I can see that it's ugly as sin, as at the moment my anchors look like this:
```
<a class="media" href="#"
onclick="player.sendEvent('STOP');
player.sendEvent('LOAD',
'path/to/playlist.xml');
return false;">load playlist</a>
```
while this gets a ref to the player
```
var player = null;
function playerReady(obj)
{
player = gid(obj.id);
};
function gid(name)
{
return document.getElementById(name);
};
```
What I'd like to be able to do is have my anchors look like this:
```
<a class="media" href="#" rel="path/to/playlist.xml">load playlist</a>
```
And then use jquery to find the anchors with class="media", read the value of the element's rel attribute and then bind a click event to it which triggers an appropriate function. Alas this is beyond my extremely meagre powers.
So far I've got:
```
$('a.media').click(function()
{
playlist = $(this).attr("rel");
player.sendEvent('LOAD', playlist
}
);
```
Which clearly doesn't work. Anyone care to help an idiot/n00b?
I should say that really what I want to do is *learn* rather than just get some one else to do it, so if you can explain things a bit that would be extra awesome. | What you're doing seems correct to me, although I'm not sure variable "player" is defined there; it depends on the context.
What you can do is something like
```
$('a.media').click(function () {
var player = $("#player-id");
if(player.length == 1){
player = player[0];
var playlist = $(this).attr("rel");
player.sendEvent('LOAD', playlist);
}
});
``` | ```
player.sendEvent('LOAD', playlist
}
);
```
Check your bracket nesting.
Otherwise, should work. But ‘rel’ isn't a very good place to put a URL, as it is only supposed to contain [known tokens](http://www.w3.org/TR/html4/struct/links.html#adef-rel). Why not put it in ‘href’ where you would expect? You just have to ‘return false’ or ‘preventDefault’ to stop the link being followed after a lick.
```
function playerReady(obj)
{
player = gid(obj.id);
};
function gid(name)
{
return document.getElementById(name);
};
```
Er, isn't gid completely superfluous here? Why not just ‘player= obj’? | Controlling JW FLV player with jQuery | [
"",
"javascript",
"jquery",
"jwplayer",
""
] |
I'm getting an error and I've googled everything I can think of with barely any insights. Maybe you can help with a fresh set of eyes.
I have a function that returns an array of objects. The code that calls this function then loops through this array and does what it needs to do with each object. It seems to work visually when it spits out the HTML, but the server logs still give an error "Invalid argument supplied for foreach()". Yeah, it's great that it works technically, but I don't want this error to pop up anymore. Thoughts?
```
<?php
// The class whose method returns an array of library_Label objects
class library_Label
{
public $id = null;
public $name = null;
public function getChildren()
{
// $children is declared earlier
return $children;
}
}
// main code
$columns = new library_Label(1);
foreach ($columns->getChildren() as $label) echo $label->Name;
?>
``` | This is fairly common, my solution is always to change this:
```
foreach ($columns->getChildren() as $label) echo $label->Name;
```
to
```
$children = $columns->getChildren();
if (is_array($children)) foreach ($children as $label) echo $label->Name;
```
It should cover all situations.
You can expand it to a full if statement with braces as well and then include an else block to handle the situation when children is empty if you want to. | You don't say what language you're using, but that looks like a PHP error. If so, check out PHP's [error reporting levels](https://www.php.net/manual/en/function.error-reporting.php). You should probably actually change the values in your php.ini, though, so that you don't dump out other errors into your server logs.
Of course, you'll want to find out why that error is being thrown regardless. | Error Showing Up in Server Logs...How Do I Stop It? | [
"",
"php",
"arrays",
"foreach",
"invalid-argument",
""
] |
using: VS2008, C#
I have a COM dll I need to use in a .NET project. In there I have a class with a method that returns an IDictionary object. IDictionary is defined in the COM dll so I'm not sure if it's the same as IDictionary in .NET.
My problem: I know the dictionary keys and I want to retrieve the values. The documentation
for this COM dll gives code in Classic ASP like
```
someValue = oMyDictionary.someDictionaryKey
```
My Question: How do I retrieve the values for the specific keys in C#?
When I create the IDictionary object in C# like this:
```
IDictionary oDictConfig = oAppConfig.GetOptionsDictionary("");
```
VS2008 reckons this dictionary object (interface) has the following methods and properties:
```
Cast<>
Count
Equals
GetEnumerator
GetHashCode
GetMultiple
GetType
let_Value
OfType<>
Prefix
PutMultiple
ToString
```
Sorry if this is a silly question, but I can't see how to retrieve a value passing a key. | [IDictionary](http://msdn.microsoft.com/en-us/library/system.collections.idictionary.aspx) has an Item property among its [members](http://msdn.microsoft.com/en-us/library/system.collections.idictionary_members.aspx) that you access via [ ].
```
var obj = oDictConfig[key];
``` | Try this:
```
dicObject["myKey"]
``` | COM Interop IDictionary - How to retrieve a value in C#? | [
"",
"c#",
"interop",
"idictionary",
""
] |
I'm learning PHP and main my concern is adding activity to my website, but I don't know SQL. Is there a way to do this without SQL? | For a quick & dirty solution, you could store user credentials in an array, e.g:
```
$creds = array(
array( 'username' => 'john123',
'password' => 'hello'),
array( 'username' => 'lucyliu',
'password' => 'dieblackmamba')
//more sub arrays like above here
);
```
You can then match the user's input, e.g.:
```
$username = $_POST['username'];
$password = $_POST['password'];
$match = false;
for($i=0;$i<count($creds);$i++) {
if(strcmp($username,$creds[$i]['username']) == 0) {
if(strcmp($password,$creds[$i]['password']) == 0) {
// start session and set something to indicate that user is logged in
session_start();
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $creds[$i]['username'];
$match = true;
}
}
}
if($match) echo 'Login successful: welcome ' . $creds[$i]['username'];
else echo 'Invalid credentials';
```
EDIT: On subsequent page call, you can check if the user is still logged in by reading the $\_SESSION
```
session_start();
if($_SESSION['authenticated'] === true) {
echo 'User ' . $_SESSION['username'] . ' is logged in.';
}
```
To log out the user, you can execute this code:
```
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
```
It would be helpful for you to read about php [sessions](http://php.net/session) and [arrays](http://php.net/array), and if I were you I would bite the bullet and try to get into SQL. | You can probably use flat files - only concern might be parallel adding of new accounts. But if you want to dig deeper in website development, SQL is definitely good to dive into. | how to add login/logout function and register without sql | [
"",
"php",
""
] |
I'm trying to understand Python's approach to variable scope. In this example, why is `f()` able to alter the value of `x`, as perceived within `main()`, but not the value of `n`?
```
def f(n, x):
n = 2
x.append(4)
print('In f():', n, x)
def main():
n = 1
x = [0,1,2,3]
print('Before:', n, x)
f(n, x)
print('After: ', n, x)
main()
```
Output:
```
Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3, 4]
```
---
See also:
* [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006)
* [Are Python variables pointers? Or else, what are they?](https://stackoverflow.com/questions/13530998/are-python-variables-pointers-or-else-what-are-they) | Some answers contain the word "copy" in the context of a function call. I find it confusing.
**Python doesn't copy *objects* you pass during a function call *ever*.**
Function parameters are *names*. When you call a function, Python binds these parameters to whatever objects you pass (via names in a caller scope).
Objects can be mutable (like lists) or immutable (like integers and strings in Python). A mutable object you can change. You can't change a name, you just can bind it to another object.
Your example is not about [scopes or namespaces](https://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces), it is about [naming and binding](http://docs.python.org/reference/executionmodel.html#naming-and-binding) and [mutability of an object](http://docs.python.org/reference/datamodel.html#objects-values-and-types) in Python.
```
def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
n = 2 # put `n` label on `2` balloon
x.append(4) # call `append` method of whatever object `x` is referring to.
print('In f():', n, x)
x = [] # put `x` label on `[]` ballon
# x = [] has no effect on the original list that is passed into the function
```
Here are nice pictures on [the difference between variables in other languages and names in Python](https://web.archive.org/web/20180121150727/http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables). | You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:
Any time you see **`varname =`**, you're creating a *new* name binding within the function's scope. Whatever value `varname` was bound to before is lost *within this scope*.
Any time you see **`varname.foo()`** you're calling a method on `varname`. The method may alter varname (e.g. `list.append`). `varname` (or, rather, the object that `varname` names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.
[note that the `global` keyword creates an exception to the first case] | Why can a function modify some arguments as perceived by the caller, but not others? | [
"",
"python",
"scope",
""
] |
Python discourages checking the types. But in many cases this may be useful:
1. Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.
2. Checking functions arguments.
3. In properties. If someone sets a wrong value or different type, I should respond quickly. | The simple answer is **No**, use Polymorphism, Exceptions etc.
1. In the case of constructor arguments being of the wrong type, an exception will be thrown when executing code that depend s on the parameter being of a particular type. If it is a weird, domain specific thing, raise your own Exception. Surround blocks of code which are likely to fail with try-except and handle errors. So it is better to use Exception handling. (*Same goes for function arguments*)
2. In properties, the same argument applies. If you are validating the value received, use an assertion to check its range etc. If the value is of the wrong type, it will fail anyway. Then, handle AssertionError.
In Python, you treat programmers as intelligent beings!! Just document your code well (make things obvious), raise Exceptions where appropriate, write polymorphic code etc. Leave the Exception handling(where it is appropriate only)/errors in construction to the client code.
**Warning**
Leaving Exception handling to clients doesn't mean that you should chuck a lot of garbage errors at the unwitting user. If at all possible, handle exceptions that might occur due to bad construction or any other reason in your code itself. Your code should be robust. Where it is impossible for you to handle the error, politely inform the user/client code programmer!
**Note**
In general, bad arguments to a constructor isn't something I worry about too much. | The answer is almost always "no". The general idea in Python, Ruby, and some other languages us called "[Duck Typing](http://en.wikipedia.org/wiki/Duck_typing)". You shouldn't care what something is, only how it works. In other words, "if all you want is something that quacks, you don't need to check that it's actually a duck."
In real life, the problem with putting in all those type checks is the inability to replace inputs with alternate implementations. You may check for dict, but I may want to pass something in which is not a dict, but implements the dict API.
Type checking only checks for one of many possible errors in code. For example, it doesn't include range checking (at least not in Python). A modern response to the assertion that there needs to be type checking is that it's more effective to develop unit tests which ensure that not only are the types correct, but also that the functionality is correct.
Another viewpoint is that you should treat your API users like consenting adults, and trust them to use the API correctly. Of course there are times when input checking is helpful, but that's less common than you think. One example is input from untrusted sources, like from the public web. | Should I check the types of constructor arguments (and at other places too)? | [
"",
"python",
"typechecking",
""
] |
Let's say that in my app I have an object instance created on page 1. The user then goes to some other part of app and I want the instance to remain. How can I 'save' the instance? Sessions? | Yes, use a [session](http://uk.php.net/manual/en/features.sessions.php).
Call [session\_start()](http://php.net/session_start) at the beginning of your page, then store your object with something like `$_SESSION['myobject']=$myobject;`
The later page can access `$_SESSION['myobject']` after it too calls session\_start()
You need to make sure that any page which uses that session has the class for the object defined or is capable of [auto-loading](http://uk.php.net/manual/en/language.oop5.autoload.php) it.
Your class can also define the magic methods [\_\_sleep](http://uk.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep) and [\_\_wakeup](http://uk.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep) which allow you to clean up any member variables you don't want serializing (like resources, such as db handles). During \_\_wakeup you can restore these. | There are two ways I have used for my applications: sessions and database. | PHP object keeping | [
"",
"php",
"session",
"object",
"instance",
""
] |
I have a problem: how can I delete a line from a text file in C#? | Read the file, remove the line in memory and put the contents back to the file (overwriting). If the file is large you might want to read it line for line, and creating a temp file, later replacing the original one. | For *very* large files I'd do something like this
```
string tempFile = Path.GetTempFileName();
using(var sr = new StreamReader("file.txt"))
using(var sw = new StreamWriter(tempFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
if(line != "removeme")
sw.WriteLine(line);
}
}
File.Delete("file.txt");
File.Move(tempFile, "file.txt");
```
**Update** I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using [LINQ and deferred execution](https://web.archive.org/web/20160214193352/http://blogs.msdn.com:80/b/charlie/archive/2007/12/09/deferred-execution.aspx)
```
var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(fileName);
File.Move(tempFile, fileName);
```
The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.
A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.
```
File.WriteAllLines(fileName,
File.ReadLines(fileName).Where(l => l != "removeme").ToList());
```
Note that The `.ToList` is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded. | How to delete a line from a text file in C#? | [
"",
"c#",
"text-files",
""
] |
For public members I get a warning "missing XML comment for publicly visible type or member ...". That is great, but not enough. I would like to enable this warning for all (or at least internal and protected) members.
Is there a way to get a warning or information about missing xml comments? Are there any tools at runtime (like Resharper) with that feature? | [StyleCop (aka MS SourceAnalysis)](http://code.msdn.microsoft.com/sourceanalysis/) can do this for you. Here is the [team's blog](http://blogs.msdn.com/sourceanalysis/) where you can read more about it. | If you are using ReSharper use Agent Smith plugin for ReSharper.
It's open source so feel free to see what goo they have in there.
[Agent Smith HomePage](http://www.agentsmithplugin.com/)
[Agent Smith source code on Google Code](http://agentsmithplugin.googlecode.com/)
EDIT: Agent Smith does xml comments validation at code editor runtime(for the lack of the better word) | Force xml comment for all members | [
"",
"c#",
"visual-studio",
""
] |
I was going to create the C++ IDE **Vim** extendable **plugin**. It is not a problem to make one which will satisfy my own needs.
This plugin was going to work with workspaces, projects and its dependencies.
This is for unix like system with **gcc** as c++ compiler.
So my question is what is the most important things you'd need from an IDE? Please take in account that this is Vim, where almost all, almost, is possible.
*Several questions:*
How often do you manage different workspaces with projects inside them and their relationships between them? What is the most annoying things in this process.
Is is necessary to recreate "project" from the Makefile?
Thanks.
*Reason to create this plugin:*
With a bunch of plugins and self written ones we can simulate most of things. It is ok when we work on a one big "infinitive" project.
Good when we already have a makefile or jam file. Bad when we have to create our owns, mostly by copy and paste existing.
All ctags and cscope related things have to know about list of a real project files. And we create such ones. This <project#get\_list\_of\_files()> and many similar could be a good project api function to cooperate with an existing and the future plugins.
Cooperation with an existing makefiles can help to find out the list of the real project files and the executable name.
With plugin system inside the plugin there can be different project templates.
Above are some reasons why I will start the job. I'd like to hear your one. | * debugger
* source code navigation tools (now I am using <http://www.vim.org/scripts/script.php?script_id=1638> plugin and ctags)
* compile lib/project/one source file from ide
* navigation by files in project
* work with source control system
* easy acces to file changes history
* rename file/variable/method functions
* easy access to c++ help
* easy change project settings (Makefiles, jam, etc)
* fast autocomplette for paths/variables/methods/parameters
* smart identation for new scopes (also it will be good thing if developer will have posibility to setup identation rules)
* highlighting incorrect by code convenstion identation (tabs instead spaces, spaces after ";", spaces near "(" or ")", etc)
* reformating selected block by convenstion | There are multiple problems. Most of them are already solved by independent and generic plugins.
## Regarding the definition of what is a *project*.
Given a set of files in a same directory, each file can be the unique file of a project -- I always have a tests/ directory where I host pet projects, or where I test the behaviour of the compiler. On the opposite, the files from a set of directories can be part of a same and very big project.
In the end, what really defines a project is a (leaf) "makefile" -- And why restrict ourselves to makefiles, what about scons, autotools, ant, (b)jam, aap? And BTW, Sun-Makefiles or GNU-Makefiles ?
Moreover, I don't see any point in having vim know the exact files in the current project. And even so, the well known [project.vim plugin](http://www.vim.org/scripts/script.php?script_id=69) already does the job. Personally I use a [local\_vimrc plugin](https://github.com/LucHermitte/local_vimrc) (I'm maintaining one, and I've seen two others on SF). With this plugin, I just have to drop a \_vimrc\_local.vim file in a directory, and what is defined in it (:mappings, :functions, variables, :commands, :settings, ...) will apply to each file under the directory -- I work on a big project having a dozen of subcomponents, each component live in its own directory, has its own makefile (not even named Makefile, nor with a name of the directory)
## Regarding C++ code understanding
Every time we want to do something complex (refactorings like rename-function, rename-variable, generate-switch-from-current-variable-which-is-an-enum, ...), we need vim to have an understanding of C++. Most of the existing plugins rely on ctags. Unfortunately, ctags comprehension of C++ is quite limited -- I have already written a [few advanced things](https://github.com/LucHermitte/lh-cpp), but I'm often stopped by the poor information provided by ctags. cscope is no better. Eventually, I think we will have to integrate an advanced tool like elsa/pork/ionk/deshydrata/....
NB: That's where, now, I concentrate most of my efforts.
## Regarding Doxygen
I don't known how difficult it is to jump to the doxygen definition associated to a current token. The first difficulty is to understand what the cursor is on (I guess omnicppcomplete has already done a lot of work in this direction). The second difficulty will be to understand how doxygen generate the page name for each symbol from the code.
Opening vim at the right line of code from a doxygen page should be simple with a greasemonkey plugin.
## Regarding the debugger
There is the [pyclewn project](http://pyclewn.wiki.sourceforge.net/) for those that run vim under linux, and with gdb as debugger. Unfortunately, it does not support other debuggers like dbx.
## Responses to other requirements:
> * When I run or debug my compiled program, I'd like the option of having a dialog pop up which asks me for the command line parameters. It should remember the last 20 or so parameters I used for the project. I do not want to have to edit the project properties for this.
My [BuildToolsWrapper plugin](https://github.com/LucHermitte/vim-build-tools-wrapper) has a `g:BTW_run_parameters` option (easily overridden with project/local\_vimrc solutions). Adding a mapping to ask the arguments to use is really simple. (see :h inputdialog())
> * work with source control system
There already exist several plugins addressing this issue. This has nothing to do with C++, and it must not be addressed by a C++ suite. | C++ vim IDE. Things you'd need from it | [
"",
"c++",
"vim",
"ide",
""
] |
I am trying to do many different queries on a result set which has a *very* large creation time. To get performance gains I wish to use a temp table and just do many queries on this temp table.
Seems pretty standard. Yet I am struggling to share this temp table in dynamic SQL. As I understand it, each SqlCommand object executes in its own thread and so the temp table is in a different scope - thus making it inaccessible from the query thread.
I tried using a global temporary table and that works great, but not ideal?
How can I share a local temporary table between dynamic SQL queries?
My intent:
```
using (var conn = new SqlClient.SqlConnection("..."))
{
// Creation involes many table joins in reality
String creationScript = "SELECT * FROM FooTable INTO #MyTemp";
SqlCommand createTempTbl = new SqlCommand(creationScript, conn);
createTempTbl.ExecuteNonQuery();
String query1 = "SELECT * FROM #MyTemp where id=@id";
SqlCommand query1Comm = new SqlCommand(query1, conn);
query1Comm.Parameters.Add("@id", ...);
String query2 = "SELECT * FROM #MyTemp where name=@name";
SqlCommand query2Comm = new SqlCommand(query2, conn);
query2Comm.Parameters.Add("@name", ...);
// And so on the queries go
} // Now want #MyTemp to be destroyed
``` | You could try using a global temporary table (ie, use `##MyTemp` rather than `#MyTemp` in your queries), [with this caveat](http://msdn.microsoft.com/en-us/library/ms174979.aspx):
> Global temporary tables are
> automatically dropped when the session
> that created the table ends and all
> other tasks have stopped referencing
> them. The association between a task
> and a table is maintained only for the
> life of a single Transact-SQL
> statement. This means that a global
> temporary table is dropped at the
> completion of the last Transact-SQL
> statement that was actively
> referencing the table when the
> creating session ended.
---
**EDIT:** Oops, missed the fact that you've already tried global temp tables.
How about moving all of your logic into a single stored procedure which creates/populates the temp table and then runs the queries and returns multiple resultsets to the client code? | I know it's a while since this one was posted but the answer, I believe, is quite simple.
I surmise you are using the MS Enterprise Library to access the database, this explains why the temp table doesn’t exist between commands. The Enterprise Library EXPLICITLY closes the connection to the DB (puts it back in the pool) when the command finishes. That is, UNLESS you put the commands into a transaction.
If you use ADO.NET directly (by opening the connection, building and executing the commands, then closing the connection) you do not get this problem (it’s up to you when the connection closes – which is more risky).
Here is some code written using the MS Enterprise Library and a transaction (sorry, VB.NET):
```
' Get a reference to the database
Dim sqlNET As New Sql.SqlDatabase("*Your Connection String Here...*")
' Specify the transaction options
Dim oTranOpt As TransactionOptions = New TransactionOptions
' What type of isolation the transaction should have (V. Important):
oTranOpt.IsolationLevel = IsolationLevel.ReadUncommitted ' This one doesn't place locks on DB but allows dirty reads
' How long the transaction has to complete before implicitly failing (h,m,s):
oTranOpt.Timeout = New TimeSpan(0, 0, 30)
' Start the scope of the transation
Using oTranScope As TransactionScope = New TransactionScope(TransactionScopeOption.Required, oTranOpt)
' Create the connection to the DB. Not abs. necessary. EL will create one but best to do so.
Using Conn As Common.DbConnection = sqlNET.CreateConnection
' Create a Temp Table
sqlNET.ExecuteNonQuery(CommandType.Text, "SELECT * INTO #MyTemp FROM FooTable")
' Get results from table, e.g.
Dim intCount As Integer = sqlNET.ExecuteScalar(CommandType.Text, "Select Count(*) from #MyTemp")
MsgBox(intCount)
' Flag transaction as successful (causes a commit when scope is disposed)
oTranScope.Complete()
End Using ' Disposes the connection
End Using ' If this point is reached without hitting the oTranScope.Complete - the transaction is rolled back and locks, if any, are released.
```
If you were to take out the transaction scope, the code would fail on the Select count(\*) as the table no longer exists. Specifying the scope keeps the connection open between command calls.
I hope this helps someone.
Neil. | SQL temp table sharing across different SQL readers | [
"",
".net",
"sql",
"sql-server-2005",
"ado.net",
"dynamic-sql",
""
] |
A certain site I know recently upgraded their bandwith from 2,5 TB monthly to 3,5 TB.
Reason is they went over the 2,5 limit recently. They're complaining they don't know how to get down the bandwidth usage.
One thing I haven't seen them consider is the fact that JPEG and other images that are displayed on the site(and it is an image-heavy site) can contain metadata. Where the picture was taken and such.
Fact of the matter is, this information is of no importance whatsoever on that site. It's not gonna be used, ever. Yet it's still adding to the bandwidth, since it increases the filesize of every images from a few bytes to a few kilobytes.
On a site that uses up more then 2,5 TB per month, stripping the several thousands images of their metadata will help decrease the bandwidth usage at least by a few Gigabytes per month I think, if not more.
So is there a way to do this in PHP? And also, for the allready existing files, does anybody know a **good** automatic metadata remover? I know of [JPEG & PNG Stripper](http://www.steelbytes.com/?mid=30), but that's not very good... Might be usefull for initial cleaning though... | Check out **[Smush.it!](http://smush.it/)** It will strip all un-necs info from an image. They have an **[API](http://smush.it/faq.php#results-table)** you can use to crunch the images.
**Note:** *By Design*, it ***may*** change the filetype on you. This is on purpose. If another filetype can display the same image with the same quality, with less bytes it will give you a new file. | It's trivial with GD:
```
$img = imagecreatefromjpeg("myimg.jpg");
imagejpeg($img, "newimg.jpg", $quality);
imagedestroy($img);
```
This won't transfer EXIF data. Don't know how much bandwidth it will actually save, though, but you could use the code above to increase the compression of the images. That would save *a lot* of bandwidth, although it possibly won't be very popular. | Having an image stripped of metadata upon upload in PHP | [
"",
"php",
"file-upload",
"metadata",
"vbulletin",
""
] |
What is the clearest way to comma-delimit a list in Java?
I know several ways of doing it, but I'm wondering what the best way is (where "best" means clearest and/or shortest, not the most efficient.
I have a list and I want to loop over it, printing each value. I want to print a comma between each item, but not after the last one (nor before the first one).
```
List --> Item ( , Item ) *
List --> ( Item , ) * Item
```
Sample solution 1:
```
boolean isFirst = true;
for (Item i : list) {
if (isFirst) {
System.out.print(i); // no comma
isFirst = false;
} else {
System.out.print(", "+i); // comma
}
}
```
Sample solution 2 - create a sublist:
```
if (list.size()>0) {
System.out.print(list.get(0)); // no comma
List theRest = list.subList(1, list.size());
for (Item i : theRest) {
System.out.print(", "+i); // comma
}
}
```
Sample solution 3:
```
Iterator<Item> i = list.iterator();
if (i.hasNext()) {
System.out.print(i.next());
while (i.hasNext())
System.out.print(", "+i.next());
}
```
These treat the first item specially; one could instead treat the last one specially.
Incidentally, here is how `List` `toString` *is* implemented (it's inherited from `AbstractCollection`), in Java 1.6:
```
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
```
It exits the loop early to avoid the comma after the last item. BTW: this is the first time I recall seeing "(this Collection)"; here's code to provoke it:
```
List l = new LinkedList();
l.add(l);
System.out.println(l);
```
I welcome any solution, even if they use unexpected libraries (regexp?); and also solutions in languages other than Java (e.g. I think Python/Ruby have an *intersperse* function - how is *that* implemented?).
*Clarification*: by libraries, I mean the standard Java libraries. For other libraries, I consider them with other languages, and interested to know how they're implemented.
*EDIT* toolkit mentioned a similar question: [Last iteration of enhanced for loop in java](https://stackoverflow.com/questions/285523/last-iteration-of-for-loop-in-java)
And another:
[Does the last element in a loop deserve a separate treatment?](https://stackoverflow.com/questions/156650/does-the-last-element-in-a-loop-deserve-a-separate-treatment) | # Java 8 and later
Using [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html) class, and [`forEach`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-) method :
```
StringJoiner joiner = new StringJoiner(",");
list.forEach(item -> joiner.add(item.toString());
return joiner.toString();
```
Using [`Stream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), and [`Collectors`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html):
```
return list.stream().
map(Object::toString).
collect(Collectors.joining(",")).toString();
```
# Java 7 and earlier
See also [#285523](https://stackoverflow.com/questions/285523/last-iteration-of-for-loop-in-java/285628#285628)
```
String delim = "";
for (Item i : list) {
sb.append(delim).append(i);
delim = ",";
}
``` | ```
org.apache.commons.lang3.StringUtils.join(list,",");
``` | The simplest way to comma-delimit a list? | [
"",
"java",
"pretty-print",
""
] |
I'm posting this question on it's own as I found post one which lacks full explanation or the best way to do it.
Should I use a language file to name items like:
$first\_name= 'name';
$last\_name = 'last\_name';
and then include this file depending on selection?
I have an app which I need to have in two languages.
Will like something in this lines:
<http://www.myapp.com/?lang=en>
<http://www.myapp.com/?lang=es>
Should I use a constants file for this purpose?
constants.php
define('OPERATION\_NOT\_ALLOWED\_EN', 'This operation is not allowed!');
define('OPERATION\_NOT\_ALLOWED\_ES', 'This operation is not allowed!');
What is the recommended way of accomplishing this? | You can follow in the footsteps of phpBB - they use a `$lang[]` array with code that looks like:
```
$lang['Next'] = 'Next';
$lang['Previous'] = 'Previous';
$lang['Goto_page'] = 'Goto page';
$lang['Joined'] = 'Joined';
$lang['IP_Address'] = 'IP Address';
$lang['Select_forum'] = 'Select a forum';
$lang['View_latest_post'] = 'View latest post';
$lang['View_newest_post'] = 'View newest post';
$lang['Page_of'] = 'Page <b>%d</b> of <b>%d</b>'; // Replaces with: Page 1 of 2 for example
$lang['ICQ'] = 'ICQ Number';
$lang['AIM'] = 'AIM Address';
$lang['MSNM'] = 'MSN Messenger';
$lang['YIM'] = 'Yahoo Messenger';
```
It is of course included from a file specified in the user's settings, but you'd be fine with your suggestion of `?lang=en` in the query string accessing something similar to a `constants.php` file.
You might want to name the file `lang_en.php` or something similar for clarity. | That will work for strings like you gave in your example. But there are other complications. For example, do you want to format dates in the appropriate format for the locale (es vs en?). How about formatting of numbers and currencies? Also, you might have "dynamic" messages: "You have $x messages in your inbox". Where you want to pass variables. Check out some of the php localization libraries. Here is an online tutorial: <http://www.devx.com/webdev/Article/38732>.
Also look at the framework you are using. Many of them have localization support. | How to Implement multi language in PHP application? | [
"",
"php",
"internationalization",
"translation",
""
] |
I have files with tons of real time data that I process with an C# application. After processing the data it is presented in Excel using a specific template.
This is solved using Interop today. I must say I don't completely gasp the whole Interop situation. Do I have to manually install the Interop functionality on each end user terminal somehow? How does it handle the mix of 2003/2007 versions? | If you know the structure of your Excel document (and presuming you don't want and kind of complex macros/ functions/ etc within the Excel document) you can generate XML using the Excel XML format. **I'm not referring to OpenXML, I'm referring to the XML format used by Excel prior to 2007.**
I cover how to do it here: <http://www.aaron-powell.com//blog/september-2008/linq-to-xml-to-excel.aspx>
The problem with Interop is that it isn't really designed to hard core document generation. If you try and do a lot of document processing you can run into locks | I've always used [FileHelpers](http://filehelpers.sourceforge.net/). You shouldn't have to do anything with the Excel installation. | Getting data from C# to Excel 03/07 | [
"",
"c#",
".net",
"excel",
"interop",
""
] |
I have a php web application where certain data changes on a weekly basis but is read very frequently often.
The SQL queries that retrieve the data and the php code for html output are fairly complex. There are multiple table joins, and numerous calculations - but they result in a fairly basic html table. Users are grouped, and the table is the same for each group each week, but different for different groups. I could potentially have hundreds of tables for thousands of users.
For performance reasons, I'd like to cache this data. Rather than running these queries and calculations every time someone hits the page, I want to run a weekly process to generate the table for each group giving me a simple read when required.
I'd be interested to know what techniques you've used successfully or unsuccessfully to achieve something like this?
Options I can see include:
* Storing the html result of the calculations in a MySQL table, identified by user group
* Storing the resultant data in a MySQL table, identified by user group (difficult as there's no fixed number of data items)
* Caching the page output in static files
Any other suggestions would be welcome! | There are indeed a few options:
* Prerender the pages on a weekly basis and then serve them "statically".
* Use a cache (e.g. [Squid](http://www.squid-cache.org/)) to cache such responses on a first-chance basis for a week. For example, you can configure the caching policy so requests that go to a particular page (e.g. very\_long.php?...) are cached separately from the rest of the website.
* Make sure you turn on DB caching. MySQL has caching of its own and you can fine tune it so that repeated long queries are not recalculated. | In the function to generate the table, make it store the result to a file on disk:
```
/cache/groups/1.txt
/cache/groups/2.txt
```
You don't necessarily have to run a weekly batch job for it, when calling the function to get the data, check if the cache is out of date (or non-existent). If so, generate and cache the results then. If not, just return the cached file.
```
function getGroupTable($groupId) {
if (cacheIsStale($groupId)) {
generateCache($groupId);
}
return file_get_contents($cacheFile);
}
```
The `cacheIsStale()` function could just look at the [file's timestamps](https://www.php.net/manual/en/function.filemtime.php) to test for freshness. | Best technique for caching results from queries that change infrequently | [
"",
"php",
"mysql",
"caching",
""
] |
I wrote this:
```
var destinations = db.DestinationDetails.
Where(dd => dd.Language.Lang == "en-US" &&
dd.Destination.Client.Any(c => c.Email == "abc@yahoo.com"));
```
How can I retrieve destinationDetails that client with email abc@yahoo.com doesn't have?
This doesn't work:
```
var destinations = db.DestinationDetails.
Where(dd => dd.Language.Lang == "en-US" &&
dd.Destination.Client.Any(c => c.Email != "abc@yahoo.com"));
```
Thanks! | I think you want to use All instead of Any:
```
dd.Destination.Client.All(c => c.Email != "abc@yahoo.com")
``` | Try
```
var destinations = db.DestinationDetails.
Where(dd => dd.Language.Lang == "en-US" &&
!dd.Destination.Client.Any(c => c.Email == "abc@yahoo.com"));
``` | LinQ to Entities: Doing the opposite query | [
"",
"c#",
"entity-framework",
"linq-to-entities",
""
] |
I cannot bind the Visible property of the WPF datagridtextcolumn to a boolean value.
My binding expression is,
```
{Binding Path=DataContext.IsThisColumnVisible, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window},Converter={StaticResource vc}}
```
I have checked that the converter works (bool to the visibility enum) and is in scope.
If I use the same expression for the header of the column, the header displays 'false' as expected.
Visible is a dependency property so should be bindable.
Anyone see what Im doing wrong? Or has anyone else been able to bind to the visible property.
Regards,
Matt | I worked this out.
DataGridCOlumn is not a framework element so the FindAncestor call was failing (DataGridColumn not part of visual tree)
Have to set source property of binding expression to a staticresource and it works fine. | Hard to say from so little of your code. What is in Visual Studio's Output window (under Debug)? That will often give you a clue as to the problem. | Binding Visible property of a DataGridColumn in WPF DataGrid | [
"",
"c#",
"wpf",
"data-binding",
""
] |
Are setters necessary for Collection Type Properties
```
//Type 1
class Company
{
private IList<Customer> customers;
public IList<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
}
//Type 2
class Company
{
private readonly IList<Customer> customers = new List<Customer>();
public IList<Customer> Customers
{
get { return customers; }
}
}
```
When do I use Type 1 vs Type 2 ?
Wouldn't it suffice if I initialize a List & use readonly property Customers ? as in `Company.Customers.Add(new Customer)`
What is the best practice with respect to providing setters for collection Type properties? | Please read the FxCop recommondation CAS2227 "Collection properties should be read only"
<http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx>
it contains good advice :) | Not in general (and I don't normally add them), but they are necessary if you want to use `XmlSerializer`. Which is a pain. It must also be a concrete type (for example `List<T>` or `T[]` - not `IList<T>`). Fortunately, `DataContractSerializer` doesn't suffer the same fate. | Setters for collection type properties | [
"",
"c#",
"oop",
"collections",
""
] |
I've got a Canvas with a few UIElements on. After I've moved them on the canvas by animating the top and left properties, very occasionally a subsiquent call to Canvas.GetTop results in NaN.
Am I not 'closing' the animations properly?
Here's how I'm doing the move
```
private void InternalMove(double durationMS, FrameworkElement fElement, Point point, EventHandler callback)
{
_moveElement = fElement;
_destination = point;
Duration duration = new Duration(TimeSpan.FromMilliseconds(durationMS));
DoubleAnimation moveLeftAnimation = new DoubleAnimation(Canvas.GetLeft(fElement), point.X, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(moveLeftAnimation, new PropertyPath("(Canvas.Left)"));
DoubleAnimation moveTopAnimation = new DoubleAnimation(Canvas.GetTop(fElement), point.Y, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(moveTopAnimation, new PropertyPath("(Canvas.Top)"));
// Create a storyboard to contain the animation.
_moveStoryboard = new Storyboard();
if (callback != null) _moveStoryboard.Completed += callback;
_moveStoryboard.Completed += new EventHandler(s1_Completed);
_moveStoryboard.Children.Add(moveLeftAnimation);
_moveStoryboard.Children.Add(moveTopAnimation);
_moveStoryboard.FillBehavior = FillBehavior.Stop;
_moveStoryboard.Begin(fElement);
}
private void s1_Completed(object sender, EventArgs e)
{
if (_moveStoryboard != null)
{
_moveStoryboard.BeginAnimation(Canvas.LeftProperty, null, HandoffBehavior.Compose);
_moveStoryboard.BeginAnimation(Canvas.TopProperty, null, HandoffBehavior.Compose);
}
Canvas.SetLeft(_moveElement, _destination.X);
Canvas.SetTop(_moveElement, _destination.Y);
}
```
thanks | It seems than `Canvas.GetTop(x)` can return 'Nan' if the value is not explictly set (even tho I do explicitly set it I still sometimes get that result).
An alternative method I'm now using is
```
Vector offset = VisualTreeHelper.GetOffset(fElement);
```
which returns the position of fElement within it's container. | I've run into a similar situation (NaN), but in a different context. As I recall, it had something to do with how the element was positioned in the container.
Sorry I couldn't provide more help, but maybe this will provide some guidance. | Canvas.GetTop() returning NaN | [
"",
"c#",
"wpf",
""
] |
Recently, I have identified very strong code smell in one of the project, I'm working for.
Especially, in its cost counting feature. To count the total cost for some operation, we have to pass many kind of information to the "parser class".
For example:
* phone numbers
* selected campaigns
* selected templates
* selected contacts
* selected groups
* and about 2-4 information types more
Before refactoring there were all this parameters were passed through constructor to the Counter class(8 parameters, you can image that..).
To increase readability I have introduced a Data class, named CostCountingData with readable getters and setters to all this properties.
But I don't think, that that code became much readable after this refactoring:
```
$cost_data = new CostCountingData();
$cost_data->setNumbers($numbers);
$cost_data->setContacts($contacts);
$cost_data->setGroups($groups);
$cost_data->setCampaigns($campaigns);
$cost_data->setUser($user);
$cost_data->setText($text);
$cost_data->setTotalQuantity($total_quantity);
$CostCounter = new TemplateReccurentSendingCostCounter($cost_data);
$total_cost = $CostCounter->count();
```
Can you tell me whether there is some problem with readability of this code snippet?
Maybe you can see any code smells and can point me at them..
The only idea I have how to refactore this code, is to split this big data object to several, consisting related data types. But I'm not sure whether should I do this or not..
Whay do you think about it? | There are a few possibilities here:
* If you only need a few of the parameters each time, the [named parameter approach](https://stackoverflow.com/questions/669081/too-big-data-objects/669104#669104) suggested elsewhere in this answer is a nice solution.
* If you always need all of the parameters, I would suggest that the smell is coming from **a broken semantic model of the data required to calculate a cost**.
No matter how you dress up a call to a method that takes eight arguments, the fact that eight supposedly unrelated pieces of information are required to calculate something will always smell.
Take a step back:
* Are the eight separate arguments *really* all unrelated, or can you compose intermediate objects that reflect the reality of the situation a little better? Products? invoice items? Something else?
* Can the cost method be split into smaller methods that calculate part of the cost based on fewer arguments, and the total cost produced from adding up the component costs? | If what you want is named parameters (which it looks to me is what you are trying to achieve), would you ever consider just passing in an associative array, with the names as keys? There is also the Named Parameter Idiom, [I can only find a good reference for this for C++ though](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.18), perhaps it's called something else by PHP programmers.
For that, you'd change your methods on CostCountingData so they all returned the original object. That way you could rewrite your top piece of code to this:
```
$cost_data = new CostCountingData();
$cost_data
->setNumbers($numbers)
->setContacts($contacts)
->setGroups($groups)
->setCampaigns($campaigns)
->setUser($user)
->setText($text)
->setTotalQuantity($total_quantity);
```
So there's two options. I would probably go for the named parameter idiom myself as it is self-documenting, but I don't think the difference is too great. | Too big data objects | [
"",
"php",
"refactoring",
""
] |
I'm new in windows application development using java. The question is this "How to i bind events to custom class methods?
As fas i have seen i can register listener classes to swing components to handle events. That is OK but i have to implement a class that implements e.g. the ActionListener interface to handle an event and then implement the actionPerformed method. That means ONE class FOR each event i have to handle?
Can't i have ONE class "listening" for events from all components and have each method in this class do the event handling?"
An example:
```
class MyEventListener { //pseudo code [no constructors, etc]
public void handleSubmitFormBtn(Event e) {
}
//other methods go here handling events from other swing components
}
```
Note: I am not sure about the method signature but i hope that you get the point.
Conclusion: ONE method to handle events fired from swing components..is it possible? Is the creation of ONE class for each the event the only way? Can't i route event handling to specific methods for a single class? | You have a few choices, each with their particular benefits/drawbacks.
**anonymous inner classes**
```
component.addActionListener(
new ActionListener()
{
public void actionPerformed(final ActionEvent e)
{
outerClassesMethod();
}
});
```
**inner class**
```
class Foo
implements ActionListener
{
public void actionPerformed(final ActionEvent e)
{
outerClassMethod();
}
}
```
**outer class**
```
public class Foo
implements ActionListener
{
private final OuterClass target;
public Foo(final OuterClass t)
{
target = t;
}
public void actionPerformed(final ActionEvent e)
{
target.targetClassMethod();
}
}
```
**class implements listener**
```
public class OuterClass
implements ActionListener
{
public void actionPerformed(final ActionEvent e)
{
method();
}
// somewhere else in the code
{
component.addActionListener(this);
}
}
```
Each way has good and bad to it.
The anonymous inner class will not allow you to do what you are asking, it can only implement one listener.
The other three will all allow you to do what you want (just add , WindowListener to the implements list for exaple). You likely want the inner class or outer class implementing the listener way to do what you want. I suggest that because the listener is likely very highly coupled to your program, and you will need to do a large set of "if" statements to figure out which control was acted on to perform the actual action (you use evt.getSource() to figure out which control was being acted on and then comare it to your instance variables to see which it was).
However, unless you are in memory constrained device, such as an Android phone, you probably should not do one method for all listeners as it can easily lead to very bad code. If memory is an issue, then go for it, but if it isn't you are better of doing one of the following things:
* one listener class per control
* one listener class per event type for all controls
* one listener class per control per event type
I prefer to code the following way, I find it to be the most flexible:
```
public class Outer
extends JFrame
{
private final JButton buttonA;
private final JButton buttonB;
{
buttonA = new JButton("A");
buttonB = new JButton("B");
}
// do not put these in the constructor unless the Outer class is final
public void init()
{
buttonA.addActionListener(new AListener());
buttonB.addActionListener(new BListener());
}
private void aMethod()
{
}
private void bMethod()
{
}
public void AListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
aMethod();
}
}
public void BListener
implements ActionListener
{
public void actionPerformed(final ActionEvent evt)
{
bMethod();
}
}
}
```
I prefer this way because it forces the methods out of the listeners, which means I only have one place to look for the code (not scattered throughout the inner classes). It also means that it is possible that aMethod() and bMethod() can be reused - if the code is in a listener that isn't practical (it is possible, but not worth the effort).
Doing it the above way is also consistent, and I prefer consistency over most things unless there is a good reason not do it. For instance on the Android I do not do that since class creation is expensive (I still have the listener call methods only, but the class itself implements the listeners and I do an if statement). | In swing what you usually do is use an anonymous class to handle your events, like so:
```
someControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event
}
});
```
Although you can basically have one class handling all your events, and register it to all handlers, anonymous classes, as mentioned above, are the correct swing idiom for handling events.
You can find much more info @ <http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html> | Java Event Binding | [
"",
"java",
"swing",
"event-handling",
""
] |
I have come across what seems like a really annoying bug running my C++ program under Microsoft Visual C++ 2003, but it could just be something I'm doing wrong so thought I'd throw it out here and see if anybody has any ideas.
I have a hierarchy of classes like this (exactly as is - e.g. there is no multiple inheritance in the real code):
```
class CWaitable
{
public:
void WakeWaiters() const
{
CDifferentClass::Get()->DoStuff(this); // Breakpoint here
}
};
class CMotion : public CWaitable
{
virtual void NotUsedInThisExampleButPertinentBecauseItsVirtual() { }
};
class CMotionWalk : public CMotion
{ ... };
void AnnoyingFunctionThatBreaks(CMotion* pMotion)
{
pMotion->WakeWaiters();
}
```
Okay, so I call "AnnoyingFunctionThatBreaks" with a "CMotionWalk" instance (e.g. the debugger says it's 0x06716fe0), and all seems well. But when I step into it, to the breakpoint on the call to "DoStuff", the 'this' pointer has a different value to the pMotion pointer I called the method on (e.g. now the debugger says one word higher - 0x06716fe4).
To phrase it differently:
pMotion has the value 0x06716fe0, but when I call a method on it, that method sees 'this' as 0x06716fe4.
I'm not just going mad am I? That is weird, right? | I believe you are simply seeing an artifact of the way that the compiler is building the vtables. I suspect that CMotion has virtual functions of it's own, and thus you end up with offsets within the derived object to get to the base object. Thus, different pointers.
If it's working (i.e. if this isn't producing crashes, and there are no pointers outside the objects) then I wouldn't worry about it too much. | Is CMotion class is deriving some other class also which contains a virtual function? I found that the this pointer does not change with the code you posted, however it changes if you have the hierarchy something like this:
```
class Test
{
public:
virtual void f()
{
}
};
class CWaitable
{
public:
void WakeWaiters() const
{
const CWaitable* p = this;
}
};
class CMotion : public CWaitable, Test
{ };
class CMotionWalk : public CMotion
{
public:
};
void AnnoyingFunctionThatBreaks(CMotion* pMotion)
{
pMotion->WakeWaiters();
}
```
I believe this is because of the multiple inheritance for CMotion class and the vtable pointer in CMotion which points to Test::f() | C++ "this" doesn't match object method was called on | [
"",
"c++",
"pointers",
"debugging",
""
] |
I currently have a thread that listens for data from the network and then runs rules on it. I then want to pass the data to the GUI. I am worried about having a deadlock in the GUI. I cant figure out were to put the mutexes on the GUI side. I am also using c# and dotnet 3.5.
What I have come up with is
1) Using a timer to create an event and dump the thread. Worried about performance.
2) Use an intermediary event to copy the data to GUI.
3) Dig in and figure out thread safe way of using GUI.
What do you think is best way to proceed?
Edit: Here is the solution I am using. I pass in the changed element and then protect the big object with a mutex. I use helper function to switch threads using InvokeRequired then BeginInvoke with a delegate. Pulled from reading the answers and then following links until reaching [Threading in Windows Forms](http://www.yoda.arachsys.com/csharp/threads/winforms.shtml) by [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet).
```
delegate void UInt32ParameterDelegate(UInt32 n);
public void UpdateLocation(UInt32 n)
{
if (InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
BeginInvoke(new UInt32ParameterDelegate(UpdateLocation), new object[] { n });
return;
}
// Must be on the UI thread if we've got this far
this.engine.location.UpdateBusy.WaitOne();
// do the work in here
this.engine.location.UpdateBusy.ReleaseMutex();
}
``` | Synchronization is very easy in Windows Forms. You can call Control.Invoke() in the background thread. The thread will stall until the delegate has finished running on the UI thread. No sync required at all.
If stalling the thread is a problem, use Control.BeginInvoke(). You'll have to protect the object(s) you pass to the delegate with a lock if the thread might alter them while it continues running. That's rarely the case in a producer-consumer scenario, the thread can simply create new objects.
Do make sure that you don't Invoke() too often. Do it more frequently than about 1000 times per second and the UI thread will stop pumping Windows messages, being bogged down by handling the invoke requests. Since it is human eyes you're trying to please, invoking more than about 25 times per second is just wasted effort. Pool intermediate results in a collection object. | I hope I understand your problem correctly.
After the background thread reads the data and does whatever it wants, it should use `Invoke` to call a method on the GUI thread. That method would update anything that should be updated in the GUI. | Winforms should I multi thread or use event timer? | [
"",
"c#",
"winforms",
"multithreading",
"user-interface",
""
] |
Is it possible to use a Case statement in a sql From clause using SQL 2005? For example, I'm trying something like:
```
SELECT Md5 FROM
CASE
WHEN @ClientType = 'Employee' THEN @Source = 'HR'
WHEN @ClientType = 'Member' THEN @Source = 'Other'
END CASE
WHERE Current = 2;
``` | Assuming SQL Server:
You would need to use dynamic SQL. Build the string and then call sp\_executesql with the string.
Edit: Better yet, just use if statements to execute the appropriate statement and assign the value to a variable. You should avoid dynamic SQL if possible. | I don't believe that's possible. For one thing, query optimizers assume a specific list of table-like things in the FROM clause.
The most simple workaround that I can think of would be a UNION between the two tables:
```
SELECT md5
FROM hr
WHERE @clienttype = 'Employee'
AND current = 2
UNION
SELECT md5
FROM other
WHERE @clienttype = 'Member'
AND current = 2;
```
Only one half of the UNION could be True, given the @clienttype predicate. | Is it possible to use a Case statement in a sql From clause | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Does including DISTINCT in a SELECT query imply that the resulting set should be sorted?
I don't think it does, but I'm looking for a an authoritative answer (web link).
I've got a query like this:
```
Select Distinct foo
From Bar
```
In oracle, the results are distinct but are not in sorted order. In Jet/MS-Access there seems to be some extra work being done to ensure that the results are sort. I'm assuming that oracle is following the spec in this case and MS Access is going beyond.
Also, is there a way I can give the table a hint that it should be sorting on `foo` (unless otherwise specified)? | From the [SQL92 specification](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt):
> If DISTINCT is specified, then let TXA be the result of eliminating redundant duplicate values from TX. Otherwise, let TXA be TX.
...
> 4) If an is not specified, then the ordering of the rows of Q is implementation-dependent.
Ultimately the real answer is that DISTINCT and ORDER BY are two separate parts of the SQL statement; If you don't have an ORDER BY clause, the results by definition will not be specifically ordered. | No. There are a number of circumstances in which a DISTINCT in Oracle does not imply a sort, the most important of which is the hashing algorithm used in 10g+ for both group by and distinct operations.
**Always** specify ORDER BY if you want an ordered result set, even in 9i and below. | Does SELECT DISTINCT imply a sort of the results | [
"",
"sql",
"oracle",
"sqlplus",
""
] |
Consider this method signature:
```
public static void WriteLine(string input, params object[] myObjects)
{
// Do stuff.
}
```
How can I determine that the WriteLine method's "myObjects" pararameter uses the params keyword and can take variable arguments? | Check for the existence of `[ParamArrayAttribute]` on it.
The parameter with `params` will always be the last parameter. | Check the [ParameterInfo](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.aspx), if [ParamArrayAttribute](http://msdn.microsoft.com/en-us/library/system.paramarrayattribute.aspx) has been applied to it:
```
static bool IsParams(ParameterInfo param)
{
return param.GetCustomAttributes(typeof (ParamArrayAttribute), false).Length > 0;
}
``` | Determining if a parameter uses "params" using reflection in C#? | [
"",
"c#",
".net",
"reflection",
"parameters",
""
] |
Doing some experiments around WCF and Entity Framework. A couple of questions.
**Option 1:**
I understand that entity framework classes can be serialized over WCF directly, with sp1 onwards. How ever, I would like to know how scenarios like delay loading, eager loading, context management etc is handled in this, if they are handled at all?
**Option 2:**
Another alternative might be to use EFPocoAdapter, to have a plain POCO wrapper on top of the entity framework, instead of exposing entity framework classes directly. <http://code.msdn.microsoft.com/EFPocoAdapter> . Has anybody used this? Any Thoughts in this direction?
**Other Thoughts:**
About ADO.NET data services - As I understand ADO.NET data services can't be configured over remoting (nettcp binding)? It supports only http based access. We all know that binary serialization is slower.
Any pointers or any other options? | I've done some digging on this, and here are my findings on this.
**ADO.NET Data Services:**
You can use ADO.NET Data services (you need SP1) to expose your Entity framework over the wire, with almost zero code. But as I understand, the only limitation is, the transaction is over HTTP. That means, there is a small over head in terms of serialization (we all know binary serialization is faster), but the advantage is the speed of implementation for our services.
I got an unofficial word from John [<http://twitter.com/John_Papa]> on this - "Definitely more options with wcf. More work in most cases too. Astoria exposes entities easily. Perf diffs are negligible in most cases"
The advantages - You don't really need to write any services at all - You can just hook the validation and security logic around the data services and entity framework and we are done. Ideal if you are consuming data centric services over http - in scenarios like having a silverlight client, or a winform/wpf front end over http.
**Exposing Entity Framework over WCF:**
With SP1, there is lot of support for employing entity framework in layered architectures. This includes support for eager loading and context management. Of course, in this case, we need to write the services (and the logic behind our methods). Or if we have the entity framework model totally alligned with the db, we could generate most of the services, which includes the methods we need.
Recommending you to read this <http://msdn.microsoft.com/en-us/magazine/cc700340.aspx>
Another alternative might be to use EFPocoAdapter, to have a plain POCO wrapper on top of the entity framework for dtos, instead of exposing entity framework classes directly. Right now it is a compass project for next version of Entity framework <http://code.msdn.microsoft.com/EFPocoAdapter>. | It's a very bad idea to expose EF classes over WCF. Microsoft made some serious mistakes that prevent this from being a useful scenario. They've exposed the entities as data contrracts, but also the base classes of the entity, and for backward links, expose two copies of the link.
On the other hand, it appears that ADO.NET Data Services have some magic that allow something close to this to work. Read the SilverLight article in this month's MSDN Magazine for an example, from the client side, of using ADO.NET Data Services. | Entity framework in a layered architecture? | [
"",
"c#",
".net",
"wcf",
"entity-framework",
""
] |
I am working on a project for an IT class where I need to pass in a value on the query string in a php page and read it into a hidden field on an ASP page.
I currently am passing the parameter fine from the php page to ASP, but I am pretty new to .NET in general. How do I get the data out of the string and into a variable in C#? For example, if the url is **`blah.com/upload?username=washington`**, how would I get "washington" and save it into a hidden field? Thanks a ton.
Jergason
Edit
I knew it would be easy. Thanks a ton. | You can add a hidden field in your aspx file:
```
<asp:HiddenField ID="username" runat="server" />
```
And in your code behind populate it from the request parameter:
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
username.Value = Request["username"];
}
}
``` | It seems you just want:
```
string username = Request.QueryString["username"];
``` | How do I get data from the query string in asp? | [
"",
"c#",
"asp.net",
"query-string",
""
] |
Easiest way to explain what I mean is with a code sample. This doesn't compile, but is there any way to achieve this effect:
```
foreach(Type someType in listOfTypes)
{
SomeMethod<someType>();
}
```
Would be really convenient if that would work, but it doesn't. Is there another way to achieve the same thing as above, and why doesn't C# allow for that to be a legal statement?
Edit: Seems like the only way to do this is via reflection which may be too slow for our needs. Any insight on why there's not an efficient way built in and whether something like this is in the works for C# 4.0? | You can use reflection. Assuming the current object contains the `SomeMethod()` method, the code to do so would look like this:
```
GetType().GetMethod("SomeMethod").
MakeGenericMethod(new Type[] { someType }).Invoke(this, null);
```
Note that if `SomeMethod()` is non-public, your code may not execute in lower-trust environments. | > Why doesn't C# allow for that to be a legal statement?
As others have noted, you can't do this. Why not? Well, consider your example:
```
foreach(Type someType in listOfTypes)
{
SomeMethod<someType>();
}
```
Notice that each type in the list of types cannot be known until *runtime*, whereas the type parameter of `SomeMethod` must be known at *compile time*. It is impossible for the compiler to tell *which* `SomeMethod<T>` to resolve your invocation to, so this is illegal.
In C# 4, this and many other similar things will be possible with the inclusion of the DLR into the CLR. In particular, dynamic method invocation will enable you to invoke methods that may not be known at compile time. | Can you use generics methods in C# if the type is unknown until runtime? | [
"",
"c#",
"generics",
"types",
""
] |
This is a Query in VBA (Access 2007)
I have 3 strings defined:
```
str_a = "db.col1 = 5"
str_b = " and db.col2 = 123"
str_c = " and db.col3 = 42"
```
Then I use these in the WHERE part of my Query:
```
"WHERE '" & str_a & "' '" & str_b & "' '" & str_c & "' ;"
```
This fails, but If I paste in the strings like this:
```
"WHERE db.col1 = 5 and db.col2 = 123 and db.col3 = 42;"
```
It works perfectly. I'm guessing the syntax is wrong when using multiple variables in a string.
Anyone have any hints? | ```
"WHERE '" & str_a & "' '" & str_b & "' '" & str_c & "' ;"
```
will include single quotes within your completed WHERE clause. And the working version you showed us has none:
```
"WHERE db.col1 = 5 and db.col2 = 123 and db.col3 = 42;"
```
So, try constructing the `WHERE` clause with no single quotes:
```
"WHERE " & str_a & " " & str_b & " " & str_c & ";"
```
For debugging purposes, it's useful to view the final string after VBA has finished constructing it. If you're storing the string in a variable named `strSQL`, you can use:
```
Debug.Print strSQL
```
to display the finished string in the Immediate Window of the VB Editor. (You can get to the Immediate Window with the `CTRL`+`g` keyboard shortcut.)
Alternatively, you could display the finished string in a message box window:
```
MsgBox strSQL
``` | You've got some extra single quotes in there.
Try this:
```
"WHERE " & str_a & str_b & str_c
```
Note: In general, you shouldn't build query strings by concatenating strings, because this leaves you vulnerable to SQL injection, and mishandles special characters. A better solution is to use prepared statements. But assuming you're operating in a very controlled environment the solution I gave should work. | Query will not run with variables, will work when variable's definitions are pasted in | [
"",
"sql",
"string",
"ms-access",
"vba",
""
] |
How do i return matching entities in a random order?
Just to be clear this is Entity Framework stuff and LINQ to Entities.
(air code)
```
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby ?????
select en;
```
Thanks
**Edit:**
I tried adding this to the context:
```
public Guid Random()
{
return new Guid();
}
```
And using this query:
```
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby context.Random()
select en;
```
But i got this error:
```
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Guid Random()' method, and this method cannot be translated into a store expression..
```
**Edit (Current code):**
```
IEnumerable<MyEntity> results = (from en in context.MyEntity
where en.type == myTypeVar
orderby context.Random()
select en).AsEnumerable();
``` | The simple solution would be creating an array (or a `List<T>`) and than randomize its indexes.
EDIT:
```
static IEnumerable<T> Randomize<T>(this IEnumerable<T> source) {
var array = source.ToArray();
// randomize indexes (several approaches are possible)
return array;
}
```
EDIT: Personally, I find the answer of Jon Skeet is more elegant:
```
var results = from ... in ... where ... orderby Guid.NewGuid() select ...
```
And sure, you can take a random number generator instead of `Guid.NewGuid()`. | A simple way of doing this is to order by `Guid.NewGuid()` but then the ordering happens on the client side. You may be able to persuade EF to do something random on the server side, but that's not necessarily simple - and doing it using "order by random number" [is apparently broken](https://stackoverflow.com/questions/7952147).
To make the ordering happen on the .NET side instead of in EF, you need `AsEnumerable`:
```
IEnumerable<MyEntity> results = context.MyEntity
.Where(en => en.type == myTypeVar)
.AsEnumerable()
.OrderBy(en => context.Random());
```
It would be better to get the *unordered* version in a list and then shuffle that though.
```
Random rnd = ...; // Assume a suitable Random instance
List<MyEntity> results = context.MyEntity
.Where(en => en.type == myTypeVar)
.ToList();
results.Shuffle(rnd); // Assuming an extension method on List<T>
```
Shuffling is more efficient than sorting, aside from anything else.
See my [article on randomness](http://csharpindepth.com/Articles/Chapter12/Random.aspx) for details about acquiring an appropriate `Random` instance though. There are lots of Fisher-Yates shuffle implementations available on Stack Overflow. | Linq to Entities, random order | [
"",
"c#",
"entity-framework",
"linq-to-entities",
""
] |
Can someone please explain "re-usable structures" for me?
I was working on making some db objects in php, but was told I was using too much processing from the computer cause I made stuff to complicated with the below objects:
My DB objects:
```
$db = new Database;
$db->db_connect();
$post_content = new DbSelect;
$post_content->select('id', 'title', 'firstName', 'created', 'catName', 'tagName');
$post_content->from('content');
$post_content->join('inner');
$post_content->on('category','cat_id','id');
$post_content->where('id','1');
$post_content->order('created');
$db->db_close();
```
Normal PHP:
```
mysql_connect();
mysql_db_select();
$query = 'SELECT id, title, s_name, created, cat_name, tag_name
FROM content
JOIN INNER category, cat_id, id
WHERE id=1
ORDER created';
mysql_close();
```
So to reiterate my questions:
1. A quick explanation of re-usable structures?
2. why is the first method using objects "wrong"?
please note:
I'll be googling this as well as hoping for feedback
I know there a "tools" like Zend and other's that have plenty of db objects built into them, but I'm trying a DIY approach | I'm not sure where to start on this one. Object Oriented design is not a trivial subject, and there are many ways it can go wrong.
Essentially, you want to try to make logical indepedent objects in your application such that you can swap them out for other modules with the same interface, or reuse them in future projects. In your database example, look at PEAR::MDB2. PEAR::MDB2 abstracts the database drivers away from your application so that you don't need to worry about which specific database you're using. Today, you might be using MySQL to run your site. Tomorrow, you might switch to Postgresql. Ideally, if you use a proper OO design, you shoudn't need to change any of your code to make it work. You only need to swap out the database layer for another. (Pear::MDB2 makes this as simple as changing your db connect string)
May I suggest reading Code Complete by Steve McConnell. There's a whole chapter on Classes. While the examples are primarily C++, the concepts can be applied to any programming language, including PHP. | Don't confuse object-oriented-programmed with "class-oriented" or "object-based" programming. They both, on the surface, can look like OOP but are not.
These are when you take structured code and wrap in a bunch of classes, but don't change the fundamentals of how it operates. When you program with objects in mind, but don't leverage any of the special conventions that OOP affords you (polymorphism, aggregation, encapsulation, etc). This is not OOP.
What you *may* have here is some of this type of code. It's a little hard to tell. Is the purpose of your DbSelect class to abstract away the raw SQL code, so that you can use connect to any database without having to rewrite your queries? (as many DBAL solutions are wont to do) Or are you doing it "just because" in an effort to look like you've achieved OOP because you turned a basic SQL query into a chain of method calls? If the latter is closer to your motivation for creating this set of classes, you probably need to think about why you're making these classes and objects in the first place.
I should note that, from what I can tell by your simple snippet, you actually have not gained anything here in the way of re-usability. Now, your design may include code that gives flexibility where I cannot see it, but kind of suspect that it isn't there. The procedural/structured snippet is really no more or less reusable than your proposed class-based one.
Whomever you were talking to has a point - developing a complex (or even simple) OOP solution can definitely have many benefits - but to do so without regard to the cost of those benefits (and there's *always* a cost) is foolish at best, and hazardous at worst. | Explanation of re-usable structures in OO PHP | [
"",
"php",
"oop",
"class",
""
] |
I just switched to Fluent NHibernate and I've encountered an issue and did not find any information about it.
Here's the case :
```
public class Field : DomainObject, IField
{
public Field()
{
}
public virtual string Name { get; set; }
public virtual string ContactPerson { get; set; }
public virtual bool Private { get; set; }
public virtual IAddress Address { get; set; }
}
```
IAddress is an interface implemented by a class named Address
```
public class Address : DomainObject, IAddress
{
public Address()
{
}
public virtual string City { get; set; }
public virtual string Country { get; set; }
public virtual string PostalCode { get; set; }
public virtual string StreetAddress { get; set; }
}
```
Here's my mapping files for both classes
ADDRESS
```
public class AddressMap : ClassMap<Address>
{
public AddressMap()
{
WithTable("Addresses");
Id(x => x.Id, "Id").Access.AsCamelCaseField(Prefix.Underscore).GeneratedBy.Guid();
Map(x => x.City, "City");
Map(x => x.Country, "Country");
Map(x => x.PostalCode, "PostalCode");
Map(x => x.StreetAddress, "StreetAddress");
}
}
```
FIELD
```
public class FieldMap : ClassMap<Field>
{
public FieldMap()
{
WithTable("Fields");
Id(x => x.Id, "Id").Access.AsCamelCaseField(Prefix.Underscore).GeneratedBy.Guid();
Map(x => x.Name, "Name");
Map(x => x.ContactPerson, "ContactPerson");
Map(x => x.Private, "Private");
References(x => x.Address, "AddressId").Cascade.Delete().Cascade.SaveUpdate();
}
}
```
So when I tried to retrive a field object from my database, I get an NHibernate error that states that IAddress is not mapped. Is there any way to specify to NHibernate to use the Address class in the mapping?
Please let me know if more information are needed.
Thanks a lot,
Charles | I find that there are valid reasons for using an interface instead of a concrete class as a property.
For example, if your Field class was in a seperate project to the Address class, and you didn't have a dependency on the Address class's project from the Field class's project.
There are other ways of dealing with this situation, but the simplest way is often to attempt what you are doing and explicity tell NHibernate the concrete class to use for IAddress.
You can now do this in Fluent NHibernate, like this:
```
References(x => x.Address, "AddressId")
.Class(typeof(Address);
```
Unfortunately you can't do this with HasMany or HasManyToMany. I'm not sure if this would even be possible due to lack of good covariance support in C#. | On your Field object, you have an object of type IAddress. This could be implemented by any number of different implementations. With what you are asking, each implementation would have its own mapping, which would introduce any number of difficulties (impossibilities?) for NHibernate to handle.
A simple example would help to demonstrate. Say you have two IAddress implementations Address1, and Address2. They each are saved in their own table, tblAddress1, and tblAddress2. When you try to load your Field object, all NHibernate knows is that you have something that implements IAddress, it does not know which implementation was persisted. How would it know which mapping to use to retrieve the child object for any given field?
I'm sure there are more complications, but this example shows why you have to have a mapping for the exact type of object that you have declared. | Fluent NHibernate, working with interfaces | [
"",
"c#",
"nhibernate",
"interface",
"mapping",
"fluent",
""
] |
I just started learning JavaScript and am wondering why this simple snippet hangs when I click on the "Call function" button. What am I missing?
```
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.write("hello");
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>
``` | You need to write inside an element or give an element a value, or you should use document write like that :
```
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.getElementById("lblMessage").innerText = "hello";
document.getElementById("txtMessage").value = "hello";
//document.write("hello");
}
</script>
</head>
<body>
<form>
<script type="text/javascript">
document.write("This is written while page processed by browser !<br />");
</script>
<input type="text" id="txtMessage" /><br />
<span id="lblMessage"></span><br />
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>
``` | If you simply want to see your button doing something then try:
```
alert("Hello");
```
instead of the document.write. | Newbie: hanging browser on function call | [
"",
"javascript",
""
] |
In C#,I'm using Blowfish.NET 2.1.3's BlowfishECB.cs file([can be found here](http://www.hotpixel.net/software.html))
In C++,It's unknown,but it is similiar.
In C++,the Initialize(blowfish) procedure is the following:
```
void cBlowFish::Initialize(BYTE key[], int keybytes)
```
In C#,the Initialize(blowfish) procedure is the same
```
public void Initialize(byte[] key, int ofs, int len)
```
This is the problem:
This is how the key is initialized in C++
```
DWORD keyArray[2] = {0}; //declaration
...some code
blowfish.Initialize((LPBYTE)keyArray, 8);
```
As you see,the key is an array of two DWORDS,which is 8 bytes total.
In C# I declare it like that,but I get an error
```
BlowfishECB blowfish = new BlowfishECB();
UInt32[] keyarray = new UInt32[2];
..some code
blowfish.Initialize(keyarray, 0, 8);
```
The error is:
Argument '1': cannot convert from 'uint[]' to 'byte[]'
What am I doing wrong?
Thanks in advance! | You can use [BitConverter](http://msdn.microsoft.com/en-us/library/1184xdy4.aspx) to get the bytes from a UInt32.
---
To do this, you'll need to convert each element in a loop. I would do something like:
```` ```
private byte[] ConvertFromUInt32Array(UInt32[] array)
{
List<byte> results = new List<byte>();
foreach(UInt32 value in array)
{
byte[] converted = BitConverter.GetBytes(value);
results.AddRange(converted);
}
return results.ToArray();
}
``` ````
To go back:
```` ```
private UInt32[] ConvertFromByteArray(byte[] array)
{
List<UInt32> results = new List<UInt32>();
for(int i=0;i<array.Length;i += 4)
{
byte[] temp = new byte[4];
for (int j=0;j<4;++j)
temp[j] = array[i+j];
results.Add(BitConverter.ToUInt32(temp);
}
return results.ToArray();
}
``` ```` | If you are using VS2008 or C# 3.5, try the following LINQ + BitConverter solution
```
var converted =
keyArray
.Select(x => BitConverter.GetBytes(x))
.SelectMany(x => x)
.ToArray();
```
Breaking this down
* The Select converts every UInt32 into a byte[]. The result is an IEnumerable<byte[]>
* The SelectMany calls flattes the IEnumerable<byte[]> to IEnumerable<byte>
* ToArray() simply converts the enumerable into an array
**EDIT** Non LINQ solution that works just as well
```
List<byte> list = new List<byte>();
foreach ( UInt32 k in keyArray) {
list.AddRange(BitConverter.GetBytes(k));
}
return list.ToArray();
``` | C# Problem using blowfish NET: How to convert from Uint32[] to byte[] | [
"",
"c#",
"byte",
"blowfish",
"uint32",
""
] |
I have a code that parses some template files and when it finds a placeholder, it replaces it with a value. Something like:
```
<html>
<head>
<title>%title%</title>
</head>
<body bgcolor="%color%">
...etc.
```
In code, the parser finds those, calls this function:
```
string getContent(const string& name)
{
if (name == "title")
return page->getTitle();
else if (name == "color")
return getBodyColor();
...etc.
}
```
and then replaces the original placeholder with returned value.
In real case, it is not a dummy web page, and there are many (50+) different placeholders that can occur.
My code is C++, but I guess this problem exists with any language. It's more about algorithms and OO design I guess. Only important thing is that this must be compiled, even if I wanted I couldn't have any dynamic/eval'd code.
I though about implementing Chain of Responsibility pattern, but it doesn't seem it would improve the situation much.
UPDATE: and I'm also concerned about [this comment](https://stackoverflow.com/questions/482804/what-are-the-known-gotchas-with-regards-to-the-chain-of-responsibilty-pattern/482894#482894) in another thread. Should I care about it? | Use a dictionary that maps tag names to a tag handler. | You want [replace conditional with polymorphism](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html). Roughly:
```
string getContent(const string& name) {
myType obj = factory.getObjForName(name);
obj.doStuff();
}
```
where doStuff is overloaded. | Replace giant switch statement with what? | [
"",
"c++",
"templates",
"switch-statement",
"chain-of-responsibility",
""
] |
I have developed a solution that relies on an AJAX call to retrieve information and update the client page every 10 seconds. This is working fine, but I am concerned at the scalability of the code, given the number and length of headers being passed from client to server and back again. I have removed a number of redundant headers on the server side, mostly ASP.NET-related, and now I'm attempting to cut down on the headers coming from the client.
The browser used by my company is IE (version 6, to be upgraded to 7 soon). This is an approximation of my current code:
```
var xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
xmlHTTP.onreadystatechange = function() {
if ((xmlHTTP.readyState == 4) && (xmlHTTP.status == 200)) {
myCallbackFunction(xmlHTTP);
}
};
xmlHTTP.open('GET', 'myUrl.aspx');
try {
xmlHTTP.setRequestHeader("User-Agent", ".");
xmlHTTP.setRequestHeader("Accept", ".");
xmlHTTP.setRequestHeader("Accept-Language", ".");
xmlHTTP.setRequestHeader("Content-Type", ".");
} catch(e) {}
xmlHTTP.send();
```
Although [I've read](http://blog.mibbit.com/?p=143) that it's possible to clear some of these headers, I haven't found a way of doing it that works in IE6. Setting them to null results in a Type Mismatch exception, so I've ended up just replacing them with '.' for the time being. Is there another way of clearing them or an alternative method of reducing the submitted HTTP headers?
Also, there seems to be no way of replacing or shortening the 'Referrer' header at all. | According to the [WD spec](http://www.w3.org/TR/XMLHttpRequest/#setrequestheader)
> The setRequestHeader() method appends a value if the HTTP header given as argument is already part of the list of request headers.
That is, you could only add headers, not replace them.
This doesn't completely match current browser behaviour, but it may be where browsers will be headed, in which case any efforts on this front are a waste of time in the long term. In any case current browser behaviour with setting headers is very varied and generally can't be relied upon.
> There seems to be no way of replacing or shortening the 'Referrer' header at all.
That wouldn't surprise me, given that some people misguidedly use ‘Referer’ [sic] as an access-control mechanism.
You could try to make sure that the current page URL wasn't excessively long, but to be honest all this smells of premature optimisation to me. Whatever you do your request is going to fit within one IP packet, so there's not gonig to be a big visible performance difference.
It may be worthwhile for Mibbit (as mentioned on the blog you linked) to try this stuff, because Mibbit draws a quite staggering amount of traffic, but for a simple company-wide application I don't think the cross-browser-and-proxy-testing-burden:end-user-benefit ratio of messing with the headers is worth it. | I would forgo this kind of micro-optimizations and look into a push model instead. By way of a starting place:
* Flash can create persistent sockets, and broker the events into javascript.
* You could implement Bidirectional-streams Over Synchronous HTTP (BOSH). See <http://xmpp.org/extensions/xep-0124.html>
Both of these are typically paired with an XMPP server on the back-end. | How can I clear HTTP headers for AJAX GET calls? | [
"",
"javascript",
"ajax",
"internet-explorer",
"http-headers",
"xmlhttprequest",
""
] |
Note: this is not [a duplicate of Jeff's question](https://stackoverflow.com/questions/181188/c-equivalent-to-vb-net-catch-when).
That question asked "Is an equivalent?" I know there isn't, and I want to know why!
The reason I ask is that I've only just become clear on how important it is, and the conclusion seems very strange to me.
The Exception Handling block of Microsoft's Enterprise Library advises us to use this pattern:
```
catch (Exception x)
{
if (ExceptionPolicy.HandleException(x, ExceptionPolicies.MyPolicy))
throw;
// recover from x somehow
}
```
The policy is defined in an XML file, so that means that if a customer has an issue, we can modify the policy to assist with tracking down (or perhaps papering over) the problem to give them a fast resolution until we deal with it properly - which may involve arguing with 3rd parties, about whose fault it all is.
This is basically an acknowledgement of the simple fact that in real applications the number of exception types and their "recoverability" status is practically impossible to manage without a facility like this.
Meanwhile, the CLR team at MS says this is not an option, and it turns out those guys know what they're talking about! The problem is that right before the `catch` block runs, any `finally` blocks nested inside the `try` block will be executed. So those `finally` blocks may do any of the following:
* Harmlessly modify the program state (phew, lucky).
* Trash something important in the customer's data, because the program state is screwed up to an unknown degree.
* Disguise or destroy important evidence that we need to diagnose an issue - especially if we're talking about calls into native code.
* Throw *another* exception, adding to the general confusion and misery.
Note that the `using` statement and C++/CLI destructors are built on `try`/`finally`, so they're affected too.
So clearly the `catch`/`throw` pattern for filtering exceptions is no good. What is actually needed is a way to filter exceptions, via a policy, without actually catching them and so triggering the execution of `finally` blocks, unless we find a policy that tells us the exception is safe to recover from.
The CLR team blogged about this recently:
* [Catch, Rethrow and Filters - Why should you care?](http://blogs.msdn.com/clrteam/archive/2009/02/05/catch-rethrow-and-filters-why-you-should-care.aspx)
* [Why catch(Exception)/empty catch is bad](http://blogs.msdn.com/clrteam/archive/2009/02/19/why-catch-exception-empty-catch-is-bad.aspx)
The outcome is that we have to write a helper function in VB.NET to allow us to access this vital capability from C#. The big clue that there is a problem is that there is code in the BCL that does this. Lots of people have blogged about doing it, but they rarely if ever mention the thing about `try`/`finally` blocks, which is the killer.
What I would like to know is:
* Are there any public statements or direct emails people have received from the C# team on this subject?
* Are there any existing Microsoft Connect suggestions asking for this? I've heard rumours of them but none of the likely keywords turned up anything.
**Update:** as noted above, I have already searched on Microsoft Connect without finding anything. I have also (unsurprisingly) Googled. I've only found people [explaining why they need this feature](http://www.codeproject.com/KB/cs/csmverrorhandling.aspx), or pointing out the [advantages of it in VB.NET](http://blogs.msdn.com/vbteam/archive/2008/10/09/vb-catch-when-why-so-special.aspx), or fruitlessly hoping that it will be [added in a future version of C#](http://gregbeech.com/blogs/tech/archive/2006/01/03/why-doesn-t-c-have-exception-filters.aspx), or [working around it](http://blogs.msdn.com/junfeng/archive/2008/12/08/exception-filter.aspx), And plenty of [misleading advice](http://msdn.microsoft.com/en-us/magazine/cc300489.aspx). But no statement on the rationale for omitting it from all current versions of C#. And the reason I'm asking about existing Connect issues is so that (a) I don't create an unnecessary duplicate and (b) I can tell interested people if I have to create one.
**Update 2:** Found [an interesting old blog post from Eric Gunnerson](http://blogs.msdn.com/ericgu/archive/2004/01/12/57985.aspx), formerly of the C# team:
> "Yes, being able to put a condition on
> a catch is somewhat more convenient
> than having to write the test
> yourself, but it doesn't really enable
> you to do anything new."
That was the same assumption I had until it was properly explained to me! | As to any existing connect bugs. The following issue deals with exception fliters. The user did not explicitly state they wanted them be an actual filter in the sense of when they execute but IMHO it's implied by the logic.
<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=401668>
Besides that issue though, there are no issues I can find or know of that are related to what you are looking for. I think it would do good to have a separate issue which explicitly calls out the want for VB.Net style exception filters.
I wouldn't worry too much about introducing a duplicate question if you've done a bit of due diligence looking for an existing one. If there is a dupe, Mads will dupe it accordingly and link you to the main request.
As for the part of getting an official response from the C# team, you will likely get that when you either 1) file a connect bug or 2) get duped against the main bug. I really doubt there is an official reason / justification out there right now.
Here's my **speculation** on the issue: My guess is that this feature simply wasn't on the original C# 1.0 feature set and since that time there hasn't been enough demand to make it into the language. The C# and VB team spend an unbelievable amount of time ranking language features at the start of every ship cycle. We have to make some **very** difficult cuts at times. Without sufficient demand there is very little chance a feature will make it into the language.
Up until recently I bet you would be hard pressed to find 1 out of 10 people who understood the difference between VB.Net's Try/When and just using a plain old if statement in a C# catch block. It seems to be a bit more on peoples minds lately so maybe it will make it into a future version of the langauge. | Using [Exception Filter Inject](http://code.msdn.microsoft.com/ExceptionFilterInjct) may be simpler than using the delegate workaround.
For a real answer to your question you will need a response from Anders Hejlsberg, or someone who was in the original design meetings. You might try seeing if you can get it asked by the Channel 9 interviewer next time [the C# design team is interviewed](http://channel9.msdn.com/posts/Charles/C-40-Meet-the-Design-Team/).
I'd guess that when the original decision was made, exception filters were seen as an unnecessary complication that might do more harm than good. You can certainly see a desire to remain 'silent' about unproven features in this interview about the decision not to support checked exceptions: [The Trouble with Checked Exceptions](http://www.artima.com/intv/handcuffsP.html).
I think the postmoterm diagnostic scenarios argue strongly for providing access to exception filters in the language. However those scenarios may not have been articulated at the time. Also those scenarios really need proper tooling support, which certainly wasn't available in V1. Finally there may be big negatives about adding this feature that we are not considering.
If there isn't a connect bug on this you should enter one and encourage others to vote it up. [I'd recommend asking for access to the CLR feature rather than attempting to design how it fits in the language.] | Why doesn't C# have support for first pass exception filtering? | [
"",
"c#",
"vb.net",
"exception",
"finally",
""
] |
I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:
```
sub uniqify($) {
my $timestamp = shift;
state $last_ts = -1;
state $next_letter = 'A';
if ($timestamp == $last_ts) {
$timestamp .= $next_letter++;
} else {
$last_ts = $timestamp;
$next_letter = 'A';
}
return $timestamp;
}
```
So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.
Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.
Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.
Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.
I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function? | Look at [this answer for a robust method to convert a number to an alphanumeric id](https://stackoverflow.com/questions/410485/whats-the-5-character-alphanumeric-id-in-reddit-url/410504#410504)
The code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id
```
from string import uppercase as up
import itertools
def to_base(q, alphabet):
if q < 0: raise ValueError( "must supply a positive integer" )
l = len(alphabet)
converted = []
while q != 0:
q, r = divmod(q, l)
converted.insert(0, alphabet[r])
return "".join(converted) or alphabet[0]
class TimestampUniqifier( object ):
def __init__(self):
self.last = ''
self.counter = itertools.count()
def __call__( self, str ):
if str == self.last:
suf = self.counter.next()
return str + to_base( suf, up )
else:
self.last = str
self.counter = itertools.count()
return str
timestamp_uniqify = TimestampUniqifier()
```
usage:
```
timestamp_uniqify('1')
'1'
timestamp_uniqify('1')
'1A'
timestamp_uniqify('1')
'1B'
timestamp_uniqify('1')
'1C'
timestamp_uniqify('2')
'2'
timestamp_uniqify('3')
'3'
timestamp_uniqify('3')
'3A'
timestamp_uniqify('3')
'3B'
```
You can call it maaaany times and it will still produce good results:
```
for i in range(100): print timestamp_uniqify('4')
4
4A
4B
4C
4D
4E
4F
4G
4H
4I
4J
4K
4L
4M
4N
4O
4P
4Q
4R
4S
4T
4U
4V
4W
4X
4Y
4Z
4BA
4BB
4BC
4BD
4BE
4BF
4BG
4BH
4BI
4BJ
4BK
4BL
4BM
4BN
4BO
4BP
4BQ
4BR
4BS
4BT
4BU
4BV
4BW
4BX
4BY
4BZ
4CA
4CB
4CC
4CD
4CE
4CF
4CG
4CH
4CI
4CJ
4CK
4CL
4CM
4CN
4CO
4CP
4CQ
4CR
4CS
4CT
4CU
4CV
4CW
4CX
4CY
4CZ
4DA
4DB
4DC
4DD
4DE
4DF
4DG
4DH
4DI
4DJ
4DK
4DL
4DM
4DN
4DO
4DP
4DQ
4DR
4DS
4DT
4DU
``` | Well, sorry to say, but you can't just do a direct translation from Perl to Python (including bit-for-bit Perlisms) and expect the outcome to be prettier. It won't be, it will be considerably uglier.
If you want the prettiness of Python you will need to use Python idioms instead.
Now for the question at hand:
```
from string import uppercase
class Uniquifier(object):
def __init__(self):
self.last_timestamp = None
self.last_suffix = 0
def uniquify(self, timestamp):
if timestamp == self.last_timestamp:
timestamp = '%s%s' % (timestamp,
uppercase[self.last_suffix])
self.last_suffix += 1
else:
self.last_suffix = 0
self.timestamp = timestamp
return timestamp
uniquifier = Uniquifier()
uniquifier.uniquify(a_timestamp)
```
Prettier? Maybe. More readable? Probably.
**Edit (re comments):** Yes this fails after Z, and I am altogether unhappy with this solution. So I won't fix it, but might offer something better, like using a number instead:
```
timestamp = '%s%s' % (timestamp,
self.last_suffix)
```
If it were me, I would do this:
```
import uuid
def uniquify(timestamp):
return '%s-%s' % (timestamp, uuid.uuid4())
```
And just be happy. | How would you translate this from Perl to Python? | [
"",
"python",
"perl",
""
] |
I've been having an argument about the usage of the word "accessor" (the context is Java programming). I tend to think of accessors as implicitly being "property accessors" -- that is, the term implies that it's more or less there to provide direct access to the object's internal state. The other party insists that any method that touches the object's state in any way is an accessor.
I know you guys can't win the argument for me, but I'm curious to know how you would define the term. :) | By accessors, I tend to think of getters and setters.
By insisting that all methods that touch the object's internal state are accessors, it seems that any instance method that actually uses the state of the object would be an accessor, and that just doesn't seem right. What kind of instance method won't use the state of the object? In other words, *an instance method that doesn't use the object's state in some way shouldn't be an instance method to begin with -- it should be a class method*.
For example, should the [`BigDecimal.add`](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#add(java.math.BigDecimal)) method be considered an accessor? It is a method that will read the value of the instance that the `add` method was called on, then return the result after adding the value of another `BigInteger`. It seems fairly straight forward that the `add` instance method is not a getter nor a setter. | An accessor method does exactly what it says on the tin: accesses some state from the type without side effects (apart from lazy instantiation, perhaps, which is not something that the caller would normally know about).
```
private int _age;
public int getAge()
{
return _age;
}
```
Methods that modify state are more usefully considered (in my opinion) as mutators. | What is the definition of "accessor method"? | [
"",
"java",
"definition",
"accessor",
""
] |
Is there a way of knowing which modules are available to import from inside a package? | Many packages will include a list called `__all__`, which lists the member modules. This is used when python does `from x import *`. You can read more about that [here](http://docs.python.org/tutorial/modules.html#importing-from-a-package).
If the package does not define `__all__`, you'll have to do something like the answer to a question I asked earlier, [here](https://stackoverflow.com/questions/487971/is-there-a-standard-way-to-list-names-of-python-modules-in-a-package). | dir([object]);
Without arguments, dir() return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
So, in the case of a module, such as 'sys':
```
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
```
That's all there is to it. | How do I find the modules that are available for import from within a package? | [
"",
"python",
"import",
""
] |
I'm coding an italian website where I need to validate some input data with an xhr call.
My code for the ajax request's like this (I'm using JQuery 1.3.2):
```
$.ajaxSetup({
type: "POST",
timeout: 10000,
contentType: "application/x-www-form-urlencoded; charset=iso-8859-1"
});
$.ajax({
url: "ajaxvalidate.do",
data: {field:controlInfo.field,value:controlInfo.fieldValue},
dataType: "json",
complete: function() {
//
},
success: function(msg) {
handleAsyncMsg(controlInfo, msg, closureOnError);
},
error: function(xhr, status, e) {
showException(controlInfo.id, status);
}
});
```
On the backend I have a java struts action to handle the xhr. I need to use the encoding ISO-8859-1 in the page to ensure the data (specially accented characters) are sent correctly in the synchronous submit.
All's working like a charm in Firefox but when I have to handle an async post from IE 7 with accented characters I have a problem: I always receive invalid characters (utf-8 maybe?).
EG I type in the form àààààààà and I get in my request this value: Ã Ã Ã Ã Ã Ã Ã Ã.
Since the request charset's correctly set to ISO-8859-1 I can't understand why the server's still not parsing the form value correctly.
This is a log sample with all the request headers and the error (the server's an old Bea Weblogic 8.1):
```
Encoding: ISO-8859-1
Header: x-requested-with - Value: XMLHttpRequest
Header: Accept-Language - Value: it
Header: Referer - Value: https://10.172.14.36:7002/reg-docroot/conv/starttim.do
Header: Accept - Value: application/json, text/javascript
Header: Content-Type - Value: application/x-www-form-urlencoded; charset=iso-8859-1
Header: UA-CPU - Value: x86
Header: Accept-Encoding - Value: gzip, deflate
Header: User-Agent - Value: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Header: Host - Value: 10.172.14.36:7002
Header: Content-Length - Value: 65
Header: Connection - Value: Keep-Alive
Header: Cache-Control - Value: no-cache
Header: Cookie - Value: JSESSIONID=JQJlNpVC86yTZJbcpt54wzt82TnkYmWYC5VLL2snt5Z8GTsQ1pLQ!1967684811
Attribute: javax.net.ssl.cipher_suite - Value: SSL_RSA_WITH_RC4_128_MD5
Attribute: javax.servlet.request.key-size - Value: 128
Attribute: javax.servlet.request.cipher_suite - Value: TLS_RSA_WITH_RC4_128_MD5
Attribute: javax.servlet.request.key_size - Value: 128
Attribute: weblogic.servlet.network_channel.port - Value: 7001
Attribute: weblogic.servlet.network_channel.sslport - Value: 7002
Attribute: org.apache.struts.action.MESSAGE - Value: org.apache.struts.util.PropertyMessageResources@4a97dbd
Attribute: org.apache.struts.globals.ORIGINAL_URI_KEY - Value: /conv/ajaxvalidate.do
Attribute: errors - Value: org.apache.struts.util.PropertyMessageResources@4a97e4d
Attribute: org.apache.struts.action.MODULE - Value: org.apache.struts.config.impl.ModuleConfigImpl@4aa2ff8
Attribute: weblogic.servlet.request.sslsession - Value: javax.net.ssl.impl.SSLSessionImpl@42157c5
field: nome - value: Ã Ã Ã Ã Ã Ã Ã Ã - action: /endtim
``` | > contentType: "application/x-www-form-urlencoded; charset=iso-8859-1"
You can *say* you're sending a form submission as ISO-8859-1 in the header, but that doesn't mean you actually are. jQuery uses the standand JavaScript encodeURIComponent() method to encode Unicode strings into query-string bytes, and that *always* uses UTF-8.
In any case, the ‘charset’ parameter for the MIME type ‘application/x-www-form-urlencoded’ is highly non-standard. As an ‘x-’ type there is no official MIME registration for this type, but HTML 4.01 doesn't specify such a parameter and it would be very unusual for an ‘application/\*’ type. Weblogic claims to detect this construct, for what it's worth.
So what you can do is either:
1: create the POST body form-urlencoded content yourself, hacking it into ISO-8859-1 format manually, using something like
```
function encodeLatin1URIComponent(str) {
var bytes= '';
for (var i= 0; i<str.length; i++)
bytes+= str.charCodeAt(i)<256? str.charAt(i) : '?';
return escape(bytes).split('+').join('%2B');
}
```
instead of encodeURIComponent().
2: lose the ‘charset’ and leave it submitting UTF-8 as normal, and make your servlet understand incoming UTF-8. This is generally best, but will mean mucking around with the servlet container config to make it choose the right encoding. For Weblogic this seems to mean [using an <input-charset> element](http://edocs.bea.com/wls/docs100/webapp/configurejsp.html#wp162180) in weblogic.xml. And by then you're looking at moving your whole app to UTF-8. Which is by no means a bad thing (non-Unicode-capable websites are sooo 20-century!) but may well be a lot of work. | Actually just solved that, I needed to do:
jQuery.ajaxSetup({
contentType: "application/json;charset=utf-8"
});
Which overrides the behaviour of adding application/x-www-form-urlencoded to the content-type in IE. | Another JQuery encoding problem, on IE | [
"",
"java",
"jquery",
"ajax",
"internet-explorer",
"iso-8859-1",
""
] |
I've seen some people using `void` operator in their code. I have also seen this in `href` attributes: `javascript:void(0)` which doesn't seem any better than `javascript:;`
So, what is the justification of using the `void` operator? | The JavaScript, the `void` operator is used to explicitly return the undefined value. It's a unary operator, meaning only one operand can be used with it. You can use it like shown below — standalone or with a parenthesis.
```
void expression;
void(expression);
```
Lets see some examples:
```
void 0; //returns undefined
void(1); //returns undefined
void 'hello'; //undefined
void {}; //undefined
void []; //undefined
void myFunction();
void(myFunction());
```
If you ask why do you need a special keyword just to return undefined instead of just returning `undefined`: the reason is that before ES5 you could actually name a global variable `undefined`, like so: `var undefined = "hello"` or `var undefined = 23`, and most browsers would accept it; the identifier `undefined` was not promised to actually be undefined¹. So, to return the *actual* undefined value, the `void` operator is/was used. It's not a very popular operator though and is seldom used.
Let's see an example of function with `void`:
```
//just a normal function
function test() {
console.log('hello');
return 2;
}
//lets call it
console.log(test()); //output is hello followed by 2
//now lets try with void
console.log(void test()); //output is hello followed by undefined
```
`void` discards the return value from the function and explicitly returns undefined.
You can read more from my tutorial post: <https://josephkhan.me/the-javascript-void-operator/>
¹ In ECMAScript 5 and later, the global variable `undefined` is guaranteed to be undefined ([ECMA-262 5th Ed.](https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition%20December%202009.pdf), § 15.1.1.3), though it is still possible to have a variable inside an inner scope be named `undefined`. | [Explanation of its use in links](https://stackoverflow.com/questions/430349/what-does-the-browser-do-when-the-source-of-iframe-is-javascript/430359#430359):
> This is the reason that bookmarklets
> often wrap the code inside void() or
> an anonymous function that doesn't
> return anything to stop the browser
> from trying to display the result of
> executing the bookmarklet. For
> example:
>
> ```
> javascript:void(window.open("dom_spy.html"))
> ```
>
> If you directly use code that returns
> something (a new window instance in
> this case), the browser will end up
> displaying that:
>
> ```
> javascript:window.open("dom_spy.html");
> ```
>
> In Firefox the above will display:
>
> ```
> [object Window]
> ``` | What is the point of void operator in JavaScript? | [
"",
"javascript",
"void",
""
] |
I'm really confused as to why this operation works. Can someone explain it?
```
$test1 = "d85d1d81b25614a3504a3d5601a9cb2e";
$test2 = "3581169b064f71be1630b321d3ca318f";
if ($test1 == 0)
echo "Test 1 is Equal!?";
if ($test2 == 0)
echo "Test 2 is Equal!?";
// Returns: Test 1 is Equal!?
```
For clarification, I am trying to compare the string `"0"` to the `$test` variables. I already know to fix the code I can just enclose (as I should have) the `0` in `""`s
I'm wondering if this is a PHP bug, a server bug, or somehow a valid operation. According to <https://www.php.net/types.comparisons> this **should not** have worked.
**Edit:** Scratch that, apparently it does mention that Loose comparisons between string and 0 is true. But I still don't know why.
**Edit 2:** I've revised my question, why does the `$test2` value of `"3581169b064f71be1630b321d3ca318f"` not work? | [From the PHP manual](http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion):
> **String conversion to numbers**
>
> When a string is evaluated in a
> numeric context, the resulting value
> and type are determined as follows.
>
> The string will be evaluated as a
> float if it contains any of the
> characters '.', 'e', or 'E'.
> Otherwise, it will be evaluated as an
> integer.
>
> The value is given by the initial
> portion of the string. If the string
> starts with valid numeric data, this
> will be the value used. Otherwise, the
> value will be 0 (zero). Valid numeric
> data is an optional sign, followed by
> one or more digits (optionally
> containing a decimal point), followed
> by an optional exponent. The exponent
> is an 'e' or 'E' followed by one or
> more digits. | **Type conversion using the == operator**
The == operator is a loosely-typed comparison. It will convert both to a common type and compare them. The way strings are converted to integers is [explained here](https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion).
Note that the [page you linked to](https://www.php.net/types.comparisons) doesn't contradict this. Check the second table, where it says that comparing the integer `0` to a string `"php"` using `==` shall be true.
What happens is that the string is converted to integer, and non-numeric strings (strings that do not contain or begin with a number) convert to `0`.
**Numeric vs non-numeric strings**
A string that consists of a number, or begins with a number, is considered a *numeric string*. If the string has other characters after that number, these are ignored.
If a string starts with a character that cannot be interpreted as part of a number, then it is a *non-numeric string* and will convert to `0`. This doesn't mean that a numeric string has to start with a digit (0-9) - for example `"-1"` is a numeric string because the minus sign is part of a number in that case.
So for example, your string `"d85d1d81b25614a3504a3d5601a9cb2e"` does not start with a number, so it would convert to `0`. But your second string `"3581169b064f71be1630b321d3ca318f"` would be converted to integer `3581169`. So that's why your second test does not work the same way.
**What you should do**
You probably want:
```
if ($test1 === "0")
```
Notice the use of triple equals instead of a double equals. This ensures that what you are comparing is a string that contains the digit zero only, and prevents any type conversion. | Comparing String to Integer gives strange results | [
"",
"php",
"casting",
"comparison",
""
] |
I've written an application in C# that moves jpgs from one set of directories to another set of directories concurrently (one thread per fixed subdirectory). The code looks something like this:
```
string destination = "";
DirectoryInfo dir = new DirectoryInfo("");
DirectoryInfo subDirs = dir.GetDirectories();
foreach (DirectoryInfo d in subDirs)
{
FileInfo[] files = subDirs.GetFiles();
foreach (FileInfo f in files)
{
f.MoveTo(destination);
}
}
```
However, the performance of the application is horrendous - tons of page faults/sec. The number of files in each subdirectory can get quite large, so I think a big performance penalty comes from a context switch, to where it can't keep all the different file arrays in RAM at the same time, such that it's going to disk nearly every time.
There's a two different solutions that I can think of. The first is rewriting this in C or C++, and the second is to use multiple processes instead of multithreading.
Edit: The files are named based on a time stamp, and the directory they are moved to are based on that name. So the directories they are moved to would correspond to the hour it was created; 3-27-2009/10 for instance.
We are creating a background worker per directory for threading.
Any suggestions? | **Reconsidered answer**
I've been rethinking my original answer below. I still suspect that using fewer threads would probably be a good idea, but as you're just *moving* files, it shouldn't actually be that IO intensive. It's possible that just *listing* the files is taking a lot of disk work.
However, I doubt that you're really running out of memory for the files. How much memory have you got? How much memory is the process taking up? How many threads are you using, and how many cores do you have? (Using significantly more threads than you have cores is a bad idea, IMO.)
I suggest the following plan of attack:
* Work out where the bottlenecks actually are. Try fetching the list of files but not doing the moving them. See how hard the disk is hit, and how long it takes.
* Experiment with different numbers of threads, with a queue of directories still to process.
* Keep an eye on the memory use and garbage collections. The Windows performance counters for the CLR are good for this.
**Original answer**
Rewriting in C or C++ wouldn't help. Using multiple processes wouldn't help. What you're doing is akin to giving a single processor a hundred threads - except you're doing it with the disk instead.
It makes sense to parallelise tasks which use IO if there's *also* a fair amount of computation involved, but if it's already disk bound, asking the disk to work with lots of files at the same time is only going to make things worse.
You may be interested in a benchmark ([description](http://msmvps.com/blogs/jon_skeet/archive/2009/03/20/benchmarking-io-buffering-vs-streaming.aspx) and [initial results](http://msmvps.com/blogs/jon_skeet/archive/2009/03/24/buffering-vs-streaming-benchmark-first-results.aspx)) I've recently been running, testing "encryption" of individual lines of a file. When the level of "encryption" is low (i.e. it's hardly doing any CPU work) the best results are always with a single thread. | Rule of thumb, don't parallelize operations with serial dependencies. In this case your hard drive is the bottleneck and to many threads are just going to make performance worse.
If you are going to use threads try to limit the number to the number of resources you have available, cores and hard disks not the number of jobs you have pending, directories to copy. | C#: poor performance with multithreading with heavy I/O | [
"",
"c#",
"performance",
"multithreading",
""
] |
Is it possible to narrow the type of a field in a Java class without making the containing class itself generic?
The generic example would be something like this:
```
abstract class MyClass {
//...
}
interface MyInterface {
//...
}
class MyConcreteClass<T extends MyClass & MyInterface> {
private T value;
}
```
Is there any way to do the following:
```
class MyConcreteClass {
private MyClass & MyInterface value;
}
```
This is essentially equivalent to MyConcreteClass or the raw MyConcreteClass type. In my implementation the type parameter will vary over the lifetime of the object (cursed mutability! It is imposed upon me by JPA!) and so the type annotation seems somewhat superfluous.
* EDIT -
There is an additional restriction I forgot to mention. We will also have this:
```
class SubA extends MyClass
class SubB extends MyClass
class SubC extends MyClass
class SubSubA extends SubA implements MyInterface
class SubSubB extends SubB implements MyInterface
class SubSubC extends SubC implements MyInterface
```
Thus, simply declaring an abstract subclass of MyClass that implements MyInterface is not a suitable solution.
Also, the ultimate field type must be a concrete type, rather than simply an interface representing the intersection, for the simple reason that JPA-persisted entites cannot be referenced by their interface types. That is, a persistent field in a JPA entity class must be of either a primitive type or a concrete entity type. | I have never come across a problem like that (and thus no elegant solution comes to mind :-)... however...
```
interface Fooable
{
}
abstract class MyClass
implements Fooable
{
}
interface MyInterface
extends Fooable
{
}
class MyConcreteClass
{
private Fooable value;
}
``` | In such complicated cases you should hide classes behind interfaces.
Then you can define an explicit interface for the intersection, i.e. an interface that extends both the interface corresponding to MyClass and MyInterface, and letting the appropriate superclasses implement it instead of MyInterface. | Narrow a Java field type without making the enclosing class generic? | [
"",
"java",
"generics",
""
] |
I am currently working on a program which sniffs TCP packets being sent and received to and from a particular address. What I am trying to accomplish is replying with custom tailored packets to certain received packets. I've already got the parsing done. I can already generated valid Ethernet, IP, and--for the most part--TCP packets.
The only thing that I cannot figure out is how the seq / ack numbers are determined.
While this may be irrelevant to the problem, the program is written in C++ using WinPCap. I am asking for any tips, articles, or other resources that may help me. | When a TCP connection is established, each side generates a random number as its initial sequence number. It is a strongly random number: there are security problems if anybody on the internet can guess the sequence number, as they can easily forge packets to inject into the TCP stream.
Thereafter, for every byte transmitted the sequence number will increment by 1. The ACK field is the sequence number from the other side, sent back to acknowledge reception.
[RFC 793](https://www.rfc-editor.org/rfc/rfc793), the original TCP protocol specification, can be of great help. | I have the same job to do.
Firstly the initial seq# will be generated randomly(0-4294967297).
Then the receiver will count the length of the data it received and send the ACK of `seq# + length = x` to the sender. The sequence will then be x and the sender will send the data. Similarly the receiver will count the length `x + length = y` and send the ACK as `y` and so on... Its how the the seq/ack is generated...
If you want to show it practically try to sniff a packet in Wireshark and follow the TCP stream and see the scenario... | TCP: How are the seq / ack numbers generated? | [
"",
"c++",
"networking",
"tcp",
"winpcap",
""
] |
I'm looking for a good IDE for C++ that has most or all of the following properties (well, the first 4 or 5 ones are mandatory):
1. cross-platform (at least Mac, Linux)
2. of course, syntax highlighting and other basic coding editor functionality
* reasonably responsive GUI, not too sluggish on mid-size (say, 100 files) projects (both my Linux and Mac computers are 5 years old)
* code completion
* integration with `gdb`
* SVN integration would be nice too
* refactoring (rename a variable semi-automatically throughout the codebase, etc.)
* can display class hierarchy
* can add hypertext-style links to the code (so you can click on a function/class name and it brings you to the declaration),
* can show code parts that (potentially) call my function (I know that's hard to do for C++ so I added the *potentially*)
So far, I've been using [Emacs](http://www.gnu.org/software/emacs/) for everything, but I think advanced features that give me more overview and search capabilities like the last three would be nice. I'm tired of just using `grep` and `find` on my codebase.
Basically, I want most of the things for C++ development that Java IDEs usually do.
I see [Netbeans](http://www.netbeans.org/features/cpp/) can be used for C++, as well as [Eclipse](http://www.eclipse.org/cdt/). I think they would fit my requirements. Has anyone actually used them for daily coding? What are the differences? What are your experiences? [Code::Blocks](http://www.codeblocks.org/) is more lightweight and doesn't do many of the things listed above, right?
Note: I don't need a GUI builder.
**Update:** With the bullet point 10 I mean that I can give it a function name (e.g. `Foo::setValue`), and it shows me all occurrences where this particular function (and not other functions of the same name, like `Bar::setValue`) is called in my codebase. | Code::Blocks does the first 5 and it's also got class method browsing (though not a heirarchy display). It's a much more lightweight solition thaen Eclipse or NetBeans, but if you like the minimalist approach it's pretty good.
To summarise CB versus your requirements:
1. Yes
2. Yes
3. Yes
4. Yes
5. Yes
6. No - but you can add it easily
7. No
8. No, but similar functionality
9. No
10. Can go from definition to decl and vice versa, but no callers list
As all the solutions you mention are free, you could always try them all and then make a decision on which one to stick with. That's what I did. | In addition to the ones mentioned, there's [QTCreator](http://www.qtsoftware.com/products/appdev/developer-tools/developer-tools), which has "Rapid code navigation tools" though I've not used it.
I think though that the non-essential requirements aren't so good, you can easily see where a method is being called using search! (of course, if you have a huge class hierarchy where every class has the same named method, you've only yourself to blame :) if you havn't laid your classes out in an easily understandable way) | Cross-platform C++ IDEs? | [
"",
"c++",
"ide",
""
] |
I want to have my website do a number of calculations every 10 minutes and then update a database with the results. How exactly do I set such a timer, i am assuming it would be in global.asax? | Doing something like that in a web application is somewhere between difficult and unstable to impossible. Web applications are simply not meant to be run non-stop, only to reply to requests.
Do you really need to do the calculations every ten minutes? I have found that in most cases when someone asks a question like this, they really just need the appearence of something running at an interval, but as long as noone is visiting the page to see the results, the results doesn't really need to be calculated.
If this is true in your case also, then you just need to keep track of when the calculations were done the last time, and for every request check if enough time has gone by to recalculate. | You'd be better off writing a separate non-UI application and then running that as a scheduled task. | How to run automatic "jobs" in asp.net? | [
"",
"c#",
"asp.net",
""
] |
> This is NOT a question on plain old boring customization; I actually want to create an program, you know, with source code, etc...
I'm thinking about programming my own media centre interface, and I figured it'd look better if I coded my own splash screen for when the OS is loading.
*Note:* The media centre interface will be run in X, but this question is regarding what will happen before the X server loads.
Simply, I'd like to make a splash screen application to hide the linux kernel boot messages. Is there a way I can program some animation in to this like some sort of animated progress bar for example? I assume that I won't be able to code any 2D/3D graphics (as that'd require X to be running, right?), so how would I go about generating that?
I'd prefer to do this in C++, but C is also an option.
*Note:* I'm not looking to use any existing "themes" or anything like that, just interested in the programming side of things.
### Update:
Some suggestions have been to use standard images (.bmp, .jpeg, etc), **I am not interested in loading images** in to an existing application. But obviously I may want to load images in to the boot screen application that I will make.
I'm not tied to a Linux distro, so this can be for anything, although Debian or a Debian-based distro would be nice.
I like the suggestion about loading the X server early and running a loading screen from there, however is there not a more direct approach? Surely you can make a program which hides the boot messages and shows a custom program? Obviously this would be very low level programming, but that's what I'm looking for...
Also, I'm **not** interested in altering the boot loader (LILO, GRUB, etc).
### Update 2:
So far good suggestions have been looking at the *source code* for applications like splashy and fbsplash. Can anyone better this suggestion? | For the graphical output you can use the [Linux framebuffer](http://en.wikipedia.org/wiki/Linux_framebuffer), for application development you can use gtk which support rendering directly to the framebuffer [GtkFB](http://www.linuxdevices.com/articles/AT9024868021.html).
For the video and such you can use mplayer which also support rendering to the framebuffer.
For the initialization you have to look around the system used, debian uses a sysv init style initialization <http://www.debian-administration.org/articles/212>, ubuntu uses upstart. | I'd look into [splashy](http://splashy.alioth.debian.org/wiki/) source code. But you will need to code in C.
If you have the skills, you can implement a software based 3D engine (like in the good old days). A simple rotating cube shouldn't be very hard to code and there are tons of tutorials.
The downside is that you will increase the boot time, something not very pleasant in a media center. | How can I code my own custom splash screen for Linux? | [
"",
"c++",
"c",
"linux",
""
] |
I have the following xml file:
```
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<config>
<a>
<b>
<param>p1</param>
<param>p2</param>
</b>
</a>
</config>
```
and the xpath code to get my node params:
```
Document doc = ...;
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/config/a/b");
Object o = expr.evaluate(doc, XPathConstants.NODESET);
NodeList list = (NodeList) o;
```
but it turns out that the nodes list (list) has 5 children, including `"\t\n"`, instead of just two. Is there something wrong with my code? How can I just get my two nodes?
Thank you! | so the xpath looks like:
`/config/a/b/*/text()`.
And the output for :
```
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
```
would be as expected: p1 and p2 | When you select `/config/a/b/`, you are selecting *all* children of `b`, which includes three text nodes and two elements. That is, given your XML above and only showing the fragment in question:
```
<b>
<param>p1</param>
<param>p2</param>
</b>
```
the first child is the text (whitespace) following `<b>` and preceding `<param>p1 ...`. The second child is the first `param` element. The third child is the text (whitespace) between the two `param` elements. And so on. The whitespace isn't ignored in XML, although many forms of processing XML ignore it.
You have a couple choices:
1. Change your xpath expression so it will only select element nodes, as suggested by Ted Dziuba, or
2. Loop over the five nodes returned and only select the non-text nodes.
You could do something like this:
```
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getNodeType() != Node.TEXT_NODE) {
System.out.println(nodes.item(i).getNodeValue());
}
}
```
You can use the node type to select only element nodes, or to remove text nodes. | Why does my XPath expression in Java return too many children? | [
"",
"java",
"xpath",
""
] |
I am new to programming and learning with Wordpress.
```
the_title(); //outputs the title of the page
```
I want to capture the title of the page into a string variable so I can manipulate it with `strtolower` and `str_replace` functions.
The only way I have gotten it to work is with output buffering.
```
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
```
What am I doing wrong? | If what you really are looking for is the `wp_title` function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
```
$mytitle = wp_title(null, false);
```
Otherwise, your only option is to find the function you're looking for and modify the source code. | There is no easier way. Your function does not *return* the string, it *prints* it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
```
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
``` | What is the best way to capture data returned from a function in PHP? | [
"",
"php",
"wordpress",
""
] |
I'm trying to build a report that will look like this:
```
jan feb mar apr may jun jul ago sep oct nov dec
food 0 1 1 2 0 0 3 1 0 0 1 1
car 1 0 0 0 1 2 1 0 1 2 3 4
home 0 0 1 2 2 2 5 1 2 4 0 0
other 0 0 0 0 0 0 0 0 0 0 0 0
```
I have two tables: `t_item` and `t_value`. `t_item` has 2 columns: `itemID` and `itemName`. `t_value` has 3 columns: `itemID`, `value`, `date`.
With the following query I can generate a list with all the itens, even with the empty ones.
```
SELECT t_item.itemID, ISNULL(SUM(t_value.value), 0) AS value
FROM t_value RIGHT OUTER JOIN t_item ON t_value.itemID = t_item.itemID
GROUP BY t_item.itemID
```
But, if I try to include a MONTH column (as follows) the result will show only the items with values...
```
SELECT t_item.itemID, ISNULL(SUM(t_value.value), 0) AS value, MONTH(date) AS date
FROM t_value RIGHT OUTER JOIN t_item ON t_value.itemID = t_item.itemID
GROUP BY t_item.itemID, MONTH(date)
```
Is it possible to do it? How do I include into the results the itens with no values and group then by month?
TIA,
Bob | ```
WITH calendar(mon) AS
(
SELECT 1
UNION ALL
SELECT mon + 1
FROM calendar
WHERE mon < 12
)
SELECT itemID, mon, SUM(value)
FROM calendar c, t_item i
LEFT OUTER JOIN
t_value v
ON v.itemID = i.itemID
AND MONTH(date) = mon
GROUP BY
i.itemID, mon
``` | For the "holes" in your data you need a filler table. Join this table with a full outer join to the fact table on month.
```
month
------
month --values jan through dec
```
For the formating you have a couple options.
* In your reporting tool use the cross tab or matrix function.
* In SQL use the CASE function.
* In SQL use the Pivot function. | SQL query with join, sum, group by, etc | [
"",
"sql",
"sql-server",
""
] |
What is the best method of understanding how and why a framework was written the way it was? | Develop a feature for it, or fix a bug. If you use the framework for developing a real-world solution, you can make a list of shortcomings to address or features to add that would make your task easier.
Fixing a bug will really help you understand the code, because most of the time you are given a piece of example code that recreates it, which you can then trace down into the bowels of hell to find where things go wrong.
All it takes is persistence, really. | Take a very simple component and analyze the code. For example, look at some of the components of the Zend Framework (something utterly simple like `Zend_Version` or, to step up a bit but still keep it simple, `Zend_Debug`). Pick them apart and see what makes them tick. Then, try to write your own simple component. | Understanding Frameworks | [
"",
"php",
"open-source",
"frameworks",
""
] |
I'd like to compile a C++ project with just a single call to `WinExec` in order to launch another executable with some command line parameters. I've no idea what settings to specify in my project in order to get produce an executable that works without requiring Microsoft side-by-side DLLs, which I don't want to have to install on my target system. Any hints?
The symptom is an application which fails to start and the following event getting written to the application log (freely translated from French):
```
Error, SideBySide, event #33
Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.21022.8" cannot be found.
```
*UPDATE: I know that using `WinExec` is bad practice, but it works like a charm, and Microsoft can't possibly remove it in any future release of the API, can't they?* | The solution has been answered (partially) by both jachymko and Josh. Here is the full solution:
1. Set **Project Properties / Configuration / Linker / Input / Ignore All Default Libraries** to **Yes** and add **`kernel32.lib`** to **Additional Dependencies**. This alone won't link, as the code automatically refers to `__security_check_cookie` and `_WinMainCRTStartup`.
2. Remove **/GS** switch to instruct the compiler not to inject the security check code. For this, set **Project Properties / Configuration / C/C++ / Code Generation / Buffer Security Check** to **No**.
3. Set **Project Properties / Configuration / C/C++ / Code Generation / Runtime Library** to **Multi-threaded (/MT)**.
4. The initial Visual Studio 2008 generated code contains an **entry point** named `_tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)`. Modify it by renaming it **`WinMain`** and convert the third argument to **`LPSTR`**.
5. Set **Project Properties / Configuration / Linker / Advanced / Entry Point** to **`WinMain`**.
With these changes to a default C++ project, the code finally compiles and links, and runs on a freshly installed Vista or XP, which lacks the runtime library. | If you specify that you want to statically link the run-time (/MT or /MTd) you should be good. Project Properties->C/C++->Code Generation->Runtime Library | How to build C++ app which runs on plain old XP SP2 with Visual Studio 2008 and no Side-by-Side DLLs? | [
"",
"c++",
"visual-studio-2008",
"side-by-side",
"crt",
""
] |
I want to download a page from the web, it's allowed to do when you are using a simple browser like Firefox, but when I use "file\_get\_contents" the server refuses and replies that it understands the command but don't allow such downloads.
So what to do? I think I saw in some scripts (on Perl) a way to make your script like a real browser by creating a user agent and cookies, which makes the servers think that your script is a real web browser.
Does anyone have an idea about this, how it can be done? | Use CURL.
```
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// set the UA
curl_setopt($ch, CURLOPT_USERAGENT, 'My App (http://www.example.com/)');
// Alternatively, lie, and pretend to be a browser
// curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
?>
```
(From <http://uk.php.net/manual/en/curl.examples-basic.php>) | Yeah, CUrl is pretty good in getting page content. I use it with classes like [DOMDocument][1] and [DOMXPath][2] to grind the content to a usable form.
```
function __construct($useragent,$url)
{
$this->useragent='Firefox (WindowsXP) - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.'.$useragent;
$this->url=$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$this->xpath = new DOMXPath($dom);
}
...
public function displayResults($site)
$data=$this->path[0]->length;
for($i=0;$i<$data;$i++)
{
$delData=$this->path[0]->item($i);
//setting the href and title properties
$urlSite=$delData->getElementsByTagName('a')->item(0)->getAttribute('href');
$titleSite=$delData->getElementsByTagName('a')->item(0)->nodeValue;
//setting the saves and additoinal
$saves=$delData->getElementsByTagName('span')->item(0)->nodeValue;
if ($saves==NULL)
{
$saves=0;
}
//build the array
$this->newSiteBookmark[$i]['source']='delicious.com';
$this->newSiteBookmark[$i]['url']=$urlSite;
$this->newSiteBookmark[$i]['title']=$titleSite;
$this->newSiteBookmark[$i]['saves']=$saves;
}
```
The latter is a part of a class that scrapes data from *delicious.com* .Not very legal though.
[1]: <https://www.php.net/domdocument>
[2]: <https://www.php.net/domxpath> | How to use PHP to get a webpage into a variable | [
"",
"php",
"authentication",
"curl",
"file-get-contents",
""
] |
```
System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
```
And now for some background...
```
string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
```
omgwut is something like this:
> copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav
And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work. | **Try the prefixing your arguments to cmd with `/C`**, effectively saying `cmd /C copy /b t.wav ...`
According to `cmd.exe /?` using
`/C <command>`
> Carries out the command specified by
> string and then terminates
For your code, it might look something like
```
// ..
proc0.StartInfo.Arguments = "/C " + omgwut;
```
**Notes:**
* A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do `cmd.exe copy ...` you'll see that the copy doesn't occur.
* There are limits to the length of the arguments you can pass as arguments. From [MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.arguments.aspx): "The maximum string length is `2,003` characters in .NET Framework applications and `488` characters in .NET Compact Framework applications."
* You can bypass the shelling out to command by using the `System.IO` classes to open the files and manually concatenate them. | Try this it might help you.. Its working with my code.
```
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
``` | Running cmd commands via .NET? | [
"",
"c#",
".net",
"process",
"cmd",
""
] |
I want to have a way to report the stack trace to the user if an exception is thrown. What is the best way to do this?
I'd like it to be portable if possible. I want information to pop up, so the user can copy the stack trace and email it to me if an error comes up. | It depends which platform.
On GCC it's pretty trivial, see [this post](https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes) for more details.
On MSVC then you can use the [StackWalker](http://www.codeproject.com/KB/threads/StackWalker.aspx) library that handles all of the underlying API calls needed for Windows.
You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal. | [Andrew Grant's answer](https://stackoverflow.com/a/691742/913098) does ***not*** help getting a stack trace of the *throwing* function, at least not with GCC, because a throw statement does not save the current stack trace on its own, and the catch handler won't have access to the stack trace at that point any more.
The only way - using GCC - to solve this is to make sure to generate a stack trace at the point of the throw instruction, and save that with the exception object.
This method requires, of course, that every code that throws an exception uses that particular Exception class.
*Update 11 July 2017*: For some helpful code, take a look at [cahit beyaz's answer](https://stackoverflow.com/a/42664648/913098), which points to <http://stacktrace.sourceforge.net> - I haven't used it yet but it looks promising.
*Update 29 July 2023*: Stack trace libraries as of July 2023:
* [C++23 `<stacktrace>`](https://en.cppreference.com/w/cpp/header/stacktrace): C++23 will introduce `<stacktrace>`, which some standard library implementations already [support](https://en.cppreference.com/w/cpp/compiler_support/23#C.2B.2B23_library_features) or partially support.
* [boost stacktrace](https://github.com/boostorg/stacktrace/): Reference implementation for `<stacktrace>` proposed by the authors. It is feature-full but requires various [configuration and dependencies](https://www.boost.org/doc/libs/develop/doc/html/stacktrace/configuration_and_build.html).
* [backward-cpp](https://github.com/bombela/backward-cpp): A widely used library and provides a lot of information, including code snippets for each frame. Depending on your system it has various [configuration and dependencies](https://github.com/bombela/backward-cpp#user-content-configuration--dependencies). It supports most platforms other than mingw.
* [cpptrace](https://github.com/jeremy-rifkin/cpptrace): A newer C++ stack trace library that is simple, portable, and self-contained. | How to display a stack trace when an exception is thrown | [
"",
"c++",
"exception",
"stack-trace",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.