Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
> **Possible Duplicate:**
> [How to remove an XmlNode from XmlNodeList](https://stackoverflow.com/questions/875136/how-to-remove-an-xmlnode-from-xmlnodelist)
Hi, How can i delete a set of nodes from an XML file.?
Here is a code snippet.
```
string path = @"C:\Documents and Settings\e454935\Desktop\NUnitSettings.xml";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
xmldoc.Load(fs);
fs.Close();
xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]);
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
xmldoc.Save(WRITER);
WRITER.Close();
```
I tried the following code simply to delete a node and got
"Object reference not set to an instance of an object." at
```
xmldoc.DocumentElement.RemoveChild(xmldoc.DocumentElement.ChildNodes[1]);
```
Here is a sample XML file,
```
<?xml version="1.0"?>
<Xml1>
<Settings>
<Setting name="DisplayFormat" value="Full" />
<Setting name="File1" value="a" />
<Setting name="File1" value="b" />
<Setting name="File1" value="c" />
<Setting name="File1" value="d" />
</Settings>
</Xml1>
```
Actually from this file i want to delete the **Four File1 nodes** which has the values "a,b,c,d" and then i want to **add a node**,
```
<Setting name="File1" value="e" />
```
How can i do this.? | It may be easier to use XPath to locate the nodes that you wish to delete. [This stackoverflow thread](https://stackoverflow.com/questions/875136/how-to-remove-an-xmlnode-from-xmlnodelist/) might give you some ideas.
In your case you will find the four nodes that you want using this expression:
```
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
``` | You can use [Linq to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx) to do this:
```
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");
``` | How to delete node from XML file using C# | [
"",
"c#",
"xml",
""
] |
I have a database of foods, which I would like to divide into a tree structure of categories, subcategories and sub-subcategories. For example,
fruits -> apples -> fuji, or
fruits -> apples -> cortland
I would like each parent page to show its immediate children (fruits page shows apples, oranges and all other fruit; apples page shows fuji, cortland and all other apples).
Also, I would like each node to know all its parent nodes. (fuji knows that its parent is apple, whose parent is fruit)
What is the best way to store this tree-like relationship using MySQL? | I suggest reading [Managing Hierarchical Data in MySQL](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). | You could try something like:
```
Table category:
id INT AUTO INCREMENT PRIMARY KEY
parent_id INT
name VARCHAR(40)
```
Then when you want to display all the sub-categories of fruit you can do:
```
SELECT C.* FROM category C WHERE C.parent_id = {$currentCategory}
``` | Best way to organize this structure? | [
"",
"php",
"mysql",
"database-design",
""
] |
One of the main reasons I use Hibernate is that it provides the flexibility to switch to another database without having to rewrite any code.
But until now I did not figure out a good way to define additional views on the tables to which my hibernate entities are matched; I am still using simple SQL scripts for that. Is there a more elegant way to define views on tables managed by hibernate?
Ideally I would like to use HQL or another generic method to do the job, so that I don't have to worry about my SQL scripts being incompatible with other kinds of databases.
If there's a way to do that, a second issue would then be to get 'synthetic' read-only instances from these views, which should make it much easier to feed the aggregated data into a UI.
**EDIT:**
It seems as if I didn't make the problem clear enough, so here's what i am trying to do: I want to write code that is independent of the used database. Since I use hibernate, I would just have to change the dialect configuration file and could then use another DBMS.
Question: how to create *views* on my hibernate entities *without* relying on a specific SQL dialect (to keep everything portable), or even HQL? And if that's possible, can I use HQL to also query these views, i.e. to create read-only aggregate entities? Is there any additional hibernate plug-in to help me with that? Haven't found anything so far... :-/ | Hibernate will not automatically create the views for you, as each dialect supports only a limited subset of the data-definition language (DDL) of the underlying database. Basically, it supports enough DDL to generate a working schema, but not enough to handle creation of "extra" objects like views.
All is not lost, though. Hibernate does give you the ability to create (and drop) additional database objects yourself in the XML mapping files, and those objects can be scoped to a particular dialect. For example, I could have a mapping like this:
```
<hibernate-mapping>
<class name='com.mycompany.myproduct.Customer' table='tbl_customer'>
<id name='id' column='customer_id'>
<generator class='native'/>
</id>
<property name='name' length='50' unique='true' not-null='true' />
</class>
<database-object>
<create>create or replace view read_only_cust...</create>
<drop>drop view read_only_cust</drop>
<dialect-scope name='org.hibernate.dialect.Oracle9Dialect' />
</database-object>
</hibernate-mapping>
```
You're free to create whatever additional views you want by adding more "database-object" sections. You have to write the SQL (DDL) yourself for each database you want to support, but since they're scoped to the dialect, Hibernate will only execute the SQL for the dialect chosen at schema export time. | Had the same problem and found the following solution in the hibernate doucmentation:
> There is no difference between a view
> and a base table for a Hibernate
> mapping. This is transparent at the
> database level, although some DBMS do
> not support views properly, especially
> with updates. Sometimes you want to
> use a view, but you cannot create one
> in the database (i.e. with a legacy
> schema). In this case, you can map an
> immutable and read-only entity to a
> given SQL subselect expression:
```
<class name="Summary">
<subselect>
select item.name, max(bid.amount), count(*)
from item
join bid on bid.item_id = item.id
group by item.name
</subselect>
<synchronize table="item"/>
<synchronize table="bid"/>
<id name="name"/>
...
</class>
```
<https://docs.jboss.org/hibernate/stable/core/manual/en-US/html_single/#mapping-declaration> | Elegant ways to handle database views on hibernate entities? | [
"",
"java",
"database",
"hibernate",
""
] |
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1
For example:
```
mylist = ['abc','abcdef','abcd']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
```
Surely there's a simple list comprehension that's short and elegant that I'm overlooking? | From the [Python documentation](http://docs.python.org/whatsnew/2.5.html#other-language-changes) itself, you can use [`max`](http://docs.python.org/library/functions.html#max):
```
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
``` | ```
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
```
or much easier:
```
max(some_list , key = len)
``` | Python's most efficient way to choose longest string in list? | [
"",
"python",
"list",
""
] |
I'm currently working on building a game which is on a planet, the way in which I'm planning to store the data is in 6 2dimensional arrays, which are heightmaps around the sphere (on the faces of a cube).
The problem I have is this, given a normalised vector which points outwards from the centre of the sphere how can I determine these two things:
1. The plane which it intersects
2. The x/y coordinates I should look up in my 2d array to get the height.
My current solution is this (using XNA):
1. Construct a ray pointing out from [0,0] along the direction vector supplied. Loop through each surface and do a ray/plane intersection (which is a method supplied by the XNA framework) to get the distance to the intersection point. Select the closest plane (shortest distance to intersection)
2. Take the 3D point, and convert it to a 2D point which can be used as an array lookup to find the radius (this is the bit I cannot work out the maths for, or find any references to through google).
A helpful constraint is that the sphere/cube system is around the origin.
**So, the problem which needs solving is this:**
Given a direction vector, how do I determine where it intersects the surrounding cube. Using this result how do I then get the correct value in a 2D array which is "painted" on the face of this cube? | Look at the magnitude of each of the 3 components of the direction. The one with the largest magnitude tells you which face of the cube you hit (and its sign tells you if it's the + or - face.)
The other two coordinates give you your 2D mapping values. We need to normalize them, though. If your XYZ direction has X as the highest magnitude, then your 2D face coordinates are just U=Y/X and V=Z/X. These both range from -1 to 1.
Be careful of flips from positive to negative sides, you may need to flip the 2D U and/or V values to match your coordinate system. | ```
# edges are called X_AXIS_POS, X_AXIS_NEG, Y_AXIS_POS, Y_AXIS_NEG, Z_AXIS_POS, Z_AXIS_NEG
if (x*x >= y*y) && (x*x >= z*z) :
return ( (x>0) ? X_AXIS_POS : X_AXIS_NEG, y/abs(x), z/abs(x))
if (y*y >= z*z) && (y*y >= x*x) :
return ( (y>0) ? Y_AXIS_POS : Y_AXIS_NEG, x/abs(y), z/abs(y))
return ( (z>0) ? Z_AXIS_POS : Z_AXIS_NEG, x/abs(z), y/abs(z))
``` | Projecting a sphere onto a cube | [
"",
"c#",
"math",
"3d",
"xna",
""
] |
I have a jquery function ('rater') that I call this way:
```
<div id="someID"></div>
<script type="text/javascript">
$('#someID').rater({options});
</script>
```
I want to get the ID ('someID' in this case) so then I can use it inside the function as a variable.
Then I use it in something like this:
```
if (??? == 'someID') { do something }
```
How can I do it?? | Retrieving the selector used to call the plugin:
```
jQuery.fn.myPlugin = function() {
alert( this.selector );
};
```
You can access the selector as a property of the jQuery object.
So, if I called the plugin like this:
```
$('div #something').myPlugin();
```
Then "div #something" would be alerted.
---
Retrieving an element's ID from within a plugin:
```
jQuery.fn.myPlugin = function() {
alert( this.attr('id') );
};
``` | Not sure why you're trying to do this, but...
```
// create jQuery plugin method: "rater"
jQuery.fn.rater = function()
{
// `this` is a jQuery object: process each matched element
return this.each(function()
{
// `this` is a single matched element. Process it, somehow...
if ( this.id == "someID" )
{
// do something special
}
// normal rater logic, whatever that might be
});
};
``` | How to get the ID of the div the function was called from in jQuery? | [
"",
"javascript",
"jquery",
"variables",
""
] |
Writing simple text on an image using PIL is easy.
```
draw = ImageDraw.Draw(img)
draw.text((10, y), text2, font=font, fill=forecolor )
```
However, when I try to write Hebrew punctuation marks (called "nikud" or ניקוד), the characters do not overlap as they should. (I would guess this question is relevant also to Arabic and other similar languages.)
On supporting environment, these two words take up the same space/width (the below example depends on your system, hence the image):
סֶפֶר ספר
However when drawing the text with PIL I get:
ס ֶ פ ֶ ר
since the library probably doesn't obey kerning(?) rules.
Is it possible to have the character and Hebrew punctuation mark take up the same space/width without manually writing character positioning?
[image - nikud and letter spacing http://tinypic.com/r/jglhc5/5](http://tinypic.com/r/jglhc5/5)
image url: <http://tinypic.com/r/jglhc5/5> | funny, after 5 years, and with great help fron @Nasser Al-Wohaibi, I realized how to do it:
Reversing the text with a BIDI algorithm was needed.
```
# -*- coding: utf-8 -*-
from bidi.algorithm import get_display
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
img= PIL.Image.new("L", (400, 200))
draw = PIL.ImageDraw.Draw(img)
font = PIL.ImageFont.truetype( r"c:\windows\fonts\arial.ttf", 30)
t1 = u'סֶפֶר ספר!'
draw.text( (10,10), 'before BiDi :' + t1, fill=255, font=font)
t2 = get_display(t1) # <--- here's the magic <---
draw.text( (10,50), 'after BiDi: ' + t2, fill=220, font=font)
img.save( 'bidi-test.png')
```
@Nasser's answer has extra value that's probably relevant only to arabic texts (the letters in arabic change shape and connected-ness based on their neiboring letters, in hebrew all letters are separate), so only the bidi part was relevant for this question.
in the sample result,
the 2nd line is the correct form, and correct vocalization marks positioning.

thank you @tzot for help + code snippets
a-propos:
samples of different font behavior with Hebrew "nikud". Not all fonts behave the same:
 | As for **Arabic** diacritics : Python +**Wand**(Python Lib) +arabic\_reshaper(Python Lib) +bidi.algorithme(Python Lib). The same applies to **PIL/Pillow**, you need to use the `arabic_reshaper` and `bidi.algorithm` and pass the generated text to `draw.text((10, 25), artext, font=font)`:
```
from wand.image import Image as wImage
from wand.display import display as wdiplay
from wand.drawing import Drawing
from wand.color import Color
import arabic_reshaper
from bidi.algorithm import get_display
reshaped_text = arabic_reshaper.reshape(u'لغةٌ عربيّة')
artext = get_display(reshaped_text)
fonts = ['C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\DroidNaskh-Bold.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Bold-Oblique.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Bold.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\Thabit-Oblique.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\majalla.ttf',
'C:\\Users\\PATH\\TO\\FONT\\Thabit-0.02\\majallab.ttf',
]
draw = Drawing()
img = wImage(width=1200,height=(len(fonts)+2)*60,background=Color('#ffffff'))
#draw.fill_color(Color('#000000'))
draw.text_alignment = 'right';
draw.text_antialias = True
draw.text_encoding = 'utf-8'
#draw.text_interline_spacing = 1
#draw.text_interword_spacing = 15.0
draw.text_kerning = 0.0
for i in range(len(fonts)):
font = fonts[i]
draw.font = font
draw.font_size = 40
draw.text(img.width / 2, 40+(i*60),artext)
print draw.get_font_metrics(img,artext)
draw(img)
draw.text(img.width / 2, 40+((i+1)*60),u'ناصر test')
draw(img)
img.save(filename='C:\\PATH\\OUTPUT\\arabictest.png'.format(r))
wdiplay(img)
```
 | Writing text with diacritic ("nikud", vocalization marks) using PIL (Python Imaging Library) | [
"",
"python",
"unicode",
"fonts",
"python-imaging-library",
"hebrew",
""
] |
Suppose I have a column of heights -- how can I select all and only those height values that are neither in the top 30% of values nor the bottom 30% of values.
I'd like the answer for PostgreSQL (or, failing that, MySQL -- I'm using Rails). | ```
WITH cte AS (
SELECT *, NTILE(100) OVER (ORDER BY column) as rank
FROM table)
SELECT * FROM cte WHERE rank BETWEEN 30 and 70
``` | For SQL Server 2005 +
```
SELECT
*
FROM
MyTable M
EXCEPT
SELECT
*
FROM
(SELECT TOP 30 PERCENT
*
FROM
MyTable M
ORDER BY
Height
UNION ALL
SELECT TOP 30 PERCENT
*
FROM
MyTable M
ORDER BY
Height DESC) foo
``` | SQL to select the middle third of all values in a column in PostgreSQL | [
"",
"sql",
"mysql",
"math",
"postgresql",
"select",
""
] |
We were thinking about organizing our BIG project this way:
```
\trunk
[CompanyName]
[Product1]
[Project1]
CompanyName.Product1.Project1.csproj
[Project2]
CompanyName.Product1.Project2.csproj
CompanyName.Product1.sln
[Product2]
```
We were trying to follow Microsoft's recommendation that namespace names follow folder structure, but are there any drawbacks for making it this way?
What is the naming convention for solutions and projects that you apply? | That looks pretty good if you ask me. Especially naming your projects by their full name including full name space part. I've found this helpful when there are numerous projects, especially if there happens to be similar projects across different products.
How and whether you split on product and project (where I assume project is more like an application than a solution project) is very much down to the size of your organisation, it's make-up and your preferences. | An alternative that I've used is to have all my solution files in the same directory.
```
\trunk
[CompanyName]
CompanyName.Product1.sln
CompanyName.Product2.sln
[Product1]
[Project1]
CompanyName.Product1.Project1.csproj
[Project2]
CompanyName.Product1.Project2.csproj
[Product2]
[Project3]
CompanyName.Product2.Project3.csproj
``` | Naming convention for Visual Studio solutions and projects | [
"",
"c#",
".net",
"visual-studio",
"namespaces",
"naming-conventions",
""
] |
When I do `1/2` in Python why does it give me zero? Even if I coerce it with `float(1/2)` still I get zero. Why? And how can I get around it?
When I give `arctan(1/2)` I get 0 as answer, but when I give `arctan(.5)` I get the correct answer! | Because Python 2.x uses integer division for integers, so:
```
1/2 == 0
```
evaluates to True.
You want to do:
```
1.0/2
```
or do a
```
from __future__ import division
``` | First, `1/2` is integer division. Until Python 3.0.
```
>>> 1/2
0
>>> 1.0/2.0
0.5
>>>
```
Second, use `math.atan2` for this kind of thing.
```
>>> math.atan2(1,2)
0.46364760900080609
>>> math.atan(.5)
0.46364760900080609
``` | Error while I use math.atan in Python! | [
"",
"python",
""
] |
What would be a good way to detect a C++ memory leak in an embedded environment? I tried overloading the new operator to log every data allocation, but I must have done something wrong, that approach isn't working. Has anyone else run into a similar situation?
This is the code for the new and delete operator overloading.
EDIT:
Full disclosure: I am looking for a memory leak in my program and I am using this code that someone else wrote to overload the new and delete operator. Part of my problem is the fact that I don't fully understand what it does. I know that the goal is to log the address of the caller and previous caller, the size of the allocation, a 1 if we are allocating, a 2 if we are deallocation. plus the name of the thread that is running.
Thanks for all the suggestions, I am going to try a different approach that someone here at work suggested. If it works, I will post it here.
Thanks again to all you first-rate programmers for taking the time to answer.
StackOverflow rocks!
**Conclusion**
Thanks for all the answers. Unfortunately, I had to move on to a different more pressing issue. This leak only occurred under a highly unlikely scenario. I feel crappy about just dropping it, I may go back to it if I have more time. I chose the answer I am most likely to use.
```
#include <stdlib.h>
#include "stdio.h"
#include "nucleus.h"
#include "plus/inc/dm_defs.h"
#include "plus/inc/pm_defs.h"
#include "posix\inc\posix.h"
extern void* TCD_Current_Thread;
extern "C" void rd_write_text(char * text);
extern PM_PCB * PMD_Created_Pools_List;
typedef struct {
void* addr;
uint16_t size;
uint16_t flags;
} MemLogEntryNarrow_t;
typedef struct {
void* addr;
uint16_t size;
uint16_t flags;
void* caller;
void* prev_caller;
void* taskid;
uint32_t timestamp;
} MemLogEntryWide_t;
//size lookup table
unsigned char MEM_bitLookupTable[] = {
0,1,1,2,1,2,2,3,1,2,2,3,1,3,3,4
};
//#pragma CODE_SECTION ("section_ramset1_0")
void *::operator new(unsigned int size)
{
asm(" STR R14, [R13, #0xC]"); //save stack address temp[0]
asm(" STR R13, [R13, #0x10]"); //save pc return address temp[1]
if ( loggingEnabled )
{
uint32_t savedInterruptState;
uint32_t currentIndex;
// protect the thread unsafe section.
savedInterruptState = NU_Local_Control_Interrupts(NU_DISABLE_INTERRUPTS);
// Note that this code is FRAGILE. It peeks backwards on the stack to find the return
// address of the caller. The location of the return address on the stack can be easily changed
// as a result of other changes in this function (i.e. adding local variables, etc).
// The offsets may need to be adjusted if this function is touched.
volatile unsigned int temp[2];
unsigned int *addr = (unsigned int *)temp[0] - 1;
unsigned int count = 1 + (0x20/4); //current stack space ***
//Scan for previous store
while ((*addr & 0xFFFF0000) != 0xE92D0000)
{
if ((*addr & 0xFFFFF000) == 0xE24DD000)
{
//add offset in words
count += ((*addr & 0xFFF) >> 2);
}
addr--;
}
count += MEM_bitLookupTable[*addr & 0xF];
count += MEM_bitLookupTable[(*addr >>4) & 0xF];
count += MEM_bitLookupTable[(*addr >> 8) & 0xF];
count += MEM_bitLookupTable[(*addr >> 12) & 0xF];
addr = (unsigned int *)temp[1] + count;
// FRAGILE CODE ENDS HERE
currentIndex = currentMemLogWriteIndex;
currentMemLogWriteIndex++;
if ( memLogNarrow )
{
if (currentMemLogWriteIndex >= MEMLOG_SIZE/2 )
{
loggingEnabled = false;
rd_write_text( "Allocation Logging is complete and DISABLED!\r\n\r\n");
}
// advance the read index if necessary.
if ( currentMemLogReadIndex == currentMemLogWriteIndex )
{
currentMemLogReadIndex++;
if ( currentMemLogReadIndex == MEMLOG_SIZE/2 )
{
currentMemLogReadIndex = 0;
}
}
NU_Local_Control_Interrupts(savedInterruptState);
//Standard operator
//(For Partition Analysis we have to consider that if we alloc size of 0 always as size of 1 then are partitions must be optimized for this)
if (size == 0) size = 1;
((MemLogEntryNarrow_t*)memLog)[currentIndex].size = size;
((MemLogEntryNarrow_t*)memLog)[currentIndex].flags = 1; //allocated
//Standard operator
void * ptr;
ptr = malloc(size);
((MemLogEntryNarrow_t*)memLog)[currentIndex].addr = ptr;
return ptr;
}
else
{
if (currentMemLogWriteIndex >= MEMLOG_SIZE/6 )
{
loggingEnabled = false;
rd_write_text( "Allocation Logging is complete and DISABLED!\r\n\r\n");
}
// advance the read index if necessary.
if ( currentMemLogReadIndex == currentMemLogWriteIndex )
{
currentMemLogReadIndex++;
if ( currentMemLogReadIndex == MEMLOG_SIZE/6 )
{
currentMemLogReadIndex = 0;
}
}
((MemLogEntryWide_t*)memLog)[currentIndex].caller = (void *)(temp[0] - 4);
((MemLogEntryWide_t*)memLog)[currentIndex].prev_caller = (void *)*addr;
NU_Local_Control_Interrupts(savedInterruptState);
((MemLogEntryWide_t*)memLog)[currentIndex].taskid = (void *)TCD_Current_Thread;
((MemLogEntryWide_t*)memLog)[currentIndex].size = size;
((MemLogEntryWide_t*)memLog)[currentIndex].flags = 1; //allocated
((MemLogEntryWide_t*)memLog)[currentIndex].timestamp = *(volatile uint32_t *)0xfffbc410; // for arm9
//Standard operator
if (size == 0) size = 1;
void * ptr;
ptr = malloc(size);
((MemLogEntryWide_t*)memLog)[currentIndex].addr = ptr;
return ptr;
}
}
else
{
//Standard operator
if (size == 0) size = 1;
void * ptr;
ptr = malloc(size);
return ptr;
}
}
//#pragma CODE_SECTION ("section_ramset1_0")
void ::operator delete(void *ptr)
{
uint32_t savedInterruptState;
uint32_t currentIndex;
asm(" STR R14, [R13, #0xC]"); //save stack address temp[0]
asm(" STR R13, [R13, #0x10]"); //save pc return address temp[1]
if ( loggingEnabled )
{
savedInterruptState = NU_Local_Control_Interrupts(NU_DISABLE_INTERRUPTS);
// Note that this code is FRAGILE. It peeks backwards on the stack to find the return
// address of the caller. The location of the return address on the stack can be easily changed
// as a result of other changes in this function (i.e. adding local variables, etc).
// The offsets may need to be adjusted if this function is touched.
volatile unsigned int temp[2];
unsigned int *addr = (unsigned int *)temp[0] - 1;
unsigned int count = 1 + (0x20/4); //current stack space ***
//Scan for previous store
while ((*addr & 0xFFFF0000) != 0xE92D0000)
{
if ((*addr & 0xFFFFF000) == 0xE24DD000)
{
//add offset in words
count += ((*addr & 0xFFF) >> 2);
}
addr--;
}
count += MEM_bitLookupTable[*addr & 0xF];
count += MEM_bitLookupTable[(*addr >>4) & 0xF];
count += MEM_bitLookupTable[(*addr >> 8) & 0xF];
count += MEM_bitLookupTable[(*addr >> 12) & 0xF];
addr = (unsigned int *)temp[1] + count;
// FRAGILE CODE ENDS HERE
currentIndex = currentMemLogWriteIndex;
currentMemLogWriteIndex++;
if ( memLogNarrow )
{
if ( currentMemLogWriteIndex >= MEMLOG_SIZE/2 )
{
loggingEnabled = false;
rd_write_text( "Allocation Logging is complete and DISABLED!\r\n\r\n");
}
// advance the read index if necessary.
if ( currentMemLogReadIndex == currentMemLogWriteIndex )
{
currentMemLogReadIndex++;
if ( currentMemLogReadIndex == MEMLOG_SIZE/2 )
{
currentMemLogReadIndex = 0;
}
}
NU_Local_Control_Interrupts(savedInterruptState);
// finish logging the fields. these are thread safe so they dont need to be inside the protected section.
((MemLogEntryNarrow_t*)memLog)[currentIndex].addr = ptr;
((MemLogEntryNarrow_t*)memLog)[currentIndex].size = 0;
((MemLogEntryNarrow_t*)memLog)[currentIndex].flags = 2; //unallocated
}
else
{
((MemLogEntryWide_t*)memLog)[currentIndex].caller = (void *)(temp[0] - 4);
((MemLogEntryWide_t*)memLog)[currentIndex].prev_caller = (void *)*addr;
if ( currentMemLogWriteIndex >= MEMLOG_SIZE/6 )
{
loggingEnabled = false;
rd_write_text( "Allocation Logging is complete and DISABLED!\r\n\r\n");
}
// advance the read index if necessary.
if ( currentMemLogReadIndex == currentMemLogWriteIndex )
{
currentMemLogReadIndex++;
if ( currentMemLogReadIndex == MEMLOG_SIZE/6 )
{
currentMemLogReadIndex = 0;
}
}
NU_Local_Control_Interrupts(savedInterruptState);
// finish logging the fields. these are thread safe so they dont need to be inside the protected section.
((MemLogEntryWide_t*)memLog)[currentIndex].addr = ptr;
((MemLogEntryWide_t*)memLog)[currentIndex].size = 0;
((MemLogEntryWide_t*)memLog)[currentIndex].flags = 2; //unallocated
((MemLogEntryWide_t*)memLog)[currentIndex].taskid = (void *)TCD_Current_Thread;
((MemLogEntryWide_t*)memLog)[currentIndex].timestamp = *(volatile uint32_t *)0xfffbc410; // for arm9
}
//Standard operator
if (ptr != NULL) {
free(ptr);
}
}
else
{
//Standard operator
if (ptr != NULL) {
free(ptr);
}
}
}
``` | One way is to insert file name and line number strings (via pointer) of the module allocating memory into the allocated block of data. The file and line number is handled by using the C++ standard "`__FILE__`" and "`__LINE__`" macros. When the memory is de-allocated, that information is removed.
One of our systems has this feature and we call it a "memory hog report". So anytime from our CLI we can print out all the allocated memory along with a big list of information of who has allocated memory. This list is sorted by which code module has the most memory allocated. Many times we'll monitor memory usage this way over time, and eventually the memory hog (leak) will bubble up to the top of the list. | If you're running Linux, I suggest trying [Valgrind](http://www.valgrind.org/). | How to find a memory leak in C++ | [
"",
"c++",
"memory-leaks",
"embedded",
""
] |
Let me provide a little detail to explain what I'm trying to accomplish before I get into the nuts and bolts of the question.
I've got two data sources - one is a SQL Server containing part numbers, descriptions, etc. The other is a CAD system that does not have a database in a traditional sense. What I'm trying to do is read out the bill of materials from the SQL Server and compare it to the CAD assembly drawing to ensure that the CAD system contains the same information as the SQL Server.
Getting the data from the SQL Server is fairly straight forward. I query the database and populate a datagrid. Done. Quick. Easy.
Getting the data from the CAD system is a little more involved. I have to load the assembly drawing to get a listing of all the component parts and then load those individual drawings to pull the "Part Number" property from the drawing. This is a somewhat time consuming and slow process (unfortunately) since each of the files must actually be accessed. I load those properties into an array (I guess a list might be more efficient).
So now I have a datagrid and array with part numbers. I need to compare them and colorize the grid accordingly. The grid should remain transparent if the part exists in both, color the row yellow if it only exists in the grid, and add a row colored red if only in the array.
As best I can tell, this means looping through the array on each line of the grid. The thought process is this:
1. Default the grid to yellow rows.
2. Loop through the grid and loop through the array to compare. If a match is found, make the row transparent and delete the element from the array.
3. After step 2 is completed, the array should only contain elements that are not found in the grid. Resize the array to remove the empty elements.
4. Add the elements of the array to the grid and color those new rows red.
The problems with this logic is that it seems expensive from a performance standpoint. Surely there is a better method? Also, if I modify the grid in some manner (like a resort) I have to go through the process again. I'd really appreciate some advice on this.
Thanks!
Note: written in Visual Studio 2005. | You could load the data from the CAD system in a dictionary (indexed by part number). Then you could go through the grid and check if it exists in the dictionary, which is a fast operation ( O(1) ). You could do exactly as you say, remove the found elements in the dictionary and add the remaining elements in the datagrid.
Here's some code for creating and using a dictionary (used C# style comments to preserve formatting):
```
//First argument is your key type, second is your item type
Dim cadParts As New Dictionary(Of Integer, Part)
//Add items to the parts dictionary
For Each part As Part In cadPartsArray
cadParts.Add(part.PartNumber,part)
Next
//Check if a part exists
Dim partNumber As Integer = 12345
If cadParts.ContainsKey(partNumber) ...
//Remove a part
cadParts.Remove(partNumber)
//Go through the remaining values
For Each part As Part In cadParts.Values ...
```
Edit:
1) Yes, if your key (here, part number) is a string, then a Dictionary(Of String,...) would be used.
2) I assumed you had a class named Part, which contained some information about a part. If you just have a part number, and no other info, then you could create a Hashset instead. It is basically the same as a dictionary, but with this structure the value is also your key. You would create a hashset like this:
```
Dim cadParts As New Hashset(Of String)
```
I won't go through code examples because it is very close to the Dictionary. ContainsKey becomes Contains, and Add accepts only one argument (which would be your part number here).
3) Yes, loop through them and add them to the hashset. | If part number is unique (it is not repeated in the values you want to search for) then you can use sorted dictionary. Then remove the duplicates and use remaining items.
To compare you can use part number as follows:
```
if(dictionary.ContainsKey(partNumber))
dictionary.Remove(partNumber)
end if
``` | Comparing arrays in VB.NET | [
"",
"sql",
"vb.net",
"arrays",
""
] |
I am going to start a new application which mainly consist NavigationPane, Grid, Toolbar. Layout should look like this demo page <http://www.gwt-ext.com/demo/>
I am quite confused which one to use in terms of writing less code, more performant, etc..
Could someone tell the pros and cons of all these technologies.
All the while I coded in javascript, so that way ExtJs seems to be the easy one for me to code. But I am curios to try GWT Ext, Is it true that it could do a lot just by writing few lines of java code.
For eg: To achieve the layout ( given in above gwt ext demo url), which one should I opt ExtJs or GWT Ext.
I read SmartGWT is relatively slower than GwtEXT. Does it have any advantage over GWT EXT. I am also looking for hibernate based data modules ( as my application is going to have many database calls). Anyone of SmartGWT or GWTExt has support for such modules. I came to know that smartgwt doesn't offer all of smartclient enterprise version functionalities, that we are allowed only a few of smartclient features. Will it be an issue?
Your response is highly appreciated. | To write the least code, use SmartGWT Pro. It provides a wizard that allows you to just pick from a list of Hibernate entities you've created, and instantly you have the ability to perform all CRUD operations on that entity, no code required. Then you can add business logic.
The wizard:
<http://www.smartclient.com/smartgwtee/showcase/#tools_hibernate_wizard>
The link about is just screenshots, but there are several Hibernate samples in the showcase. See especially the Master-Detail Batch Load and Save sample.
As far as performance, real-world performance of most enterprise apps is dictated by how often the application has to contact the server. In this area SmartGWT has a large lead because of features like Adaptive Filtering (see the Featured area in the SmartGWT showcase).
Almost all reports we receive of SmartGWT being "slow" are due to having Firebug enabled. Disable Firebug and performance is fine, so normal end users will never perceive slowness. | The GWT-Ext main page now says
"GWT-Ext is no longer under active development and has been superseded by Smart GWT. Assistance will be provided to existing users of GWT-Ext looking to migrate to Smart GWT."
so why would anyone use it? | ExtJs Vs Ext GWT Vs SmartGWT | [
"",
"javascript",
"extjs",
"smartgwt",
"gwt-ext",
""
] |
I'm building classes that interface with the Twitter API, and I'm wondering whether PHP's built-in XML or JSON parser is faster? Twitter will send me the same data in either format, so PHP performance will determine my choice. I'm using php\_apc, so you can disregard parse time and assume I'm running off bytecode.
Thanks!
more: I'm just looking to get associative arrays from the data. I'm not doing tree walking, node iteration or anything too complex. The format will always be the same. (I hope!) | I didn't do any benchmark but...
Since JSON is only a description of nested string sequences, without the need to offer a DOM interface, attributes parsing and other subtle stuff, my guess is that a JSON parser is WAY faster that an XML parser. | The comment from Adam above convinced me to benchmark it. Using <https://twitter.com/status/mentions.[format]>, I found that simplexml\_load\_string() is SLIGHTLY faster than json\_decode(). But the difference is practically a margin of error.
```
Test #1 time (xml): 3.75221395493 seconds
Test #2 time (xml): 4.1562371254 seconds
Test #3 time (xml): 3.60420489311 seconds
Test #4 time (xml): 3.85622000694 seconds
Test #5 time (xml): 3.89622211456 seconds
```
versus
```
Test #1 time (json): 4.53225803375 seconds
Test #2 time (json): 4.06823205948 seconds
Test #3 time (json): 4.03222990036 seconds
Test #4 time (json): 3.80421590805 seconds
Test #5 time (json): 3.88022208214 seconds
```
on the following code (where I've already curl'ed the data to a file, data.[xml,json]).
```
<?php
$test = 'json'; //xml or json
$data = implode(file("data.".$test),"\r\n");
for ($t=1; $t<=5; $t++) {
$start[$t] = microtime(1);
for ($i=0; $i<3000; $i++) {
if ($test == 'xml') $xml = simplexml_load_string($data);
else $json = json_decode($data);
}
$end[$t] = microtime(1);
echo "<p>Test #{$t} time ({$test}): " . ($end[$t] - $start[$t]). " seconds</p>";
}
``` | PHP: is JSON or XML parser faster? | [
"",
"php",
"xml",
"json",
"performance",
""
] |
I have a table that contains information for 4 electrical generators. I would like to have the results of the four querys in one row. Does any one have a suggestion?
```
SELECT avg(KW) as GEN_101_AVG
FROM genset WHERE (GenSetName like 'GEA3519') and GenDate >= '1 jan 2003 00:00:00' and GenDate < '1 feb 2003 00:00:00'
SELECT avg(KW) as GEN_201_AVG
FROM genset WHERE (GenSetName like 'GEA3520') and GenDate >= '1 jan 2003 00:00:00' and GenDate < '1 feb 2003 00:00:00'
SELECT avg(KW) as GEN_301_AVG
FROM genset WHERE (GenSetName like 'GEA3521') and GenDate >= '1 jan 2003 00:00:00' and GenDate < '1 feb 2003 00:00:00'
SELECT avg(KW) as GEN_401_AVG
FROM genset WHERE (GenSetName like 'GEA3522') and GenDate >= '1 jan 2003 00:00:00' and GenDate < '1 feb 2003 00:00:00'
``` | ```
SELECT (
SELECT avg(KW)
FROM genset
WHERE (GenSetName like 'GEA3519')
and GenDate >= '1 jan 2003 00:00:00'
and GenDate < '1 feb 2003 00:00:00'
) AS avg_GEA3519,
(
SELECT avg(KW)
FROM genset
WHERE (GenSetName like 'GEA3520')
and GenDate >= '1 jan 2003 00:00:00'
and GenDate < '1 feb 2003 00:00:00'
) AS avg_GEA3520,
(
SELECT avg(KW)
FROM genset
WHERE (GenSetName like 'GEA3521')
and GenDate >= '1 jan 2003 00:00:00'
and GenDate < '1 feb 2003 00:00:00'
) AS avg_GEA3521,
(
SELECT avg(KW)
FROM genset
WHERE (GenSetName like 'GEA3522')
and GenDate >= '1 jan 2003 00:00:00'
and GenDate < '1 feb 2003 00:00:00'
) AS avg_GEA3522
```
, or in `SQL Server 2005+`, this:
```
SELECT [GEA3519], [GEA3520], [GEA3521], [GEA3522]
FROM (
SELECT GenSetName, KW
FROM genset
WHERE GenDate >= '1 Jan 2003 00:00:00'
AND GenDate < '1 Feb 2003 00:00:00'
) AS q
PIVOT
(
AVG(KW)
FOR GenSetName IN (['GEA3519'], ['GEA3520'], ['GEA3521'], ['GEA3522']
)
``` | Another option:
```
SELECT
AVG(GEN_101.kw) AS GEN_101_AVG,
AVG(GEN_201.kw) AS GEN_201_AVG,
AVG(GEN_301.kw) AS GEN_301_AVG,
AVG(GEN_401.kw) AS GEN_401_AVG
FROM
Genset GEN_101
INNER JOIN Genset GEN_201 ON
GEN_201.GenSetName = 'GEA3520' AND
GEN_201.GenDate >= '1 jan 2003 00:00:00' AND
GEN_201.GenDate < '1 feb 2003 00:00:00'
INNER JOIN Genset GEN_101 ON
GEN_301.GenSetName = 'GEA3521' AND
GEN_301.GenDate >= '1 jan 2003 00:00:00' AND
GEN_301.GenDate < '1 feb 2003 00:00:00'
INNER JOIN Genset GEN_101 ON
GEN_401.GenSetName = 'GEA3522' AND
GEN_401.GenDate >= '1 jan 2003 00:00:00' AND
GEN_401.GenDate < '1 feb 2003 00:00:00'
WHERE
GEN_101.GenSetName = 'GEA3519' AND
GEN_101.GenDate >= '1 jan 2003 00:00:00' AND
GEN_101.GenDate < '1 feb 2003 00:00:00'
``` | How do I take the results of multiple selects and combine into one row | [
"",
"sql",
"sql-server",
"t-sql",
"pivot",
""
] |
To set the background: I'm interested in:
* Capturing implicit signals of interest in books as users browse around a site. The site is written in django (python) using mysql, memcached, ngnix, and apache
Let's say, for instance, my site sells books. As a user browses around my site I'd like to keep track of which books they've viewed, and how many times they've viewed them.
Not that I'd store the data this way, but ideally I could have on-the-fly access to a structure like:
```
{user_id : {book_id: number_of_views, book_id_2: number_of_views}}
```
I realize there are a few approaches here:
* Some flat-file log
* Writing an object to a database every time
* Writing to an object in memcached
I don't really know the performance implications, but I'd rather not be writing to a database on every single page view, and the lag writing to a log and computing the structure later seems not quick enough to give good recommendations on-the-fly as you use the site, and the memcached appraoch seems fine, but there's a cost in keeping this obj in memory: you might lose it, and it never gets written somewhere 'permanent'.
What approach would you suggest? (doesn't have to be one of the above) Thanks! | If this data is not an unimportant statistic that might or might not be available I'd suggest taking the simple approach and using a model. It will surely hit the database everytime.
Unless you are absolutely positively sure these queries **are** actually degrading overall experience there is no need to worry about it. Even if you optimize this one, there's a good chance other *unexpected* queries are wasting more CPU time. I assume you wouldn't be asking this question if you were testing all other queries. So why risk premature optimization on this one?
An advantage of the model approach would be *having an API in place*. When you have tested and decided to optimize you can keep this API and change the underlying model with something else (which will most probably be more complex than a model).
I'd definitely go with a model first and see how it performs. (and also how other parts of the project perform) | *What approach would you suggest? (doesn't have to be one of the above) Thanks!*
hmmmm ...this like been in a four walled room with only one door and saying i want to get out of room but not through the only door...
There was an article i was reading sometime back (can't get the link now) that says memcache can handle huge (facebook uses it) sets of data in memory with very little degradation in performance...my advice is you will need to explore more on memcache, i think it will do the trick. | Capturing Implicit Signals of Interest in Django | [
"",
"python",
"mysql",
"django",
"collaborative-filtering",
""
] |
I'm having difficulty setting up a simple menu that displays results on a div box:
I have a list of 10 links which link to php files on my server that return data.
I would like it so that when the viewer clicks on one of the links, the data from the php file will display on a div box on the screen, and then when he clicks on another link, it will display the data from that php file in the div box (replacing the previous text).
I know this is pretty simple, but I can't get it to work. I'm using jQuery, and would like to know if any of you have any quick solutions.
Thanks!!
UPDATE: I've been pretty much failing javascript code-wise. But here is the basic idea for the framework:
```
<div class="tabs">
<ul class="tabNavigation" style="float:left; padding:1px;">
<li><a href="#displayphpfile">Load phpfile1</a></li>
<li><a href="#displayphpfile">Load phpfile2</a></li>
<li><a href="#displayphpfile">Load phpfile3</a></li>
</ul>
<div id="displayphpfile">
<p>Load phpfile1</p>
</div>
</div>
``` | jQuery has a specific method for doing that: load().
I would change your example a little though, so the hrefs of the links point to the php file:
```
<div class="tabs">
<ul class="tabNavigation" style="float:left; padding:1px;">
<li><a href="phpfile1.php">Load phpfile1</a></li>
<li><a href="phpfile2.php">Load phpfile2</a></li>
<li><a href="phpfile3.php">Load phpfile3</a></li>
</ul>
<div id="displayphpfile">
<p>Load phpfile1</p>
</div>
</div>
```
Then the code is very simple:
```
$(document).ready(function() {
$(".tabNavigation a").click(function() {
$("#displayphpfile").load($(this).attr("href"));
return false;
});
});
``` | I haven't tested this, but is this close to what you want?
```
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function() {
var file = $(this).text().toLowerCase() + '.php';
$.ajax({
url:file,
cache:false,
success: function(response) {
$('#data_goes_here').html(response);
}
});
return false;
});
});
</script>
<ol>
<li><a href="#">Foo</a></li>
<li><a href="#">Bar</a>
<li><a href="#">Baz</a></li>
</ol>
<div id="data_goes_here"></div>
``` | Simple ajax onclick question | [
"",
"php",
"jquery",
"ajax",
""
] |
I could swear I saw an object being created this way. What does somethingelse do? | Taking it quite literally, it can be that the class `JSomething` has a field called `somethingelse` that is of type `JSomething`:
```
class JSomething {
JSomething somethingelse;
}
```
In that case, the reference to the `JSomething` called `somethingelse` inside the `JSomething` can be obtained by the following:
```
JSomething something = new JSomething().somethingelse;
```
However, I suspect that this was seen as part of a [design pattern](http://en.wikipedia.org/wiki/Design_pattern_(computer_science)) called the [builder pattern](http://en.wikipedia.org/wiki/Builder_pattern) -- where a method call returns an instance of the same type.
For example, take the [`StringBuilder.append`](http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html#append(java.lang.String)) method -- it returns a [`StringBuilder`](http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html). Therefore, it would be possible to do the following:
```
StringBuilder sb = new StringBuilder("Hello").append("World!");
``` | It seems that new JSomething().somethingelse is just a field access. Maybe a badly written static access of JSomething.somethingelse. For example `Color color = new Color(0).black;` instead of `Color color = Color.black;`. | JSomething something = new JSomething().somethingelse; | [
"",
"java",
"object",
"methods",
""
] |
I have a subscription based website (with a monthly fee) and I would like to prevent users from sharing accounts in order to avoid paying the monthly fee.
Is there a way this can be done?
Cheers,
Mike | The approach with IP is not suitable, because there are users that use the same external ip in order to surf the web. But in some cases it's a suitable approach(let's say in an intranet web application for example).
You can monitor the number of concurent sessions for the same login. Than one approach would be to log when more than 1 concurent session is present for the same login. Than you may analyse the logs.
Base on these data you may take some actions. good luck. | Keep a log of the IP adresses of the account. If it changes quickly and oftenly I think it is safe to assume that the account is used by multiple people. | How do I prevent users from sharing the same account? (ASP.NET MVC) | [
"",
"c#",
"asp.net-mvc",
"security",
""
] |
I manage a group of programmers. I do value my employees opinion but lately we've been divided as to which framework to use on web projects.
I personally favor **[MooTools](http://mootools.net/)**, but some of my team seems to want to migrate to [jQuery](http://jquery.com/) because it is more widely adopted. That by itself is not enough for me to allow a migration.
I have used both **[jQuery](http://jquery.com/)** and **[MooTools](http://mootools.net/)**. [This particular essay](http://jqueryvsmootools.com/) tends to reflect how I feel about both frameworks. **[jQuery](http://jquery.com/)** is great for DOM Manipulation, but seem to be limited to helping you do that.
Feature wise, both **[jQuery](http://jquery.com/)** and **[MooTools](http://mootools.net/)** allow for easy **DOM Selection and Manipulation**:
```
// jQuery
$('#someContainer div[class~=dialog]')
.css('border', '2px solid red')
.addClass('critical');
// MooTools
$('#someContainer div[class~=dialog]')
.setStyle('border', '2px solid red')
.addClass('critical');
```
Both **[jQuery](http://jquery.com/)** and **[MooTools](http://mootools.net/)** allow for easy **AJAX**:
```
// jQuery
$('#someContainer div[class~=dialog]')
.load('/DialogContent.html');
// MooTools (Using shorthand notation, you can also use Request.HTML)
$('#someContainer div[class~=dialog]')
.load('/DialogContent.html');
```
Both **[jQuery](http://jquery.com/)** and **[MooTools](http://mootools.net/)** allow for easy **DOM Animation**:
```
// jQuery
$('#someContainer div[class~=dialog]')
.animate({opacity: 1}, 500);
// MooTools (Using shorthand notation, you can also use Fx.Tween).
$('#someContainer div[class~=dialog]')
.set('tween', {duration: 500})
.tween('opacity', 1);
```
**[jQuery](http://jquery.com/)** offers the following extras:
* Large community of supporters
* Plugin Repository
* Integration with Microsoft's ASP.NET and VisualStudio
* Used by Microsoft, Google and others
**[MooTools](http://mootools.net/)** offers the following extras:
* Object Oriented Framework with Classic OOP emulation for JS
* Extended native objects
* Higher consistency between browsers for native functions support.
* More easy code reuse
* Used by The World Wide Web Consortium, Palm and others.
Given that, it seems that **[MooTools](http://mootools.net/)** does everything **[jQuery](http://jquery.com/)** does and more (some things I cannot do in **[jQuery](http://jquery.com/)** and I can in **[MooTools](http://mootools.net/)**) but **[jQuery](http://jquery.com/)** has a smaller learning curve.
So the question is, why did you or your team choose **[jQuery](http://jquery.com/)** over another JavaScript framework?
**Note:** While I know and admit **[jQuery](http://jquery.com/)** is a great framework, there are other options around and I'm trying to take a decision as to why **[jQuery](http://jquery.com/)** should be our choice versus what we use right now (**[MooTools](http://mootools.net/)**)? | That's an odd question... I get the impression that...
1. you are very familiar with mootools and take full advantage of its OOP model, making your code easier to manage and support already.
2. you realise that jQuery's purpose is somewhat different and tweaked towards DOM manipulation and AJAX and that mootools does do everything jQuery does AND then some.
3. sounds as if you do not need to be using much in the way of 3-rd party plugins which makes the points of jQuery's popularity and support a bit less important.
Bottom line, is it the hype? jQuery is turning into one of these magical marketing buzzwords like 'AJAX', .NET and Web 2.0 — which is great for them but why do *you* need to justify staying with the framework that works so well for you? There's also the business considerations which I imagine will cover things like:
* framework longevity, or is mootools likely to go away in the face of the ever growing jQuery — very doubtful, seeing as they just released 1.3 beta 1 and have 2.0 is in the pipelines for release by the end of the year.
* cost of staff and their training (I imagine finding mootools programmers will be more difficult than these that slap jquery on their C.V / resume).
* time (and cost) taken to maintain and extend your systems under each framework given your resources.
Both frameworks are great but I believe your interests are best served in staying with mootools. | Personally, jQuery does exactly what I need.
I try to do most of my stuff in my server-side code, which is well structured: it has proper OOP, layers, and an MVC architecture. When I *need* to do something with Javascript, I have found (so far) that jQuery has what I need. Frankly, that falls into three categories:
* **Simple DOM manipulation**, usually showing/hiding stuff without hitting the server.
* **Ajax calls**, nuff said.
* **UI perks**, including modal popups, animations, fading transitions from/to hidden/shown. I am a hardcore backend coding guy, and I *suck* at UI stuff. I really like that jQuery lets me *programmatically* make stuff that looks appealing.
On top of that, the jQuery plugin library is huge, and I've found quite a few libraries that simplify my client-side work. Good stuff.
MooTools introduces OO thinking, which is nice, but not what I need. I want to keep my structuredness all on the backend, and not have to introduce that thinking to my client-side code. To me, client-side code is a very small piece of the emphasis and thinking about it from a Class-point-of-view is way overkill, and way more work. I feel like I'd be building two applications instead of one if I were to use what I'd think would be best practices for MooToools.
I think that sums up why its so popular, especially around here. By and large, we're backend code-y type people, and jQuery lets us make an appealing UI programmatically, and lets us focus on our backend core. | Why is jQuery so widely adopted versus other Javascript frameworks? | [
"",
"javascript",
"jquery",
"frameworks",
"mootools",
""
] |
I'm still stuck on my problem of trying to parse articles from wikipedia. Actually I wish to parse the infobox section of articles from wikipedia i.e. my application has references to countries and on each country page I would like to be able to show the infobox which is on corresponding wikipedia article of that country. I'm using php here - I would greatly appreciate it if anyone has any code snippets or advice on what should I be doing here.
Thanks again.
---
EDIT
Well I have a db table with names of countries. And I have a script that takes a country and shows its details. I would like to grab the infobox - the blue box with all country details images etc as it is from wikipedia and show it on my page. I would like to know a really simple and easy way to do that - or have a script that just downloads the information of the infobox to a local remote system which I could access myself later on. I mean I'm open to ideas here - except that the end result I want is to see the infobox on my page - of course with a little Content by Wikipedia link at the bottom :)
---
EDIT
I think I found what I was looking for on <http://infochimps.org> - they got loads of datasets in I think the YAML language. I can use this information straight up as it is but I would need a way to constantly update this information from wikipedia now and then although I believe infoboxes rarely change especially o countries unless some nation decides to change their capital city or so. | I suggest performing a WebRequest against wikipedia. From there you will have the page and you can simply parse or query out the data that you need using a regex, character crawl, or some other form that you are familiar with. Essentially a screen scrape!
EDIT - I would add to this answer that you can use HtmlAgilityPack for those in C# land. For PHP it looks like SimpleHtmlDom. Having said that it looks like Wikipedia has a more than adequate API. This question probably answers your needs best:
[Is there a Wikipedia API?](https://stackoverflow.com/questions/627594/is-there-a-wikipedia-api) | I'd use the wikipedia (wikimedia) API. You can get data back in JSON, XML, php native format, and others. You'll then still need to parse the returned information to extract and format the info you want, but the info box start, stop, and information types are clear.
Run your query for just rvsection=0, as this first section gets you the material before the first section break, including the infobox. Then you'll need to parse the infobox content, which shouldn't be too hard. See en.wikipedia.org/w/api.php for the formal wikipedia api documentation, and www.mediawiki.org/wiki/API for the manual.
Run, for example, the query: <http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xmlfm&titles=fortran&rvsection=0> | How do I grab just the parsed Infobox of a wikipedia article? | [
"",
"php",
"wikipedia",
"wikipedia-api",
""
] |
Everyone knows that this is not thread safe:
```
public StringBuilder Builder
{
get
{
if (_builder != null)
_builder = new StringBuilder();
return _builder;
}
}
```
What about this?
```
public StringBuilder Builder
{
get { return _builder ?? (_builder = new StringBuilder()); }
}
``` | **BEGIN EDIT**
Based on your edited title, the null-coalescing operator itself seems to be thread-safe (see [Phil Haack's analysis](http://haacked.com/archive/2006/08/08/IsTheNullCoalescingOperatorThreadSafe.aspx)). It appears, however, that it doesn't guarantee against the potential multiple calls to the StringBuilder constructor.
**END EDIT**
You have a larger problem with threading, and that is that the Builder property itself represents state that can be shared across threads. Even if you make the lazy initialization thread safe, there's no guarantee that methods consuming Builder are doing it in a thread safe manner.
```
// below code makes the getter thread safe
private object builderConstructionSynch = new object();
public StringBuilder Builder
{
get
{
lock (builderConstructionSynch)
{
if (_builder == null) _builder = new StringBuilder();
}
return _builder;
}
}
```
The above will prevent the threading problem in the lazy initialization of \_builder, but unless you synchronize your calls to instance methods of StringBuilder, you're not guaranteed thread safety in any methods that consume the Builder property. This is because instance methods in StringBuilder weren't designed to be thread safe. See the below text from the [MSDN StringBuilder page](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx).
> Any public static (Shared in Visual
> Basic) members of this type are thread
> safe. Any instance members are not
> guaranteed to be thread safe.
If you're consuming StringBuilder in multiple threads, you're probably better served encapsulating it in your class. Make Builder private and expose what behavior you need as a public method:
```
public void AppendString(string toAppend)
{
lock (Builder)
{
Builder.Append(toAppend);
}
}
```
This way you're not writing synchronization code all over the place. | That is no more or less thread-safe; you could still have two threads do the null check at the same time, thus create separate objects and not see the other. | Is the C# '??' operator thread safe? | [
"",
"c#",
".net",
"thread-safety",
"null-coalescing-operator",
""
] |
I have set up an email id my PHP web application. Users will send emails to this id.
I want to process these emails in the application. Ho do I go about doing this?
Thanks in advance. | I recently worked on a project that required parsing of email from gmail and updating database with certain values based on the contents of the email. I used the [ezcMail](http://ezcomponents.org/docs/tutorials/Mail) [(now) Zeta Components](https://github.com/zetacomponents/Mail) library to connect to the mail server and parse the emails.
The strategy I adopted was to filter all interesting incoming mail with a label "unprocessed". Run the PHP script via a crontab every 15 minutes. The script would connect to the mail server and open the IMAP unprocessed folder and parse each email. After inserting the interesting values into the database, the script moves the files to another IMAP folder "Proccessed".
I also found **IMAP to be better than POP** for this sort of processing. | Recently I wanted to be able to receive emails immediately in something I was making so I did some research (I came looking on this question here too actually) and I ended up finding Google App Engine to be pretty helpful. It has an api you can use to receive and process emails sent to `____@yourapp.appspotmail.com`. I know that it doesn't really seem helpful since you probably don't want your app on App Engine and you want to receive emails at yourdomain.tld, but with a little setup you can get what you want.
My basic setup is like this:
* User sends email to user\_id@mydomain.tld (an email address that doesn't actually exist)
* mydomain.tld has a catchall email address that forwards to inbox@GAEapp.appspotmail.com
* GAEapp (a tiny app on app engine) receives the email, processes it out, and sends a post request with relevant stuff to mydomain.tld
So basically you can make a little GAE app that works like a go between to grab the emails. Even with the redirect it'll work out ok, the email will be fine.
Also I decided to learn me some django and I made a free app called [Emailization](http://emailization.com) that will basically do that for you. You create a recipient like `___@emailization.com` and give a URL to POST to. Anything sent to that address gets POSTed to you URL. You can make a catchall on your domain that forwards to that emailization recipient and you'll get email through the catchall too!
or you can see a [small GAE app](https://github.com/capitao/bare-bones-receiver) I made that you can setup yourself that does the same thing.
Hope that helps somebody! | How do I receive email and process it in a web application | [
"",
"php",
"email",
""
] |
I am working with an **Oracle** 10g Database.
I have the following two tables:
```
T_DEBTOR :
- ID_DEBTOR
- HEADER
T_ELEMENT :
- ID_ELEMENT
- ID_DEBTOR
- INSURER
```
These two tables are joined using the ID\_DEBTOR field.
I want to update the T\_ELEMENT.INSURER value with the associated T\_DEBTOR.HEADER only if HEADER is not null.
In others words:
```
If T_DEBTOR.HEADER != null
Then T_ELEMENT.INSURER = T_DEBTOR.HEADER
Else T_ELEMENT.INSURER is not modified!
```
I tried to use the following SQL query:
```
update
T_ELEMENT elt
set elt.INSURER = (
select HEADER
from T_DEBTOR debtor
where
debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR);
```
This query is working for all elements linked to debtors that has a HEADER not null.
However, when the T\_DEBTOR.HEADER is null, then this query set the T\_ELEMENT.INSURER to null, which is not correct.
ie:
```
If T_DEBTOR.HEADER != null
Then T_ELEMENT.INSURER = T_DEBTOR.HEADER --> This part is OK
Else T_ELEMENT.INSURER is set to null --> This part is NOT OK
```
What is wrong with my query?
*Edit, regarding the Brian Storrar answer:*
What I want to do is something like that:
```
update
T_ELEMENT elt
set elt.INSURER = (
select HEADER
from T_DEBTOR debtor
where
debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR)
where debtor.HEADER is not null;
``` | Good question.
To simulate your situation, I've created sample tables:
```
SQL> create table t_debtor(id_debtor,header)
2 as
3 select 1, 'Header 1' from dual union all
4 select 2, null from dual union all
5 select 3, 'Header 3' from dual
6 /
Tabel is aangemaakt.
SQL> create table t_element (id_element,id_debtor,insurer)
2 as
3 select 1, 1, 'to be updated' from dual union all
4 select 2, 1, 'to be updated' from dual union all
5 select 3, 2, 'not to be updated' from dual union all
6 select 4, 2, 'not to be updated' from dual union all
7 select 5, 3, 'to be updated' from dual
8 /
Tabel is aangemaakt.
```
And with your current update statement, the problem becomes clear: the "not to be updated" values are set to NULL:
```
SQL> update
2 T_ELEMENT elt
3 set elt.INSURER = (
4 select HEADER
5 from T_DEBTOR debtor
6 where
7 debtor.HEADER is not null
8 and debtor.ID_DEBTOR = elt.ID_DEBTOR)
9 /
5 rijen zijn bijgewerkt.
SQL> select * from t_element
2 /
ID_ELEMENT ID_DEBTOR INSURER
---------- ---------- -----------------
1 1 Header 1
2 1 Header 1
3 2
4 2
5 3 Header 3
5 rijen zijn geselecteerd.
```
The best way to do this update, is to update a join of both tables. There are some restrictions however:
```
SQL> rollback
2 /
Rollback is voltooid.
SQL> update ( select elt.insurer
2 , dtr.header
3 from t_element elt
4 , t_debtor dtr
5 where elt.id_debtor = dtr.id_debtor
6 and dtr.header is not null
7 )
8 set insurer = header
9 /
set insurer = header
*
FOUT in regel 8:
.ORA-01779: cannot modify a column which maps to a non key-preserved table
```
With the bypass ujvc hint, we can circumvent this restriction.
But it is not advisable to do so unless you know really really sure that t\_debtor.id\_debtor is unique.
```
SQL> update /*+ bypass_ujvc */
2 ( select elt.insurer
3 , dtr.header
4 from t_element elt
5 , t_debtor dtr
6 where elt.id_debtor = dtr.id_debtor
7 and dtr.header is not null
8 )
9 set insurer = header
10 /
3 rijen zijn bijgewerkt.
SQL> select * from t_element
2 /
ID_ELEMENT ID_DEBTOR INSURER
---------- ---------- -----------------
1 1 Header 1
2 1 Header 1
3 2 not to be updated
4 2 not to be updated
5 3 Header 3
5 rijen zijn geselecteerd.
```
It's better to just add a primary key. You'll probably have this one already in place:
```
SQL> rollback
2 /
Rollback is voltooid.
SQL> alter table t_debtor add primary key (id_debtor)
2 /
Tabel is gewijzigd.
SQL> update ( select elt.insurer
2 , dtr.header
3 from t_element elt
4 , t_debtor dtr
5 where elt.id_debtor = dtr.id_debtor
6 and dtr.header is not null
7 )
8 set insurer = header
9 /
3 rijen zijn bijgewerkt.
SQL> select * from t_element
2 /
ID_ELEMENT ID_DEBTOR INSURER
---------- ---------- -----------------
1 1 Header 1
2 1 Header 1
3 2 not to be updated
4 2 not to be updated
5 3 Header 3
5 rijen zijn geselecteerd.
```
Regards,
Rob. | I've found a solution to solve my problem (the where clause is added):
```
update
T_ELEMENT elt
set elt.INSURER = (
select HEADER
from T_DEBTOR debtor
where
debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR)
where exists (
select null
from T_DEBTOR debtor
where debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR);
```
If you have a better solution, do not hesitate to post it! | What is wrong with my update statement with a join in Oracle? | [
"",
"sql",
"oracle",
"sql-update",
""
] |
We have a large high-performance software system which consists of multiple interacting Java processes (not EJBs). Each process can be on the same machine or on a different machine.
Certain events are generated in one process, and are then propagated in different ways to other processes for further processing and so on.
For benchmarking purposes, we need to create a log of when each event passed through a "checkpoint", eventually combine these logs to obtain a timeline of how each event propagated through the system and with what latency (of course, process switching and IPC adds latency, which is ok).
The problem, of course, is clock synchronization. So here are my questions:
1) If all processes are on the same machine, is it guaranteed that currentTimeMilis would be accurate at the time of call? Is there some bound on the errors of ITP?
2) If some processes may be on different machines, is there an off-the-shelf solution (that is also free or open-source) for clock synchronization? I am preferably looking for a solution that may bypass the operating system (Windows or Linux) and work straight from Java. I am also ideally looking for something that can operate at microsecond accuracy. I've thought about NTP, but I'm not sure if it's available via Java rather than through the OS, and I am not sure about its complexity.
3) Is there a way to determine the margin of error in using NTP in a particular configuration (or of any solution I end up using) so that I can give a margin of error on our calculation of the latency?
Thanks! | With distributed programming, clock synchronisation is often not enough. you might want to build a logical time framework (such as the Lamport or vector clocks or Singhal-Kshemkalyani methods ... and there are loads more to keep causality in sync across machines). Which you choose often depends on the application and required causality between events.
Clocks are sync'd to ensure concurrent events are kept in the right sequential order. There are other ways to do this than keeping the system clock synchronized ... which unless they share a common physical clock ... is quite tricky.
In terms of NTP error margin, there are solutions:
my recommendation:
Read:
**Distributed Computing: Principles, Algorithms and Systems**
Especially: Chapter 3, logical time
**Edit**
Further to Cheeso's post, I found
<http://www.uniforum.org/publications/ufm/apr96/opengroup.html>
<http://sourceforge.net/projects/freedce>
There maybe DCE Java bindings out there. | I'd really just use NTP. It's pretty accurate even over the internet, and on a LAN it should be even better. According to Wikipedia[[1](http://en.wikipedia.org/wiki/Network_Time_Protocol)],
> NTPv4 can usually maintain time to within 10 milliseconds (1/100 s) over the public Internet, and can achieve accuracies of 200 microseconds (1/5000 s) or better in local area networks under ideal conditions.
so it may be good enough for your needs if your conditions are "ideal" enough. NTP has been around long enough that pretty much everything works with it. I don't see any reason to do this through Java rather than the OS. If the OS is synced up, so will be Java.
[1] [Wikipedia: Network Time Protocol](http://en.wikipedia.org/wiki/Network_Time_Protocol) | Is there an off-the-shelf clock synchronization solution for Java? | [
"",
"java",
"real-time",
"distributed",
"clock-synchronization",
"vector-clock",
""
] |
Whats the easiest way to determine which Java class is compiled with the "wrong" version number?
I've a project with a large number of dependencies and somewhere I've a class compiled using Java 1.6, where Java 1.5 is required. At runtime I get the uninformative exception:
```
[WARN] StandardWrapperValve[shell]: Servlet.service() for servlet shell threw exception
java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:675)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:316)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374)
at foo.Listener.(Listener.java:30)
at foo.rpc.service.MapServiceImpl.(MapServiceImpl.java:58)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
at java.lang.Class.newInstance0(Class.java:350)
at java.lang.Class.newInstance(Class.java:303)
at com.google.gwt.dev.shell.GWTShellServlet.tryGetOrLoadServlet(GWTShellServlet.java:934)
at com.google.gwt.dev.shell.GWTShellServlet.service(GWTShellServlet.java:276)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
at java.lang.Thread.run(Thread.java:613)
```
The only thing I spot is the class foo.Listener at which all my dependencies (Camel, ActiveMQ, various in house libraries) are required.
The best thing I've thought of so far is too use opensnoop and manually dig through the jars and classes using the ideas from ["how-can-i-find-the-target-java-version-for-a-compiled-class"](https://stackoverflow.com/questions/698129/how-can-i-find-the-target-java-version-for-a-compiled-class). Is there a better way? | You might try attaching a debugger with a breakpoint set on UnsupportedClassVersionError. (Run -> Add Java Exception Breakpoint in Eclipse)
You could then examine the class name passed into the defineClass or loadClass frame when the breakpoint halts the VM. | Try running with the -verbose flag on the command line. | Finding which .class file has a bad version | [
"",
"java",
""
] |
I have some embarrassingly-parallelizable work in a .NET 3.5 console app and I want to take advantage of hyperthreading and multi-core processors. **How do I pick the best number of worker threads to utilize either of these the best on an arbitrary system?** For example, if it's a dual core I will want 2 threads; quad core I will want 4 threads. What I'm ultimately after is determining the processor characteristics so I can know how many threads to create.
I'm not asking how to split up the work nor how to do threading, I'm asking how do I determine the "optimal" number of the threads on an arbitrary machine this console app will run on. | You can use [Environment.ProcessorCount](http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx) if that's the only thing you're after. But usually using a ThreadPool is indeed the better option.
The .NET thread pool also has provisions for sometimes allocating *more* threads than you have cores to maximise throughput in certain scenarios where many threads are waiting for I/O to finish. | I'd suggest that you don't try to determine it yourself. Use the ThreadPool and let .NET manage the threads for you. | How do I pick the best number of threads for hyptherthreading/multicore? | [
"",
"c#",
"multithreading",
".net-3.5",
""
] |
When should I explicitly write `this->member` in a method of
a class? | Usually, you do not have to, `this->` is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where `this->` is explicitly required.
Consider the following code:
```
template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
```
If you omit `this->`, some compilers do not know how to treat `i`. In order to tell it that `i` is indeed a member of `A<T>`, for any `T`, the `this->` prefix is required.
Note: it is possible to still omit `this->` prefix by using:
```
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
``` | If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.
```
#include <iostream>
using namespace std;
class A
{
public:
int a;
void f() {
a = 4;
int a = 5;
cout << a << endl;
cout << this->a << endl;
}
};
int main()
{
A a;
a.f();
}
```
prints:
5
4 | When should I make explicit use of the `this` pointer? | [
"",
"c++",
"this",
""
] |
I tried the `java.io.Console` API using eclipse. My sample code follows.
```
package app;
import java.io.Console;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Console console = System.console();
console.printf("Hello, world!!");
}
}
```
When I tried running the example, I got the following error.
> Exception in thread "main"
> java.lang.NullPointerException at
> app.MainClass.main(MainClass.java:11)
Where did I go wrong? Thanks. | Since you've mentioned in a comment that you're using Eclipse, it appears that there is currently no support for [`Console`](http://java.sun.com/javase/6/docs/api/java/io/Console.html) in Eclipse, according to this [bug report](https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429).
The [`System.console`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#console()) method returns a console associated with the current Java virtual machine, and if there is no console, then it will return `null`. From the documentation of the `System.console` method:
> Returns the unique `Console` object associated with the current Java
> virtual machine, if any.
>
> **Returns:**
>
> The system console, if any, otherwise `null`.
Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a `null` check on the `Console` object to see if something has been returned or not; this will prevent a `NullPointerException` by trying to use the non-existent `Console` object.
For example:
```
Console c = System.console();
if (c == null) {
System.out.println("No console available");
} else {
// Use the returned Console.
}
``` | [System.console](http://java.sun.com/javase/6/docs/api/java/lang/System.html#console()) returns null if you don't run the application in a console. See [this question](https://stackoverflow.com/questions/104254/java-io-console-support-in-eclipse-ide) for suggestions. | Java console API | [
"",
"java",
"console",
""
] |
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?
```
import datetime
a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
dateList.append(a - datetime.timedelta(days = x))
print dateList
``` | Marginally better...
```
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]
``` | [`Pandas`](http://pandas.pydata.org/) is great for time series in general, and has direct support for date ranges.
For example [`pd.date_range()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html):
```
import pandas as pd
from datetime import datetime
datelist = pd.date_range(datetime.today(), periods=100).tolist()
```
It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in [`bdate_range`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.bdate_range.html).
See [date range documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#generating-ranges-of-timestamps)
In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.
**EDIT by OP:**
If you need actual python datetimes, as opposed to Pandas timestamps:
```
import pandas as pd
from datetime import datetime
pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()
#OR
pd.date_range(start="2018-09-09",end="2020-02-02")
```
This uses the "end" parameter to match the original question, but if you want descending dates:
```
pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()
``` | Creating a range of dates in Python | [
"",
"python",
"datetime",
"date",
""
] |
I'm doing some work with a server side service I don't control. The following works fine in standard C#, but fails (due to missing crypto classes) in Silverlight 2 and 3.
```
static String DecryptString()
{
s = "<cipherTextHere>";
byte[] toDecryptArray = Convert.FromBase64String(s);
string key = "<key here>";
byte[] keyArray = new byte[key.Length / 2];
for (int i = 0; i < keyArray.Length; i++)
{
keyArray[i] = Convert.ToByte(Convert.ToInt32(key.Substring(i * 2, 2), 16));
}
using (var algo = new System.Security.Cryptography.AesManaged())
{
// The two lines below are the problem
// as SL does not give me the option to select padding or ciphermode
algo.Padding = PaddingMode.PKCS7;
algo.Mode = CipherMode.ECB;
algo.Key = keyArray;
ICryptoTransform cTransform = algo.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(
toDecryptArray, 0, toDecryptArray.Length);
return (UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length));
}
}
```
What are my options? | Solution from [someone smart](http://www.netcrucible.com/blog/): "You cannot select padding or ciphermode for AesManaged in Silverlight, so you will have to use the default. Padding by default is PKCS7 just like in your C# code, but cipher mode is CBC."
This works, but now I'm going to have to go convinnce the service provider to switch :( | You could write your own crypto provider, or you could search for third party components which have already addressed the issue.
I know that xceed have implemented a compression provider for Silverlight so compression and encryption are definately possible.
try
[Cryptography Tutorial](http://www.cryptography-tutorial.com/) | How do I work around the missing crypto classes in silverlight 2/3? | [
"",
"c#",
"silverlight",
"cryptography",
""
] |
I have been using a noscript tag to show a warning when users have JavaScript disabled or are using script blocking plugins like Noscript. The website will not function properly if JavaScript is disabled and users may not figure out why it is not working without the warning.
After the latest Google algorithm shuffle, I have seen the daily traffic drop to about 1/3 of what it was in the previous months. I have also seen pages that were ranking #1 or #2 in the SERPS drop out of the results. After doing some investigating in webmaster tools, I noticed that "JavaScript" is listed as #16 in the keywords section. This makes no sense because the site has nothing to do with JavaScript and the only place that word appears is in the text between the noscript tags.
It seems that Google is now including and indexing the content between the noscript tags. I don't believe that this was happening before. The warning is three sentences. I'd imagine that having the same three sentences appearing at the top of every single page on the site could have a damaging effect on the SEO.
Do you think this could be causing a problem with SEO? And, is there any other method to provide a warning to users who have JavaScript disabled in a way that won't be indexed or read by search engines? | Somebody on another forum mentioned using an image for the warning. The way I see it, this would have three benefits:
1. There wouldn't be any irrelevant text for search engines to index.
2. The code to display a single image is less bulky than a text warning (which gets loaded on every page).
3. Tracking could be implemented to determine how many times the image is called, to give an idea of how many visitors have JavaScript disabled or blocked.
If you combine this with something like the non-noscript technique mentioned by J-P, it seems to be the best possible solution. | Put the `<noscript>` content at the **end** of your HTML, and then use CSS to position it at the top of the browser window. Google will no longer consider it important.
Stack Overflow itself uses this technique - do a View Source on this page and you'll see a "works best with JavaScript" warning near the end of the HTML, which appears at the top of the page when you switch off JavaScript. | Noscript Tag, JavaScript Disabled Warning and Google Penalty | [
"",
"javascript",
"seo",
"noscript",
""
] |
How can I retrieve data stored using MIDP's RMS? I would like to collect some data in the handset and then be able to process it in the PC's application.
If I can't do it using RMS, is there a way to store data in text files using MIDP? | You can programmatically retrieve data from RMS and send it to server with a network call, and thus to a PC application. Some handsets implement the JSR 75 (javax.microedition.io.file) for file system access, not all. You can use it to read and write text files. However I think sending the data over a HTTP connection is the easiest way to do this. | HTTP is the way to go - but if you are looking at doing this with multiple devices you will run into different problems.
Sending a little data should be simple you build a HTTP GET request and just put your data in the url - however there is a limit to the length of urls - sometimes this is restricted by device, or by the network that you are using the device on - and sometimes by the server at the other end.
We have found the best way to send up data is to send it up in batches and multiple HTTP POST requests - which gets around any proxy servers that might be in the way. We use JSON to send data as it is very lightweight.
We did have success using the HTTP method to attach a file to a request - but soon found out this was limited to certain devices and networks.
If this is all just for personal use - then just do what works - but for an application you want others to use I can only recommend HTTP POST and in small batches (2K say). | Store data with MIDP RMS and retrieve in PC | [
"",
"java",
"java-me",
"midp",
"midlet",
"rms",
""
] |
I have two tables that holds inforamtion for SKU.
Log table has datetimefield 2008-10-26 06:21:59.820
the other table has datetimefield 2008-10-26 06:22:02.313
I want to include this datetime fields in join for these 2 tables.
Is it possible to join to tables with datetime fields that has difference not more than 3 seconds? What is the best way to do that? | This is one way to do it:
```
select * from table_a, table_b
where table_a.sku = table_b.sku
and abs(datediff(second,table_a.datetime,table_b.datetime))<=3
```
Be careful, with big tables this kind of join can be very slow. | ```
SELECT
t1.id,
t2.id
FROM
t1
INNER JOIN t2 ON ABS(DATEDIFF(ms, t1.datefield, t2.datefield)) <= 3000
WHERE
...
```
Beware, this will be slow. And probably not always right (as in: it will not always join records that should be joined because they belong together, it will of course always be *technically* correct).
EDIT:
Changed from `ABS(DATEDIFF(ss, t1.datefield, t2.datefield)) <= 3` to the above because of @richardtallent's excellent observation in the comments. | Joining by datetimefield SQL Server | [
"",
"sql",
"sql-server",
"join",
""
] |
Say I have a table that has items and attributes listed like,
```
frog green
cat furry
frog nice
cat 4 legs
frog 4 legs
```
From the items column I want to select unique objects that have both the green and 4 legs attribute. I would expect to get back just the frog object in this case. What is the most efficient query to do this? | ```
select item.name
from item
where item.attribute in ('4 legs', 'green')
group by item.name
having count(distinct item.attribute) = 2
``` | The most efficient way to do this is with a self-join:
```
SELECT * FROM attributes a1
JOIN attributes a2 USING (item_name) -- e.g. frog
WHERE a1.value = 'green' AND a2.value = '4 legs';
```
Another solution that some people use is a trick with GROUP BY:
```
SELECT item_name FROM attributes
WHERE value IN ('4 legs', 'green')
GROUP BY item_name
HAVING COUNT(*) = 2;
```
But the GROUP BY solution may not be as efficient as a JOIN, depending on which brand of RDBMS you use. Also one method may scale better as the volume in your table grows. | What is a SQL statement to select an item that has several attributes in an item/attribute list? | [
"",
"sql",
"relational-division",
"sql-match-all",
""
] |
I am showing a splash screen on a background thread while my program loads. Once it loads I am aborting the Thread as it's only purpose was to show a Now Loading splash form.
My problem is that when aborting a Thread it throws a `ThreadAbortException` that the user can just click Continue on.
How do I deal with this? I was trying to suppress it like so -->
```
try
{
Program.splashThread.Abort();
}
catch(Exception ex)
{
}
```
but I have a feeling that is going to get me yelled at here and it doesn't work any way.
Thanks! | You don't need to cancel the thread. I'll exemplify with code.
In the splash screen form:
```
public void CloseSplash()
{
Invoke((MethodInvoker)delegate
{
this.Close();
});
}
```
In the Program.cs file:
```
private static Splash _splash = null;
public static void CloseSplash()
{
if (_splash!= null)
{
_splash.CloseSplash();
}
}
```
Now, when your Main method starts, show the splash in a thread:
```
Thread t = new Thread(new ThreadStart(delegate
{
_splash = new Splash();
_splash.ShowDialog();
}));
t.Start();
```
...and when you want it to close, just close it:
```
Program.CloseSplash();
```
Then you don't need to worry about aborting the thread; it will exit gracefully. | Please refer to the following link obtained doing a Google search (first result returned):
<http://msdn.microsoft.com/en-us/library/5b50fdsz.aspx>
Pay special attention to this part:
When this method is invoked on a thread, the system throws a **ThreadAbortException** in the thread to abort it. **ThreadAbortException** is a special exception that can be caught by application code, but is re-thrown at the end of the catch block unless **ResetAbort** is called. **ResetAbort** cancels the request to abort, and prevents the **ThreadAbortException** from terminating the thread. Unexecuted finally blocks are executed before the thread is aborted. | How do I suppress a thread.abort() error C#? | [
"",
"c#",
".net",
"multithreading",
"error-suppression",
"thread-abort",
""
] |
Here is my data model (simplified),
```
public class AddressBook {
private List<Group> groups = new ArrayList<Group>();
private List<People> peoples = new ArrayList<People>();
@OneToMany(mappedBy = "addressbook", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<Group> getGroups() {
return groups;
}
@OneToMany(mappedBy = "addressbook", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<People> getPeoples() {
return peoples;
}
}
public class Group {
private AddressBook addressBook;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
public void setAddressBook(AddressBook addressBook) {
this.addressBook = addressBook;
}
}
public class People {
private AddressBook addressBook;
private Group group;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
public AddressBook getAddressBook() {
return addressBook;
}
public Group getGroup() {
return group;
}
}
```
I want to delete a full group from my addressbook, and all the people belonging to this group. So I do something like:
```
adressBook.getPeople().removeAll(peopleBelongingToGroupA);
adressBook.getGroups().remove(groupA);
```
But when my transaction is committed, Hibernate does first:
```
delete from groups where groupName='groupA';
```
Instead of deleting the people first. That causes my FOREIGN\_KEY constraint between people and group to be violated.
Is there a way to tell hibernate to delete the people first, then the groups? Is there a flaw in my model? | Have you tried putting setting the cascade on each @ManyToOne. You've only specified, in many ways, cascade deletion on the AddressBook. This property is for each association I believe.
The EJB3.0 specification is well worth having to hand when writing these beans. See <http://jcp.org/en/jsr/detail?id=220>
Update:
Reading your datamodel again, there may be a missing annotation on people here that would explain the behaviour. Do you have cascade set on the link with people->group? This would explain why the first statement would first start by trying to delete the group. Presumably you would want an annotation for groups on people that does not cascade? | there are 2 options
1) call flush before the second delete
2) add an 'cascade' to your mappings: i.e. cascade="delete". A delete of the group will delete also delete members of the group. | Order of Hibernate delete queries | [
"",
"java",
"hibernate",
""
] |
I need to have a file synchronizing feature in my .NET application. Can I make use of rsync? Is there any API available? | You can use the source code that comes with [DeltaCopy](http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp), which is a "'Windows Friendly' wrapper" to the original RSync.
The source is written in c++, so it's not exactly .Net, but you can write managed C++ wrappers and use them.
It's not a direct solution, I know, but it may be somewhat helpful. (in other words, HTH) | There is a C# implementation of RSync on github with some recent commits:
<http://github.com/MatthewSteeples/rsync.net> | Is there any .NET API using rsync? | [
"",
"c#",
"rsync",
""
] |
Goal: Given a number (it may be very long and it is greater than 0), I'd like to get the five least meaningful digits dropping any 0 at the end of that number.
I tried to solve this with regex, Helped by RegexBuddy I came to this one:
```
[\d]+([\d]{0,4}+[1-9])0*
```
But python can't compile that.
```
>>> import re
>>> re.compile(r"[\d]+([\d]{0,4}+[1-9])0*")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/re.py", line 188, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.5/re.py", line 241, in _compile
raise error, v # invalid expression
sre_constants.error: multiple repeat
```
The problem is the "+" after "{0,4}", it seems it doesn't work in python (even in 2.6)
How can I write a working regex?
PS:
I know you can start dividing by 10 and then using the remainder n%100000... but this is a problem about regex. | That regular expression is very superfluous. Try this:
```
>>> import re
>>> re.compile(r"(\d{0,4}[1-9])0*$")
```
The above regular expression assumes that the number is valid (it will also match "abc**012345**0", for example.) If you really need the validation that there are no non-number characters, you may use this:
```
>>> import re
>>> re.compile(r"^\d*?(\d{0,4}[1-9])0*$")
```
Anyways, the `\d` does not need to be in a character class, and the quantifier `{0,4}` does not need to be forced to be greedy (as the additional `+` specifies, although apparently Python does not recognize that.)
Also, in the second regular expression, the `\d` is non-greedy, as I believe this will improve the performance and accuracy. I also made it "zero or more" as I assume that is what you want.
I also added anchors as this ensures that your regular expression won't match anything in the middle of a string. If this is what you desired though (maybe you're scanning a long text?), remove the anchors. | \d{0,4}+ is a possessive quantifier supported by certain regular expression flavors such as .NET and Java. Python does not support possessive quantifiers.
In RegexBuddy, select Python in the toolbar at the top, and RegexBuddy will tell you that Python doesn't support possessive quantifiers. The + will be highlighted in red in the regular expression, and the Create tab will indicate the error.
If you select Python on the Use tab in RegexBuddy, RegexBuddy will generate a Python source code snippet with a regular expression without the possessive quantifier, and a comment indicating that the removal of the possessive quantifier may yield different results. Here's the Python code that RegexBuddy generates using the regex from the question:
```
# Your regular expression could not be converted to the flavor required by this language:
# Python does not support possessive quantifiers
# Because of this, the code snippet below will not work as you intended, if at all.
reobj = re.compile(r"[\d]+([\d]{0,4}[1-9])0*")
```
What you probably did is select a flavor such as Java in the main toolbar, and then click Copy Regex as Python String. That will give you a Java regular expression formatted as a Pythong string. The items in the Copy menu do not convert your regular expression. They merely format it as a string. This allows you to do things like format a JavaScript regular expression as a Python string so your server-side Python script can feed a regex into client-side JavaScript code. | Regex in Python | [
"",
"python",
"regex",
"regexbuddy",
""
] |
I have a scenario in my current application where I want to fetch the Gmail id's of my users.
Could anyone tell me the way with piece of code in C#?
Note: I am developing a web-base application in asp.net with C#. | Use the [google contacts api](http://code.google.com/apis/contacts/docs/3.0/developers_guide_dotnet.html) there are C# sample there. | You can use the [Google Accounts API](http://code.google.com/apis/accounts/).
[You can find an example here.](http://code.google.com/apis/contacts/docs/2.0/developers_guide_dotnet.html) | How to fetch Gmail contacts? | [
"",
"c#",
"asp.net",
"email",
"gmail",
""
] |
I'm trying to load a piece of (possibly) malformed HTML into an XMLDocument object, but it fails with XMLExceptions... since there are extra opening/closing tags, and malformed XML tags such as `<img >` instead of `<img />`
How do I get the XML to parse with all the errors in the data? Is there any XML validator that I can apply before parsing, to correct these errors? Or would handling the exception parse whatever can be parsed? | The [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) will parse html, rather than xhtml, and is quite forgiving. The object model will be familiar if you've used `XmlDocument`. | You might want to check out the answer to [this question](https://stackoverflow.com/questions/118654/iron-python-beautiful-soup-win32-app).
Basically somewhere between a .NET port of beautifulsoup and the HTML agility pack there is a way. | Parse malformed XML | [
"",
"c#",
"xml",
"parsing",
"xmldocument",
"xml-parsing",
""
] |
I am trying to initialise a FileInputStream object using a File object. I am getting a FileNotFound error on the line
```
fis = new FileInputStream(file);
```
This is strange since I have opened this file through the same method to do regex many times.
My method is as follows:
```
private BufferedInputStream fileToBIS(File file){
FileInputStream fis = null;
BufferedInputStream bis =null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bis;
}
```
java.io.FileNotFoundException: C:\dev\server\tomcat6\webapps\sample-site (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at controller.ScanEditRegions.fileToBIS(ScanEditRegions.java:52)
at controller.ScanEditRegions.tidyHTML(ScanEditRegions.java:38)
at controller.ScanEditRegions.process(ScanEditRegions.java:64)
at controller.ScanEditRegions.visitAllDirsAndFiles(ScanEditRegions.java:148)
at controller.Manager.main(Manager.java:10) | Judging by the stacktrace you pasted in your post I'd guess that you do not have the rights to read the file.
The File class allows you to performs useful checks on a file, some of them:
```
boolean canExecute();
boolean canRead();
boolean canWrite();
boolean exists();
boolean isFile();
boolean isDirectory();
```
For example, you could check for: exists() && isFile() && canRead() and print a better error-message depending on the reason why you cant read the file. | You might want to make sure that (in order of likely-hood):
1. The file exists.
2. The file is not a directory.
3. You or the Java process have permissions to open the file.
4. Another process doesn't have a lock on the file (likely, as you would probably receive a standard IOException instead of FileNotFoundException) | Get FileNotFoundException when initialising FileInputStream with File object | [
"",
"java",
"filenotfoundexception",
"fileinputstream",
"bufferedinputstream",
""
] |
Let's say that I have a model Foo that inherits from SuperFoo:
```
class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
```
In class Foo, I'd like to override the verbose\_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template? | A simple hack I have used is:
```
class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Meta:
abstract = True
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
Foo._meta.get_field('name').verbose_name = 'Whatever'
``` | Bearing in mind the caveat that modifying Foo.\_meta.fields will affect the superclass too - and therefore is only really useful if the superclass is abstract, I've wrapped the answer @Gerry gave up as a reusable class decorator:
```
def modify_fields(**kwargs):
def wrap(cls):
for field, prop_dict in kwargs.items():
for prop, val in prop_dict.items():
setattr(cls._meta.get_field(field), prop, val)
return cls
return wrap
```
Use it like this:
```
@modify_fields(timestamp={
'verbose_name': 'Available From',
'help_text': 'Earliest date you can book this'})
class Purchase(BaseOrderItem):
pass
```
The example above changes the verbose\_name and help\_text for the inherited field 'timestamp'. You can pass in as many keyword args as there are fields you want to modify. | how to override the verbose name of a superclass model field in django | [
"",
"python",
"django",
"inheritance",
"django-models",
""
] |
In my project (based on php/mysql/jquery ) i need the user to enter time.
But it seems very annoying to enter the time in strict formats like
06:00 PM
or
14:00
So i want to give the user freedom to enter time in a very friendly way like
6 pm, 11am etc
or
14
which will then be converted internally into a strict time format for further processing.
Can anybody suggest me any good plugin . If no plugins are there please suggest me how to approach. | What I tend to do for date and/or time fields is let the user enter it in whatever format they like, then format it back to a "universal" particular format on blur of the field. [Date.js](http://www.datejs.com/) is incredibly handy for both the parsing and the formatting.
Something like
```
$('.timeboxme').blur(function() {
var $el = $(this);
var theDate = Date.parse($el.val());
if(theDate) {
$el.val(theDate.toString("HH:mm"));
} else {
//it didn't appear to be a valid date/time, tell the user
}
});
```
As a bonus, if you use date.js, you get some fancy tricks you can tell the user about, like "+3 hours" or "last hour" :-) | [Datejs](http://www.datejs.com/) is very close to what you are asking for. | user-friendly time entry | [
"",
"php",
"jquery",
"mysql",
""
] |
I will start from example: I have an version of my app which looks like this
**1.0.3450.26573** (it is hard to read and looks nasty). Code to take this version is:
```
String Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
```
I want to see version **1.0.12**, **1.0.13**, **1.0.14** where 1.0.[BUILD], where BUILD is auto increasing on each build.
**How can I do this in a best way?** | Yeah, revision number would be great, but how I can get it, I use [SourceGear Vault](http://www.sourcegear.com/vault/). | Actually, build number will not do you any good unless you'll be able to track which build number corresponds to which version of source code your application was built from. Rather, consider using revision number from your repository (if your SCM tool is anything similar to Subversion; to do so try [svnversion](http://svnbook.red-bean.com/en/1.1/re57.html)). | .NET C# how to make version more readable automatically? | [
"",
"c#",
".net",
"version-control",
""
] |
Let's say I have a Java ArrayList, that is sorted. Now I would like to find the index of value x. What would be the fastest (without more than 30 lines of code) way to do this? Use of the IndexOf() method? Iterate through all values in a simple for loop? Use of some cool algorithm? We are talking about around let's say 50 integer keys. | [Binary search](http://en.wikipedia.org/wiki/Binary_search), but since it's only 50 items, who cares (unless you have to do it millions of times)? A simple linear search is simpler and the difference in performance for 50 items is negligible.
**Edit**: You could also use the built-in java.util.Collections [binarySearch](http://java.sun.com/javase/6/docs/api/java/util/Collections.html) method. Be aware, that it will return an insertion point even if the item isn't found. You may need to make an extra couple of checks to make sure that the item really is the one you want. Thanks to @Matthew for the pointer. | tvanfosson is right, that the time for either will be very low, so unless this code runs very frequently it won't make much difference.
However, Java has built-in functionality for binary searches of Lists (including ArrayLists), [Collections.binarySearch](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)). | Best way to find value in List when list is sorted | [
"",
"java",
"algorithm",
"search",
"sorting",
""
] |
I'm new to Django and I'm trying to learn it through a simple project. I'm developing a system called 'dubliners' and an app called 'book'. The directory structure is like this:
```
dubliners/book/ [includes models.py, views.py, etc.]
dubliners/templates/book/
```
I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.
Thanks for the answers posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template:
```
<img src="/home/tony/london.jpg" />
```
The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path? | In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example
```
<img src="../media/foo.png">
```
And then you'll just make sure that directory is there with the relevant file(s).
during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.
Right [here](http://docs.djangoproject.com/en/dev/howto/static-files/). | Try this,
## settings.py
```
# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'
```
## urls.py
```
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
```
## .html
```
<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />
```
## Caveat
Beware! using `Context()` will yield you an empty value for `{{MEDIA_URL}}`. You must use `RequestContext()`, instead.
I hope, this will help. | How do I include image files in Django templates? | [
"",
"python",
"django",
"django-templates",
""
] |
I have two tables parent and child (related as such on PK/FK GUID)
Child has a Timestamp (the record creation date/time).
What I want to do is get only the most recent child record AND the parent record, FOR EACH parent record.
```
SELECT
dbo_Parents.ParentName,
dbo_ChildEntry.CountPropertys,
dbo_ChildEntry.DateTimeStamp
FROM
dbo_Parents INNER JOIN dbo_ChildEntry
ON
dbo_Parents.ParentID = dbo_ChildEntry.ParentID
WHERE
([WHAT SHOULD BE HERE?]))
``` | Assuming that you want the most recent entry, you have to use TOP 1 and order by.
```
SELECT TOP 1
dbo_Parents.ParentName,
dbo_ChildEntry.CountPropertys,
dbo_ChildEntry.DateTimeStamp
FROM dbo_Parents
INNER JOIN dbo_ChildEntry ON dbo_Parents.ParentID = dbo_ChildEntry.ParentID
ORDER BY dbo_ChildEntry.DateTimeStamp desc
```
Edit after clarification: "the most recent child record AND the parent record, FOR EACH parent record":
```
WHERE dbo_ChildEntry.DateTimeStamp =
( Select Max( dbo_ChildEntry.DateTimeStamp )
from dbo_ChildEntry
where dbo_Parents.ParentID = dbo_ChildEntry.ParentId )
``` | ```
WHERE dbo.ChildEntry.DateTimeStamp = ( Select Max( c.DateTimeStamp )
from dbo.ChildEntry c
where dbo_Parents.ParentID = c.ParentId )
``` | SQL SELECT WHERE Trouble any ideas helpful | [
"",
"sql",
"sql-server",
"sql-server-2005",
"join",
"where-clause",
""
] |
How can I query all user defined data types from sql server like the way I do this for database object which are stored in sysobjects. | In SQL Server 2005 (and above) you can do this
```
SELECT * FROM sys.Types WHERE is_user_defined = 1
```
If you are on SQL Server 2000, you can use SysTypes. I think the query is as follows:
```
SELECT * FROM SysTypes WHERE xusertype > 256
``` | You can use the [`sys.types`](http://msdn.microsoft.com/en-us/library/ms188021.aspx) view for this. When `user_type_id` and `system_type_id` are different, you have a user type.
As AakashM says, the `sys.types` view is only available from SQL Server 2005 and higher.
EDIT: A better way to determine whether a type is a user-defined type is to check the `is_user_defined` flag (see Tim C's answer). | Query all user defined types from Sql Server? | [
"",
"sql",
"sql-server",
""
] |
I have the following settings in my web.config file. It basically restricts access to a page if the user is not logged in. If I don't want to use the asp login controls or implement a membership provider, how can I 'tell' asp that the loginregister.aspx page has authorized the request if I want to implement my own login system?
Thanks.
```
<authentication mode="Forms">
<forms loginUrl="~/loginregister.aspx"
name=".ASPXFORMSAUTH" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<location path="~/secretpage.aspx" allowOverride="true">
<system.web>
<compilation debug="true" />
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
``` | After you validate your user, set a ticket....
```
Response.Cookies.Add(TicketHelper.CreateAuthCookie(Login1.UserName, userData, Login1.RememberMeSet /*persistent cookie*/));
```
using this helper class...
If using a login control, do it in Authenticated event handler.
```
using System;
using System.Web;
using System.Web.Security;
namespace CustomAuthRepurposingFormsAuth
{
public static class TicketHelper
{
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="userData">be mindful of the cookie size or you will be chasing ghosts</param>
/// <param name="persistent"></param>
/// <returns></returns>
public static HttpCookie CreateAuthCookie(string userName, string userData, bool persistent)
{
DateTime issued = DateTime.Now;
// formsAuth does not expose timeout!? have to hack around the
// spoiled parts and keep moving..
HttpCookie fooCookie = FormsAuthentication.GetAuthCookie("foo", true);
int formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes);
DateTime expiration = DateTime.Now.AddMinutes(formsTimeout);
string cookiePath = FormsAuthentication.FormsCookiePath;
var ticket = new FormsAuthenticationTicket(0, userName, issued, expiration, true, userData, cookiePath);
return CreateAuthCookie(ticket, expiration, persistent);
}
public static HttpCookie CreateAuthCookie(FormsAuthenticationTicket ticket, DateTime expiration, bool persistent)
{
string creamyFilling = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, creamyFilling)
{
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath
};
if (persistent)
{
cookie.Expires = expiration;
}
return cookie;
}
}
``` | ```
// formsAuth does not expose timeout!? have to hack around the
// spoiled parts and keep moving..
HttpCookie fooCookie = FormsAuthentication.GetAuthCookie("foo", true);
int formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes);
```
Forms Authentication does expose timeout as of .Net 4.0 `FormsAuthentication.Timeout.TotalMinutes` | How to set asp.net authenticated properties | [
"",
"c#",
"asp.net-membership",
""
] |
In a similar way to using varargs in C or C++:
```
fn(a, b)
fn(a, b, c, d, ...)
``` | Yes. You can use `*args` as a *non-keyword* argument. You will then be able to pass any number of arguments.
```
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)
```
As you can see, Python will *unpack* the arguments as a single tuple with all the arguments.
For keyword arguments you need to accept those as a separate actual argument, as shown in [Skurmedel's answer](https://stackoverflow.com/a/919720/28169). | Adding to unwinds post:
You can send multiple key-value args too.
```
def myfunc(**kwargs):
# kwargs is a dictionary.
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc(abc=123, efh=456)
# abc = 123
# efh = 456
```
And you can mix the two:
```
def myfunc2(*args, **kwargs):
for a in args:
print a
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123
```
They must be both declared and called in that order, that is the function signature needs to be \*args, \*\*kwargs, and called in that order. | Can a variable number of arguments be passed to a function? | [
"",
"python",
""
] |
How can I truncate a string after 20 words in PHP? | ```
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
```
Outputs:
```
Hello here is a long ...
``` | Change the number `3` to the number `20` below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the `3` to `20` to change the default value):
```
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}
var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
var_dump(first3words("hello yes world")); # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes")); # => "hello yes"
var_dump(first3words("hello")); # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words("")); # => ""
``` | How can I truncate a string to the first 20 words in PHP? | [
"",
"php",
"string",
""
] |
`float('nan')` represents NaN (not a number). But how do I check for it? | Use [`math.isnan`](http://docs.python.org/library/math.html#math.isnan):
```
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
``` | The usual way to test for a NaN is to see if it's equal to itself:
```
def isNaN(num):
return num != num
``` | How to check for NaN values | [
"",
"python",
"math",
"nan",
""
] |
*NOTE: Sorry for the long question!*
I'm trying to understand some key areas behind object orientation and I couldn't decide one way or another about my particular question.
Let's say I have an object full of lovely data. Class bob.
```
Bob myBob = new Bob("This string is data");
```
Let's say I want to save the contents of myBob to an xml file (bob.xml)
Should I have an object act on bob to write the contents out, or should I have myBob do this?
**Case 1: Act on object**
```
Writer myWriter = new Writer(myBob, "C:\\bob.xml");
```
**Case 2: Save method**
```
myBob.Save("C:\\bob.xml");
```
Some people are siding with option one as it means if the code for writing files is changed, it doesn't need to updated across every Save method; promoting code reuse I suppose. My problem with this is getting all the data out of objects which may have private data with no accessor.
The case for option two is that the method only acts on the data held by the object and that's the way it should be. No interference from other objects.
Or is the answer to my question one of those "case dependent" issues? If so, how do you know when one method is prefered over the other? | The correct approach, in general, is your Case 1. This maintains a single responsibility for the class (whatever it does) without coupling it to a specific persistence mechanism (a disk).
You're looking at a specific case of a more generalized problem: Serialization. It's good and OK for an object to have some means to indicate how it should be serialized-- it's the only entity that knows what's necessary to deserialize it, after all. But if you make the object save itself to disk, you've tightly coupled that object to a specific implementation.
Instead, consider creating an interface that a generalized "writer" can use to "serialize" the object to whatever that writer serializes to. This way, you'll be able to serialize to disk, to the network, to memory, to whatever you actually need to serialize to. :) | I would make `Bob` know how to serialize itself since it has private data. Another object (such as your `Writer`) would take that and put it on disk. Bob knows how to deal with its data best but it need not care about how or where that is stored. Your Writer knows how to save data best but it need not care about how that data is created. | Should an object write itself out to a file, or should another object act on it to perform I/O? | [
"",
"c#",
"design-patterns",
"oop",
"io",
""
] |
long time listener. First time caller...
Not strictly a PHP question as it involves regular expressions but this one has got me tearing my hair out.
I have 3 regular expressions that I want to create, and only one is working correctly.
Now I am not sure whether this is due to the fact that:
1. I don't understand preg\_match and
ereg and their return codes as I
haven't worked in PHP for about 7
years.
2. My regular expressions are
just plain wrong.
3. I am mentally disabled.
Either way here are the expressions and my feeble attempts in making them work.
1) Match any number starting with 2,3,4 or 5 then followed by 5 digits. (This one I think works)
code:
```
if (!ereg('/[2-5]\d{5}/', $_POST['packageNumber' )
{
echo "The package number is not the correct format.";
}
```
2) Match any number starting with 2,3,4 or 5 then followed by 5 digits then a period then a 1 or a 2.
```
if (!ereg("/[2-5]\d{5}\.[1-2]/", $_POST['packageModifier' )
{
echo "The package modifier is not the correct format.";
}
```
3) Match any combination of alphanumerics, spaces,periods and hypens up to 50 characters.
```
if (!ereg("/[0-9a-zA-Z\s\-\.]{0,50}/", $_POST['customerNumber' )
{
echo "The customer number is not the correct format.";
}
```
If anyone can please tell me what I am doing wrong I'll give them my first born. | I'm assuming that you just missed off the closing ] on the $\_POSTS and i've added in anchors for the start and end of the lines and used preg\_match.
If you don't anchor it and the pattern is matched anywhere in the string then the entire thing will match. For example.
"dfasfasfasfasf25555555as5f15sdsdasdsfghfsgihfughd54" would be matched if the first one was not anchored.
**Number One**
```
if (!preg_match('/^[2-5]\d{5}$/', $_POST['packageNumber'])) {
echo "The package number is not the correct format.";
}
```
**Number Two**
```
if (!preg_match('/^[2-5]\d{5}\.[2-5]$/', $_POST['packageModifier'])) {
echo "The package modifier is not the correct format.";
}
```
**Number Three**
```
if (!preg_match('/^[0-9a-zA-Z\s\-.]{0,50}$/m', $_POST['customerNumber'])) {
echo "The package modifier is not the correct format.";
}
``` | You are mixing up [PCRE functions](http://docs.php.net/manual/en/ref.pcre.php) and [POSIX regular expression functions](http://docs.php.net/manual/en/ref.regex.php). You are using a [Perl-Compatible regular expression](http://docs.php.net/manual/en/pcre.pattern.php) with a POSIX regular expression function.
So replace `ereg` by `preg_match` and it should work:
```
if (!preg_match('/^[2-5]\d{5}$/', $_POST['packageNumber'])) {
echo "The package number is not the correct format.";
}
if (!preg_match("/^[2-5]\d{5}\.[1-2]$/", $_POST['packageModifier'])) {
echo "The package modifier is not the correct format.";
}
if (!preg_match("/^[0-9a-zA-Z\s\-.]{0,50}$/", $_POST['customerNumber'])) {
echo "The customer number is not the correct format.";
}
```
Along with fixing the PHP syntax errors I added anchors for the start (`^`) and the end (`$`) of the string to be matched. | <?PHP, REGEX and me. A tragedy in three acts | [
"",
"php",
"regex",
""
] |
How can I create and show a popup window at a specific time in WPF?
What I mean how to display the window on the side of system tray. | You could use a timer if you're trying to make the thing popup in a certain number of hours/seconds/minutes (or work out how many hours/seconds/minutes are left until your specific time comes around).
```
private System.Windows.Threading.DispatcherTimer popupTimer;
// Whatever is going to start the timer - I've used a click event
private void OnClick(object sender, RoutedEventArgs e)
{
popupTimer = new System.Windows.Threading.DispatcherTimer();
// Work out interval as time you want to popup - current time
popupTimer.Interval = specificTime - DateTime.Now;
popupTimer.IsEnabled = true;
popupTimer.Tick += new EventHandler(popupTimer_Tick);
}
void popupTimer_Tick(object sender, EventArgs e)
{
popupTimer.IsEnabled = false;
// Show popup
// ......
}
```
---
Ok, so you also want to know how to do a notifier popup type thing, which maybe this article in [CodeProject](http://www.codeproject.com/KB/WPF/WPF_TaskbarNotifier.aspx?display=Print) might help. | Check out [this question](https://stackoverflow.com/questions/725917/good-way-of-firing-an-event-at-a-particular-time-of-day) for firing an event at a set time. | PopUp window on a specific time in WPF? | [
"",
"c#",
"wpf-controls",
""
] |
I have a XML file which holds configuration data for data sources, and the related queries held in 'dataseries' elements.
As I don't really need domain objects made up from the XML, rather just settings read and used to configure connections etc. I was wondering if there is any advantage in using the XML schema I have defined?
I am using LINQ to XML for reading my XML and initially thought it would be a good idea to use strongly typed XML.
Should I be using the .xsd or is it overkill?
A mock XML file:
```
<?xml version="1.0" encoding="utf-8" ?>
<datasource name=" Datasource" cache="true">
<database>
<connection>
<provider-name>sqlServer6.0</provider-name>
<source name="E5"
connectionString=""/>
</connection>
<update-interval>30</update-interval>
<minimum-update-interval>2</minimum-update-interval>
</database>
<dataseries name="" identifier="e5">
<graph-type></graph-type>
<query>
SELECT Period, Price
FROM PriceUS
WHERE Date = @date
</query>
</dataseries>
<dataseries name="" identifier="e52">
<graph-type></graph-type>
<query>
SELECT Period, Price
FROM PriceUS
WHERE Date = @date
</query>
</dataseries>
</datasource>
``` | There are two levels of "correct" XML documents: [well-formed and valid](http://en.wikipedia.org/wiki/XML).
Well-formed means it conforms to XML spec, and valid means that it conforms to your schema. If and when you are accepting an XML document from a total stranger, it's usually a good idea to check the validity of the document before moving forward.
As you mentioned, XML schema could also be used to generate XML databinding entities. When you publish a service or a schema to the world or your client, the schema document could be used as a spec. The world or your client can then use the XSD file to validate or databind to XML documents that you exchange. | Technically, there are two formal schema types in XML. There's the original schema syntax, called a Document Type Definition (DTD), which is a holdover from the ancient SGML days. And then there is the W3C standard, XSD, which is more compatible with modern data.
The only reason I mention this is that you might receive an XML file that is described using a DTD and you might need to know how to deal with it.
But please, friends don't let friends create DTDs for new applications. | When should I use xml schemas(.xsd) when reading xml? | [
"",
"c#",
"xml",
"xsd",
""
] |
I have a method on an interface:
```
string DoSomething(string whatever);
```
I want to mock this with MOQ, so that it returns whatever was passed in - something like:
```
_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
.Returns( [the parameter that was passed] ) ;
```
Any ideas? | You can use a lambda with an input parameter, like so:
```
.Returns((string myval) => { return myval; });
```
Or slightly more readable:
```
.Returns<string>(x => x);
``` | Even more useful, if you have multiple parameters you can access any/all of them with:
```
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>()))
.Returns((string a, string b, string c) => string.Concat(a,b,c));
```
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them. | Returning value that was passed into a method | [
"",
"c#",
"mocking",
"moq",
""
] |
I want to be able to asynchronously wait on a socket, then synchronously read from it:
```
for (;;)
{
while (data available on socket)
{
read message from socket;
process it;
}
do something else;
}
```
I need this because I want to poll a queue with messages from GUI at the same time, so the "do something else" part has a short `wait()`.
Is this possible with Java sockets? I tried to check `.available()` on a `DataInputStream`associated with the socket, but
* It seems to work only when I connect, not when I accept a connection (???)
* I get no indication that the connection has been closed.
I tried to do it with a Selector, but it requires the socket channel to be in non-blocking mode all the time. | Why don't you use two threads (or am I misunderstanding what you want to do)? | The Java non-blocking I/O package ([**`java.nio`**](http://java.sun.com/j2se/1.4.2/docs/guide/nio/)) will allow you to do asynchronous reading from a socket via `Selector`s.
Check [this link](http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/index.html) for some examples to get you started. | Java sockets - asynchronous wait, synchronous read | [
"",
"java",
"sockets",
""
] |
is there anything like (1==0 ? "no" : "yes") in javascript? | JavaScript has the conditional operator, so it's perfectly legitimate to do:
```
var response = (1 == 0 ? "no" : "yes");
``` | yes, exactly as you wrote it :) | is there anything like (1==0 ? "no" : "yes") in javascript? | [
"",
"javascript",
""
] |
I am working with a legacy webservice, and they supplied us their WSDL to work with.
Now my problem is, that *every* function specifies the same argument and return type. And this type is then specified as being *string*!
Example:
```
<definitions targetNamespace="java:the.custom.namespace" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="java:the.custom.namespace" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types>
<schema targetNamespace="java:the.custom.namespace" xmlns="http://www.w3.org/1999/XMLSchema" />
</types>
<message name="LegacySystemRequest">
<part name="arg0" type="xsd:string" />
</message>
<message name="LegacySystemResponse">
<part name="return" type="xsd:string" />
</message>
<portType name="LegacySystemPortType">
<operation name="HelloWorld">
<input message="tns:LegacySystemRequest" />
<output message="tns:LegacySystemResponse" />
</operation>
</types>
```
I am not familiar with creating webservices in Java, but is there an obvious thing they could be doing wrong since they are not exposing the structure of their DTOs? I know from examples that they are complex, so I do not want to write to hardcode them all into my code. Is there any technical hints I could give them? | There are often two reasons why they would use strings when they could use more complex types instead:
1) The people who created the SOAP server don't know better and are just too inexperienced to use more complex types.
2) Some application that calls this web service can't handle more complex data types than strings.
As you said, it is a legacy service so it's likely that the people who created it were too inexperienced with SOAP to add more complexity. Considering the fact that the SOAP standard was final in 2003, it's no surprise to find services that old with similar simplicity. It was just too new back then.
This isn't uncommon for any new technology, since many people start using it before they have complete knowledge about it. Once they have the experience, the technique is becoming outdated again.
You could provide them some hints about how to improve it, but I guess they know their service isn't very good. They just might not have the resources to improve it. Or maybe they're already improving this service but the new service might still be in beta. | It's impossible to say for sure from this WSDL, but I would guess that the web service is nothing more than a carrier for arbitrary data, and was probably bolted on to a legacy system.
The strings could be anything, perhaps XML in themselves, or perhaps CSV data, or something like that. Certainly not a good example of WSDL design.
You'll just have to invoke it and see what you get back....
Also, this WSDL looks like it might be from an rpc-encoded web service, which is not compatible with modern java WS stacks, which require document-encoding. Older stacks (like Axis 1) support it, though. | Why does a webservice specify all request and response types as a string? | [
"",
"java",
"web-services",
"wsdl",
""
] |
How can you make a simple tag like `<img src="a.gif">` hidden programmatically using JavaScript? | I'm not sure I understand your question. But there are two approaches to making the image invisible...
Pure HTML
```
<img src="a.gif" style="display: none;" />
```
Or...
HTML + Javascript
```
<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>
<img id="myImage" src="a.gif" />
``` | You can hide an image using javascript like this:
```
document.images['imageName'].style.visibility = hidden;
```
If that isn't what you are after, you need to explain yourself more clearly. | How to create a hidden <img> in JavaScript? | [
"",
"javascript",
"html",
"css",
""
] |
I am creating an application where the user needs to log in to access data. I would like to save the user credentials when they first login and give a "Remember Me" option.
Is there any class/interface implementation which I can use in my WinMo application in order to be able to do this? Or is SQL the only option available?
Thanks. | SQL Server certainly isn't the only option. There isn't any specific "save and retrieve the following user and password info" API, but basically all you're saying is that you need to be able to save some data and retrieve it the next time the app runs. You could save that info in the registry or in a file of any sort (SQL CE, text, MySQL, custom binary format, etc). | There is a feature in Windows Mobile for managing credential information such as user names and passwords called [Credential Manager](http://msdn.microsoft.com/en-us/library/ms881554.aspx). | Windows Mobile - saving user data across application sessions | [
"",
"c#",
"windows-mobile",
"compact-framework",
"persistence",
""
] |
The application that I am having trouble with is a generic web application... nothing special about the way it handles users. That is to say, I handle user information in the session variable, with the session managed via a cookie.
A client of mine is having an issue whereby the users are logged in and every now and again they are presented with a page for a different user (this is easy to determine because the user's name is at the top of each page). If they click the 'Home' link, everything is fine again, apparently.
Now as far as my PHP knowledge is concerned, it would take some effort to mix this kind of thing up, right? I can't replicate the issue in any of our development environments and as far as I am concerned, like I say, it would take some effort to actually 'share' this kind of session information...
So my question is this: what could be the possible problems? Every time I experienced this before it was due to a 'mis-behaving' proxy server, though they are telling me that they are not proxying the requests.
Is there anything else that I may be missing? Any other possible reasons for this (naturally this could include an issue with my code)?
Thanks... | So it turns out that the final outcome of *this* situation, at least, was fairly oddball.
It turns out that the client was using handheld computers to access the application and letting the batteries go flat. This particular device then reset its clock to 2005 when the battery was eventually recharged and it seems as though this led the browser to read certain pages from its cache.
As soon as the clock on the device/s was set correctly, the issue went away.
Thanks to all for the suggestions: I hate trying to debug these caching type issues. I guess, though, that I really should add some headers to try and stop these handhelds caching the data. | By the sounds of it, even though your client assures you that it isn't, it still seems like a proxy or caching problem to me. If at all possible, you could add something like a timestamp when a page was generated somewhere near the user field just to make sure the request is up to date.
This way if the page messes up, you have some indication if the page was generated earlier and stored by something on the way. If your ajax results are cached by the browser and your client has multiple people on the same webbrowser, it wouldn't require a proxy to get wacky results.
Another way you could attack this problem is by logging the requests from your client, and checking if you've missed anything. If you play back the requests, do you get the same result?
Can you verify that when you are logged in as user A, and you 'misplace' your session cookie (delete it), can you still get to the information you wanted? If so, there might be something wrong with the way authentication is handled.
Hope this helps! | PHP User Sessions Getting 'Muddled' | [
"",
"php",
"session",
""
] |
Is there a way to know, during run-time, a variable's name (from the code)?
Or do variable's names forgotten during compilation (byte-code or not)?
e.g.:
```
>>> vari = 15
>>> print vari.~~name~~()
'vari'
```
**Note**: I'm talking about plain data-type variables (`int`, `str`, `list` etc.) | here a basic (maybe weird) function that shows the name of its argument...
the idea is to analyze code and search for the calls to the function (added in the **init** method it could help to find the instance name, although with a more complex code analysis)
```
def display(var):
import inspect, re
callingframe = inspect.currentframe().f_back
cntext = "".join(inspect.getframeinfo(callingframe, 5)[3]) #gets 5 lines
m = re.search("display\s+\(\s+(\w+)\s+\)", cntext, re.MULTILINE)
print m.group(1), type(var), var
```
please note:
getting multiple lines from the calling code helps in case the call was split as in the below example:
```
display(
my_var
)
```
but will produce unexpected result on this:
```
display(first_var)
display(second_var)
```
If you don't have control on the format of your project you can still improve the code to detect and manage different situations...
Overall I guess a static code analysis could produce a more reliable result, but I'm too lazy to check it now | Variable names don't get forgotten, you can access variables (and look which variables you have) by introspection, e.g.
```
>>> i = 1
>>> locals()["i"]
1
```
However, because there are no pointers in Python, there's no way to reference a variable without actually writing its name. So if you wanted to print a variable name and its value, you could go via `locals()` or a similar function. (`[i]` becomes `[1]` and there's no way to retrieve the information that the `1` actually came from `i`.) | How to retrieve a variable's name in python at runtime? | [
"",
"python",
""
] |
When should I go for a Windows Service and when should I go for a "Background Application" that runs in the notification area?
If I'm not wrong, my design decision would be, any app that needs to be running before the user logins to the computer should be a service. For everything else use a background app. Is my decision right?
Moreover, if I need "admin privileges" for my background app, I would escalate using a manifest. Are there any other specific advantage of running as a service? | My general rules of thumb are as follows
* If it needs to always run, it's a service.
* If it needs to be run under a particular user account, Network Service, Local System, generally it's a service (or a COM+ application)
* If the user needs some control over it, it's generally a notification area application.
* If it needs to notify the user of something, it's a notification area application
The fun comes when you have the need to run something as a system account, but also interact with it. IIS is a good example of this, it's a service, but the administration is an application - it needs to be running at the startup, it needs access to particular things a user can't normal access (c:\inetpub), but the user needs to be able to start, stop and configure it. | I would design an application as a service if the applcation has a critical purpose and should never (or rarely) be closed. Windows services provide good crash-recovery options, good notifications (see the recovery tab in service property).
Also a good reason to use services is because they can run under any user ( so if you
deploy them on a server that you remote to, you can safely log out after starting the service without worring that the application will close too).
I also design services in combination with a desktop application that can interact with the service and can be used to monitor or reconfigure the service while running. This way you can have all the benefits of a tray application, in your service.
However, you should not abuse using services and only use them, as I said, for cirtical applications. | Windows Service vs Windows Application - Best Practice | [
"",
"c#",
"windows",
"winforms",
"windows-services",
""
] |
I'm working on a PHP project and I would like to know recommendations for implementing [continuous integration](http://en.wikipedia.org/wiki/Continuous_integration).
I've read all the theory, but I never got to use continuous integration. So it should be rather easy to start.
I've read about [Xinc](http://code.google.com/p/xinc/), [Hudson](http://en.wikipedia.org/wiki/Hudson_%28software%29), among others, but I would like to get some feedback based on experience. Have you used continuous integration in PHP projects? What has been your experience? Which server would you recommend? | I have had good luck with [phpUnderControl](http://phpundercontrol.org/about.html), which is based on CruiseControl. | There is also Jenkins now that [Oracle made a fuss about Hudson](http://www.infoq.com/news/2011/01/jenkins). There is a config template for it that makes it ridiculously easy to setup with all the [QA Tools](http://phpqatools.org/) you'd need for a PHP CI environment:
* <http://edorian.github.io/2011-02-01-setting-up-jenkins-for-php-projects>
* <http://jenkins-php.org>
* <http://jenkins-ci.org> | Recommended server for continuous integration for a PHP project | [
"",
"php",
"continuous-integration",
""
] |
I have a server which is set to EST, and all records in the database are set to EST. I would like to know how to set it to GMT. I want to offer a time zone option to my users. | No matter in which GMT time zone the server is, here is an extremely easy way to get time and date for any time zone. This is done with the `time()` and `gmdate()` functions. The `gmdate()` function normally gives us GMT time, but by doing a trick with the `time()` function we can get GMT+N or GMT-N, meaning we can get the time for any GMT time zone.
For example, if you have to get the time for GMT+5, you can do it as follows
```
<?php
$offset=5*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()+$offset);
?>
```
Now if you have to get the time for GMT-5, you can just subtract the offset from the `time()` instead of adding to it, like in the following example where we are getting the time for GMT-4
```
<?php
$offset=4*60*60; //converting 4 hours to seconds.
$dateFormat="d-m-Y H:i"; //set the date format
$timeNdate=gmdate($dateFormat, time()-$offset); //get GMT date - 4
?>
``` | I would *strongly* suggest avoiding messing with UNIX timestamps to make it look like a different time zone. This is a lesson I've learnt the hard way, way too many times.
A timestamp is the number of seconds since Midnight 1 January 1970, GMT. It doesn't matter where you are in the world, a given timestamp represents the exact same moment in time, regardless of time zones. Yes, the timestamp "0" means 10am 1/1/70 in Australia, Midnight 1/1/70 in London and 5pm 31/12/69 in LA, but this doesn't mean you can simply add or subtract values and guarantee accuracy.
The golden example which stuffed me up every year for way too long was when daylight savings would crop up. Daylight savings means that there are "clock times" which don't exist in certain parts of the world. For example, in most parts of the US, there was no such time as 2:01am on April 2, 2006.
Enough quasi-intelligible ranting though. My advice is to store your dates in the database as timestamps, and then...
* If you need the local time at the server, use [`date()`](http://php.net/date)
* If you need to get GMT, then use [`gmdate()`](http://php.net/gmdate)
* If you need to get a different timezone, use [`date_default_timezone_set()`](http://php.net/date_default_timezone_set) and then `date()`
For example,
```
$timestamp = time();
echo "BRISBANE: " . date('r', $timestamp) . "\n";
echo " UTC: " . gmdate('r', $timestamp) . "\n";
date_default_timezone_set('Africa/Johannesburg');
echo " JOBURG: " . date('r', $timestamp) . "\n";
// BRISBANE: Tue, 12 May 2009 18:28:20 +1000
// UTC: Tue, 12 May 2009 08:28:20 +0000
// JOBURG: Tue, 12 May 2009 10:28:20 +0200
```
This will keep your values clean (you don't have to be worrying about adding offsets, and then subtracting before saving), it will respect all Daylight Savings rules, and you also don't have to even look up the timezone of the place you want. | How do I get Greenwich Mean Time in PHP? | [
"",
"php",
"timezone",
""
] |
Is there a limit to the number of critical sections I can initialize and use?
My app creates a number of (a couple of thousand) objects that need to be thread-safe. If I have a critical section within each, will that use up too many resources?
I thought that because I need to declare my own CRITICAL\_SECTION object, I don't waste kernel resources like I would with a Win32 Mutex or Event? But I just have a nagging doubt...?
To be honest, not all those objects probably *need* to be thread-safe for my application, but the critical section is in some low-level base class in a library, and I do need a couple of thousand of them!
I may have the opportunity to modify this library, so I was wondering if there is any way to lazily create (and then use from then on) the critical section only when I detect the object is being used from a different thread to the one it was created in? Or is this what Windows would do for me? | If you read carefully the documentation for [IntializeCriticalSectionWithSpinCount()](http://msdn.microsoft.com/en-us/library/ms683476(VS.85).aspx), it is clear that each critical section is backed by an Event object, although the API for critical sections treats them as opaque structures. Additionally, the 'Windows 2000' comment on the dwSpinCount parameter states that the event object is "allocated on demand."
I do not know of any documentation that says what conditions satisfy 'on demand,' but I would suspect that it is not created until a thread blocks while entering the critical section. For critical sections with a spin count, it may not be until the spin wait is exhausted.
Empirically speaking, I have worked on an application that I know to have created at least 60,000 live COM objects, each of which synchronizes itself with its own CRITICAL\_SECTION. I have never seen any errors that suggested I had exhausted the supply of kernel objects. | There's no limit to the number of `CRITICAL_SECTION` *structures* that you can declare -- they're just POD data structures at the lowest level. There may be some limit to the number that you can *initialize* with [`InitializeCriticalSection()`](http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx). According to the documentation, it might raise a `STATUS_NO_MEMORY` exception on Windows 2000/XP/Server 2003, but apparently it's guaranteed to succeed on Vista. They don't occupy any kernel resources until you initialize them (if they take any at all).
If you find that the `STATUS_NO_MEMORY` exception is being raised, you can try only initializing the `CRITICAL_SECTION` for a given object if there's a chance it could be used in a multiple threads. If you know a particular object will only be used with one thread, set a flag, and then skip all calls to `InitializeCriticalSection()`, `EnterCriticalSection()`, `LeaveCriticalSection()`, and `DeleteCriticalSection()`. | How many CRITICAL_SECTIONs can I create? | [
"",
"c++",
"multithreading",
"winapi",
"windows-xp",
"thread-safety",
""
] |
The clue is in the title but basically I've inherited some code which has 800+ instances of strcpy. I want to write a new function and then to replace strcpy with strcpy\_mine.
So I'm trying to work out what parameter list strcpy\_mine will have.
I tried:
```
void strcpy_mine( char* pTarget, const char* const pCopyMe )
{
const unsigned int lenAlwaysFour = sizeof(pCopyMe ); //:(
strncpy( pTarget, pCopyMe, lenAlwaysFour );
//add extra terminator in case of overrun
pTarget[lenAlwaysFour] = 0;
}
```
but the sizeof is always 4 pCopyMe is a pointer
what I don't want to do is replace
```
strcpy (buf, pCopyMe);
```
with
```
strncpy (buf, pCopyMe, sizeof(pCopyMe)); buf[sizeof(pCopyMe)] = 0;
```
Any ideas? (strcpy\_l isn't available) | Depending on how the call-sites look like, often majority of cases can be handled by a simple template:
```
#include <string.h>
template <int bufferSize>
void strcpy_mine( char (&pTarget)[bufferSize], const char* const pCopyMe )
{
strncpy( pTarget, pCopyMe, bufferSize-1 );
//add extra terminator in case of overrun
pTarget[bufferSize-1] = 0;
}
int main()
{
char buf[128];
strcpy_mine(buf,"Testing");
return 0;
}
```
If you are using Microsoft Visual Studio 2005 or newer, see [Secure Template Overloads](http://msdn.microsoft.com/en-us/library/ms175759(VS.80).aspx) for a Microsoft implementation. | sizeof() returns the size of the type - in this case `const char* const` which will be 4 on 32-bit machines.
I think you think you want `strlen()`. But that isn't the right way to use strncpy functions.
You need the size of the **output** buffer for strncpy.
To fix this you need to examine the code at each call site, and work out the size of the output buffer, and pass that as an argument to `strcpy_mine`. If the call-site for strcpy (or strcpy\_mine) doesn't know the size of the output buffer, you need to search backwards in the code for the location that allocates the buffer, and pass the size all the way down to the strcpy site.
Basically you can't write a drop in replacement for strcpy that takes the same arguments and hope to avoid the problems that produced strncpy in the first place (and better replacements beyond that). You can create a function that takes the same arguments as strncpy, but ensures the result is null-terminated - look at the implementation of [OpenBSD's strlcpy()](http://en.wikipedia.org/wiki/Strlcpy) function. But the first step has to be to change the calling sites to pass on knowledge of the output buffer size. | strcpy... want to replace with strcpy_mine which will strncpy and null terminate | [
"",
"c++",
"c",
"strcpy",
""
] |
I'm interested in learning about the available choices of **high-quality, stand-alone source code formatters for Java.**
The formatter must be stand-alone, that is, it must support a **"batch" mode** that is [**decoupled from any particular development environment**](https://stackoverflow.com/questions/384101). Ideally, it should be **independent of any particular operating system** as well. So, a built-in formatter for the IDE du jour is of little interest here (unless that IDE supports batch mode formatter invocation, perhaps from the command line). A formatter written in closed-source C/C++ that only runs on, say, Windows is not ideal, but is somewhat interesting.
**To be clear, a "formatter" (or "beautifier") is not the same as a "style checker."** A formatter accepts source code as input, applies styling rules, and produces styled source code that is semantically equivalent to the original source code. Syntactic modifications are limited to things like modifying code layout as in changing whitespace, or organizing `import` statements. Very little, if any, other refactoring is performed. A style checker also applies styling rules, but it simply *reports* rule violations *without producing modified source code* as output. So the picture looks like this:
**Formatter** (produces modified source code that conforms to styling rules)
Read Source Code → Apply Styling Rules → Write Styled Source Code
**Style Checker** (does not produce modified source code)
Read Source Code → Apply Styling Rules → Write Rule Violations
**Further Clarifications**
Solutions must be highly configurable. I want to be able to specify my own style, not simply select from a preset list.
Also, I'm **not looking for a [general purpose pretty-printer written in Java](https://stackoverflow.com/questions/332166)** that can pretty-print many things. I want to style Java code.
I'm also **not *necessarily* interested in a [grand-unified formatter](https://stackoverflow.com/questions/251622)** for many languages. I suppose it might be nice for a solution to have support for languages other than Java, but that is not a requirement.
Furthermore, **[tools that only perform code highlighting](https://stackoverflow.com/questions/206441) are [right](http://en.wikipedia.org/wiki/Holy_Hand_Grenade_of_Antioch) [out](http://www.youtube.com/watch?v=xOrgLj9lOwk).**
I'm also **not interested in a web service.** I want a tool that I can run locally.
Finally, solutions need not be restricted to open source, public domain, shareware, free software, commercial, or anything else. **All forms of licensing are acceptable**. | JIndent (Commercial) does what you want:
<http://www.jindent.com/>
I've also used Jalopy in the past to do this, it's open source:
<http://jalopy.sourceforge.net/>
EDIT: I will note that Jalopy is fairly old and there doesn't seem to be any recent updates to it. I'm not quite sure if it will work with Java 5/6. You might want to look at Jacobe instead:
<http://www.tiobe.com/index.php/content/products/jacobe/Jacobe.html>
There's also a more complete list of formatters here on Roedy Green's site:
<http://mindprod.com/jgloss/beautifier.html> | You can also run Eclipse reformatter from command line.
Here is the [Eclipse documentation of the feature](http://topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-231.htm)
First you have to [create configuration file specific to your project of your Java code formatter settings.](https://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-231.htm)
Then save `{projectDirectory}/.settings/org.eclipse.jdt.core.prefs` to another location.
Now you will call the formatter.
`"c:\path\to\eclipse\eclipse.exe" -vm "C:\path\to\jdk\bin\java.exe" -application org.eclipse.jdt.core.JavaCodeFormatter -config "c:\path\to\org.eclipse.jdt.core.prefs" "C:\path\to\your\src"`
[WARNING] This seems to have stopped working in Eclipse 2018. Use Eclipse Oxygen. | Stand-alone Java code formatter/beautifier/pretty printer? | [
"",
"java",
"coding-style",
"code-formatting",
""
] |
How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it.
You might think that it is `SelectedItem` but apparently that ~~does not exist~~ is readonly and therefore unusable.
This is what I want to do:
```
<TreeView ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource ClusterTemplate}"
SelectedItem="{Binding Path=Model.SelectedCluster}" />
```
I want to bind the `SelectedItem` to a property on my Model.
But this gives me the error:
> 'SelectedItem' property is read-only and cannot be set from markup.
**Edit:**
Ok, this is the way that I solved this:
```
<TreeView
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}"
SelectedItemChanged="TreeView_OnSelectedItemChanged" />
```
and in the codebehindfile of my xaml:
```
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Model.SelectedCluster = (Cluster)e.NewValue;
}
``` | I realise this has already had an answer accepted, but I put this together to solve the problem. It uses a similar idea to Delta's solution, but without the need to subclass the TreeView:
```
public class BindableSelectedItemBehavior : Behavior<TreeView>
{
#region SelectedItem Property
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));
private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var item = e.NewValue as TreeViewItem;
if (item != null)
{
item.SetValue(TreeViewItem.IsSelectedProperty, true);
}
}
#endregion
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
if (this.AssociatedObject != null)
{
this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
}
}
private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
this.SelectedItem = e.NewValue;
}
}
```
You can then use this in your XAML as:
```
<TreeView>
<e:Interaction.Behaviors>
<behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
</e:Interaction.Behaviors>
</TreeView>
```
Hopefully it will help someone! | This property exists : [TreeView.SelectedItem](http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditem.aspx)
But it is readonly, so you cannot assign it through a binding, only retrieve it | Data binding to SelectedItem in a WPF Treeview | [
"",
"c#",
"wpf",
"mvvm",
"treeview",
"selecteditem",
""
] |
I have a Windows Mobile application in which I want to check the device orientation.
Therefore I wrote the following property in one of my forms:
```
internal static Microsoft.WindowsCE.Forms.ScreenOrientation DeviceOriginalOrientation { get; private set; }
```
The strange thing is that after that whenever I open a UserControl, the designer shows this warning even if that UserControl doesn't use the property:
**Could not load file or assembly 'Microsoft.WindowsCE.Forms, Version=3.5.0.0, Culture=neutral, PublicKeyToken=969db8053d3322ac' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**
Commenting the above property will dismiss the warning and shows the user control again.
The application is built successfully and runs without any problems in both cases.
Does anybody know why this happens and how can I fix it? | This problem cost me a couple of hours. I solved it by adding the Microsoft.WindowsCE.Forms.dll to the GAC using gacutil. Hope it helps.
Robin | Yes, this is pretty much expected. Since it's a static property (which I'd disagree with in the first place) the designer has to initialize it, which means loading up Microsoft.WindowsCE.Forms, which means loading device-specific entry points. Admittedly, the error message sucks, but then the designer support for device stuff has [lots of fun issues](http://blog.opennetcf.com/ctacke/2008/11/26/Studio08sToolboxAndCompactFrameworkAssemblies.aspx) that are hard to divine the causes for.
I'd try moving it to another class or wrapping it with a check to see if you're in the designer. Something like this works for us:
```
protected bool IsDesignTime
{
get
{
// Determine if this instance is running against .NET Framework
// by using the MSCoreLib PublicKeyToken
System.Reflection.Assembly mscorlibAssembly = typeof(int).Assembly;
if ((mscorlibAssembly != null))
{
if (mscorlibAssembly.FullName.ToUpper().EndsWith("B77A5C561934E089"))
{
return true;
}
}
return false;
}
}
``` | Strange behaviour with Microsoft.WindowsCE.Forms | [
"",
"c#",
"visual-studio-2008",
"compact-framework",
""
] |
> **Possible Duplicate:**
> [Multiline strings in Javascript](https://stackoverflow.com/questions/805107/multiline-strings-in-javascript)
In Ruby you can do something like this:
```
temp = <<-SQLCODE
select * from users
SQLCODE
```
This way you have very long string literals in your code without having to escape lots of characters. Is there something similar in JavaScript?
Currently I have JavaScript code like this, and it's driving me nuts...
```
new Element.update(lightbox_id, " \
<div id='overlay' class='overlay' > \
</div> \
<div id='lightbox' class='lightbox'> \
<div class='lightbox_title'> \
<div class='corner_image' onclick=\"close_lightbox();return false;\"><a href='#'>" + corner_image + "</a></div> \
<div class='lightboxname' id='lightboxname'>" + title + "</div> \
<div class='close_image'> \
<a href='#' onclick=\"close_lightbox();return false;\">Close</a> or Escape key\
</div> \
</div> \
<div id='" + lightbox_content_id + "' class='lightbox_content'> \
</div> \
<script> \
watch_for_escape(); \
</script> \
</div> \
");
``` | The syntax you are referring to is often known as [here-document (or HEREDOC)](http://en.wikipedia.org/wiki/Heredoc) and no, it is not available in Javascript.
Adding a backslash as you have been doing is the appropriate way to span strings over multiple lines in JavaScript. | Having html inline like that is bad practice, but if you really want to handle it cleaner, try this:
Place a hidden div on your page with the html you want, and replace the custom params with something like {title}. When calling update, pass yourdiv.innerHTML.replace(... | What is the best way to have long string literals in Javascript? | [
"",
"javascript",
"ruby-on-rails",
"ruby",
"heredoc",
""
] |
I have discovered that results coming from my SQL Server are having the field names truncated:
```
$query = "SELECT some_really_really_long_field_name FROM ..."
...
print_r($row);
array(
'some_really_really_long_field_n' => 'value'
)
```
Does anyone know how to avoid this behaviour?
I think the database driver is ADODB.
So you don't have to count: the field names are being truncated to 31 characters.
SQL Server doesn't seem to mind the long field names in itself, so I can only presume that there is a char[32] string buffer somewhere in the ADODB driver which can't contain the long names. | You're probably using the decade-old, deprecated bundled MSSQL client. Use the [new MSSQL driver for PHP from Microsoft](http://www.microsoft.com/sqlserver/2005/en/us/PHP-Driver.aspx) or install the MSSQL client tools from your MSSQL server CD. | you can use an alias for your long field names, something like this:
```
$query = "SELECT some_really_really_long_field_name AS short_alias FROM ..."
```
this will work for your current problem. But I suggest using [PDO](http://ir.php.net/manual/en/book.pdo.php) MSSQL driver to connect to database. | PHP & SQL Server - field names truncated | [
"",
"php",
"sql-server-2005",
""
] |
I have a piece of software that has worked fine on many machines, althoughon one machine there is a problem that appears to occur occasionaly, the MenuStrip and the ToolStrip both appear as a blank white background with a red cross over it, as a custom control would if you created a null object. This doesn't happen whilst I am debugging and I don't know how to make the problem re-occur, but it does happen. I was wondering if anyone knew what could be the problem?
Would it be the version of the .NET framework?
Thanks | This is a common occurrence when there's a GDI+ problem ("The Red X of Death"). Are you doing any custom drawing in `OnPaint`? Or perhaps there's a graphic resource or a glyph which is corrupt or being improperly disposed of.
**Edit:** I've re-read your question. You seem to have this only on one of the machines. I've googled around a bit for this, and I stumbled upon [this old thread](http://www.developmentnow.com/g/20_2006_2_0_0_689988/A-generic-error-occurred-in-GDI-exception-and-Red-X-displayed-on-Form.htm). The post at the bottom suggests that there might be an issue with Virtual Memory turned off:
> We did manage to solve this - we were
> seeing the problem on a device running
> XP embedded. The XPe image developer
> had turned off Virtual Memory and as
> soon as we turned it on the problem
> went away. I believe it is just a
> symptom of the system running out of
> memory to display the graphics (maybe
> particularly if you use a lot of
> double buffering)
Hope that helps. | Sounds like a symptom of an [Out Of Memory Exception](http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx) to me.
**Edit:**
Which can sometimes lead onto a `System.InvalidOperationException: BufferedGraphicsContext` | "Red Cross" problem on MenuStrip and ToolStrip | [
"",
"c#",
"multithreading",
"toolstrip",
"menustrip",
""
] |
Yesterday I ran into a g++ (3.4.6) compiler problem for code that I have been compiling without a problem using the Intel (9.0) compiler. Here's a code snippet that shows what happened:
```
template<typename A, typename B>
class Foo { };
struct Bar {
void method ( Foo<int,int> const& stuff = Foo<int,int>() );
};
```
The g++ compiler error is:
```
foo.cpp:5: error: expected `,' or `...' before '>' token
foo.cpp:5: error: wrong number of template arguments (1, should be 2)
foo.cpp:2: error: provided for `template<class A, class B> struct Foo'
foo.cpp:5: error: default argument missing for parameter 2 of `void Bar::method(const Foo<int, int>&, int)'
```
Apparently, the default argument is not accepted when written this way, and the compiler assumes that instead of the second template argument a new function argument is specified, for which it then expects a default value because the `stuff` argument has one. I can help the compiler by creating a typedef, and then everything compiles fine:
```
template<typename A, typename B>
class Foo { };
struct Bar {
typedef Foo<int,int> FooType;
void method ( FooType const& stuff = FooType() );
};
```
So I can solve my problem, but I don't understand what is going on. Do I miss a C++ (template?) language feature here and am I doing something wrong, or is the g++ compiler wrong in not accepting the first piece of code?
Note BTW that this also compiles ...
```
template<typename A, typename B>
class Foo { };
void method ( Foo<int,int> const& stuff = Foo<int,int>() );
``` | I am not so sure that this is a bug in g++ (since version 4.2.4). The code now passes in g++ 4.4 (see UPDATE below). In order to have this code compile for other versions of compilers you can add a set of parenthesis around the default argument:
```
template<typename A, typename B>
class Foo { };
struct Bar {
void method ( Foo<int,int> const& stuff = ( Foo<int,int>() ) );
};
```
IMO, these parenthesis are necessary as there is an additional requirement that the default argument can refer to a member of the class that may be declared later in the class body:
```
struct Bar {
void method ( int i = j); // 'j' not declared yet
static const int j = 0;
};
```
The above code is legal, and when the declaration for 'method' is being parsed the member 'j' has not yet been seen. The compiler therefore can only parse the default argument using *syntax* checking only, (ie. matching parenthesis and commas). When g++ is parsing your original declaration, what it is actually seeing is the following:
```
void method ( Foo<int,int> const& stuff = Foo<int // Arg 1 with dflt.
, int>() ); // Arg 2 - syntax error
```
Adding the extra set of parenthesis ensures that the default argument is handled correctly.
The following case shows an example where g++ succeeds but Comeau still generates a syntax error:
```
template<int J, int K>
class Foo { };
struct Bar {
void method ( Foo<0, 0> const & i = ( Foo<j, k> () ) );
static const int j = 0;
static const int k = 0;
};
```
**EDIT:**
In response to the comment: "You could just as well have a function call with multiple arguments there", the reason that this does not cause a problem is that the comma's inside the function call are surrounded in parenthesis:
```
int foo (int, int, int);
struct Bar {
void method ( int j =
foo (0, 0, 0) ); // Comma's here are inside ( )
};
```
It is possible therefore, to parse this using the *syntax* of the expression only. In C++, all '(' must be matched with ')' and so this is easy to parse. The reason for the problem here is that '<' does not need to be matched, since it is overloaded in C++ and so can be the less than operator or the start of a template argument list. The following example shows where '<' is used in the default argument and implies the less than operator:
```
template<int I, int J>
class Foo { };
struct Bar {
template <typename T> struct Y { };
void method ( ::Foo<0,0> const& stuff = Foo<10 , Y < int > = Y<int>() );
struct X {
::Foo<0, 0> operator< (int);
};
static X Foo;
};
```
The above "Foo<10" is a call to the "operator<" defined in 'X', not the start of the template argument list. Again, Comeau generates syntax errors on the above code and g++ (including 3.2.3) parse this correctly.
FYI, the appropriate references are a note in 8.3.6/5:
> [Note: in member function declarations, names in default argument expressions are looked
> up as described in 3.4.1...
and then in 3.4.1/8
> A name used in the definition of a member function (9.3) of class X following the function’s declaratorid29)
> shall be declared in one of the following ways:
...
> — shall be a member of class X or be a member of a base class of X (10.2), or
This bullet here, is the part that forces the compiler to "delay" lookup for the meaning of the default argument until all of the class members have been declared.
**<UPDATE>**
As pointed out by "Employed Russian", g++ 4.4 is now able to parse all of these examples. However, until the [DR](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#325) has been addressed by the C++ standards committee I am not yet ready to call this a "bug". I believe that long term extra parenthesis will be required to ensure portability to other compilers/tools (and maybe even future versions of g++).
It has been my experience that the C++ standard does not dictate that compiler vendors should all use the same parser technology and they also cannot expect that all technologies are equally powerful. As a result, parsing requirements normally don't require that vendors perform superhuman feats. To illustrate this consider the following two examples:
```
typedef T::TYPE TYPE;
T::TYPE t;
```
If 'T' is dependent, then given each context 'TYPE' **must** be a typename, however the standard still requires the *typename* keyword. These examples are unambiguous and can only mean one thing, however the standard (in order to allow for all parser technologies) still requires the *typename* keyword.
It's possible that the DR may be addressed in such a way that a compiler which fails to parse these examples will still be "standard conforming" as long as extra parenthesis allows the code to parse.
**</UPDATE>** | This is a known [bug](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57) in gcc.
It has been fixed in gcc-4.4, which compiles the original source just fine. | default template class argument confuses g++? | [
"",
"c++",
"templates",
"gcc",
"g++",
"intel",
""
] |
We are running tomcat application server that handle over 100 concurrent sessions.
In the last 2 months the most active users noticed that sometimes they are getting kicked off from the system.
As I understood from the log tomcat sessions are getting expired without any reason.
I see no problems from the web application side.
Is there any problem from the tomcat side?
Tomcat 6.0.18. | If there has been no code change triggering this, I would look at memory usage. This *might* be the effect of Tomcat running out of memory and invalidating sessions to recover.
If at all possible monitor garbage collections, and/or put surveillance on with jconsole Java Flight Recorder or jvisualvm. | A possible cause is that you put in the session an object that does NOT implement the Serializable interface. Tomcat occasionally writes some of the sessions on the disk. If a session contains non-serializable objects it will simply be removed from the container (because of the NotSerializableException). If this is happening you should see the Exception in the tomcat log file. | Tomcat sessions expiring unexpectedly | [
"",
"java",
"session",
"tomcat",
""
] |
I am having a command line arguments as like this I need to get the two as like this how is it possible
ApplicationId =1; Name =2
I like to get the two values 1,2 in single array how to do this. | Try
```
string values = "ApplicationId =1; Name =2";
string[] pairs = values.Split(';');
string value1 = pairs[0].Split('=')[1];
string value2 = pairs[1].Split('=')[1];
```
You'll need better error checking of course, but value1 and value2 should be "1" and "2" respectively | It isn't entirely clear to me, but I'm going to assume that the arguments are actually:
```
ApplicationId=1 Name=2
```
the spacing etc is important due to how the system splits arguments. In a `Main(string[] args)` method, that will be an array length 2. You can process this, for example into a dictionary:
```
static void Main(string[] args) {
Dictionary<string, string> options = new Dictionary<string, string>();
foreach (string arg in args)
{
string[] pieces = arg.Split('=');
options[pieces[0]] = pieces.Length > 1 ? pieces[1] : "";
}
Console.WriteLine(options["Name"]); // access by key
// get just the values
string[] vals = new string[options.Count];
options.Values.CopyTo(vals, 0);
}
``` | command line arguments array | [
"",
"c#",
"command-line",
""
] |
I want to make sure I don't pummel the permgen space, so I'm carefully interning my strings.
Are these two statements equivalent ?
```
String s1 = ( "hello" + "world" ).intern();
String s2 = "hello".intern() + "world".intern();
```
**UPDATE**
How I framed my question was totally different from the actual application. Here's the method where I am using intern.
```
public String toAddress( Transport transport )
{
Constraint.NonNullArgument.check( transport, "transport" );
switch( transport )
{
case GOOGLE:
case MSN:
return ( transport.code() + PERIOD + _domain ).intern();
case YAHOO:
default:
return _domain;
}
}
private String _domain; // is initialized during constructor
private static final String PERIOD = ".";
``` | The best advice I can think of is: don't bother. Statically declared String's will be in the constant pool any how so unless you are dynamically creating a String that is...errr no I can't think of a reason.
I've been programming using Java since 97 and I've never actually used `String.intern()`.
EDIT: After seeing your update I really am of the opinion that you shouldn't be using intern(). Your method looks perfectly normal and there there is little or no reason to use intern().
My reason for this is that it is infect an optimisation and potentially a premature one at that, you are second guessing the garbage collector. If the just of you method is short lived then the resulting string will die the young generation very shortly afterwards in the next minor GC and if it isn't it'll be interned (for want of a better word) in the mature generation anyhow.
I guess the only time this could be a good idea is if you spend a bit of time with a profiler and prove that it makes a large difference to the performance of your application. | As jensgram says, the two statements are not equivalent. Two important rules:
* Concatenating string literals in code ends up with a string constant, so these two statements *are* exactly equivalent (they'll produce identical bytecode):
```
String x = "foo" + "bar":
String x = "foobar";
```
* String constants are interned automatically, you don't need to do it explicitly
Now, this concentrates on literals - are you *actually* calling `intern` on literals, or is your real use case somewhat different (e.g. interning values fetched from a database which you'll see frequently)? If so, please give us more details.
EDIT: Okay, based on the question edit: this *could* save some memory *if* you end up storing the return value of `toAddress()` somewhere that it'll stick around for a long time *and* you'll end up with the same address multiple times. If those *aren't* the case, interning will actually probably make things worse. I don't know for sure whether interned strings stick around forever, but it's quite possible.
This looks to me like it's *unlikely* to be a good use of interning, and may well be making things worse instead. You mention trying to save permgen space - why do you believe interning will help there? The concatenated strings won't end up in permgen anyway, unless I'm much mistaken. | Am I correctly interning my Strings? | [
"",
"java",
"memory-management",
""
] |
I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.
I'm not the first to ask a question on this subject [see [here](https://stackoverflow.com/questions/567999/preventing-beautifulsoup-from-converting-my-xml-tags-to-lowercase)]. However, I did not understand the answer given to that question and in BeautifulSoup-3.1.0.1 BeautifulSoup.py does not appear to contain any instances of "`encodedName`" or "`Tag.__str__`" | According to Leonard Richardson, creator|maintainer of Beautiful Soup, you [can't](http://groups.google.com/group/beautifulsoup/browse_thread/thread/ff6910752566df78). | ```
import html5lib
from html5lib import treebuilders
f = open("mydocument.html")
parser = html5lib.XMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup"))
document = parser.parse(f)
```
'document' is now a BeautifulSoup-like tree, but retains the cases of tags. See [html5lib](http://code.google.com/p/html5lib/) for documentation and installation. | Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase? | [
"",
"python",
"xml",
"beautifulsoup",
""
] |
One of the C++0x improvements that will allow to write more efficient C++ code is the unique\_ptr smart pointer (too bad, that it will not allow moving through memmove() like operations: the proposal didn't make into the draft).
**What are other performance improvements in upcoming standard?** Take following code for example:
```
vector<char *> v(10,"astring");
string concat = accumulate(v.begin(),v.end(), string(""));
```
The code will concatenate all the strings contained in vector **v**. The problem with this neat piece of code is that accumulate() copies things around, and does not use references. And the string() reallocates each time plus operator is called. The code has therefore poor performance compared to well optimized analogical C code.
Does C++0x provide tools to solve the problem and maybe others? | Yes C++ solves the problem through something called *move semantics*.
Basically it allows for one object to take on the internal representation of another object if that object is a temporary. Instead of copying every byte in the string via a copy-constructor, for example, you can often just allow the destination string to take on the internal representation of the source string. This is allowed only when the source is an r-value.
This is done through the introduction of a *move constructor*. Its a constructor where you know that the src object is a temporary and is going away. Therefore it is acceptable for the destination to take on the internal representation of the src object.
The same is true for *move assignment operators*.
To distinguish a copy constructor from a move constructor, the language has introduced *rvalue references*. A class defines its move constructor to take an *rvalue reference* which will only be bound to rvalues (temporaries). So my class would define something along the lines of:
```
class CMyString
{
private:
char* rawStr;
public:
// move constructor bound to rvalues
CMyString(CMyString&& srcStr)
{
rawStr = srcStr.rawStr
srcStr.rawStr = NULL;
}
// move assignment operator
CMyString& operator=(CMyString&& srcStr)
{
if(rawStr != srcStr.rawStr) // protect against self assignment
{
delete[] rawStr;
rawStr = srcStr.rawStr
srcStr.rawStr = NULL;
}
return *this;
}
~CMyString()
{
delete [] rawStr;
}
}
```
[Here](http://blogs.msdn.com/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx) is a very good and detailed article on move semantics and the syntax that allows you to do this. | One performance-boost will be generalized constant expressions,which is introduced by the keyword constexpr.
```
constexpr int returnSomething() {return 40;}
int avalue[returnSomething() + 2];
```
This is not legal C++ code, because returnSomething()+2 is not a constant expression.
But by using the constexpr keyword, C++0x can tell the compiler that the expression is a compile-time constant. | C++0x performance improvements | [
"",
"c++",
"optimization",
"stl",
"c++11",
"unique-ptr",
""
] |
If you have [DOMNode](https://www.php.net/manual/en/class.domnode.php) in PHP, how can you get the outer xml (i.e. the all of the XML that is inside this element plus the element itself)?
For example, lets say this is the structure
```
<car>
<tire>Michelin</tire>
<seats>Leather</seats>
<type>
<color>red</color>
<make>Audi</make>
</type>
</car>
```
And I have a pointer to the <type> node... I want to get back
```
<type>
<color>red</color>
<make>Audi</make>
</type>
```
If I just ask for the text, I get back "redAudi". | You need a DOMDocument:
```
// If you don't have a document already:
$doc = new DOMDocument('1.0', 'UTF-8');
echo $doc->saveXML($node); // where $node is your DOMNode
```
Check DOMDocument::saveXML in the docs for more info.
When you pass a DOMNode to saveXML() you get back only the contents of that node not the whole document. | After an hour spent, I came up with this (it seems the best solution)
```
$node->ownerDocument->saveXml($node);
``` | In PHP, how can I get the Outer XML from a DOMNode? | [
"",
"php",
"xml",
""
] |
I am trying to make use of JQuery and Fancybox. This is how it should be used: <http://fancy.klade.lv/howto>
However, I can not generate many ids for "a href" and I do not want to make many instances of fancybox ready. So I want to be able to use one fancy box instance for many hyperlinks that do the same thing.
Whenever any of these links are clicked, the fancybox should popup for it. I thought I would use the onclick attribute for a "`<a href`" tag or any other tags, I can chnage this but how do I use the fancybox? I tried this but nothing came up:
```
<a href="#not-working" onclick="fancybox(hideOnContentClick);">Not Working?</a>
```
Thanks for any help | Don't do it that way. If you can't generate unique IDs (or simply don't want to) you should be doing it with CSS classes instead:
```
<a href="image.jpg" class="fancy"><img src="image_thumbnail.jpg"></a>
```
with:
```
$(function() {
$("a.fancy").fancybox({
'zoomSpeedIn': 300,
'zoomSpeedOut': 300,
'overlayShow': false
});
});
```
(from their usage page). | This demonstrates how to use fancybox (1.3.4) without requiring the `<a href>` link element by calling fancybox directly.
**Inline:**
```
<div id="menuitem" class="menuitems"></div>
<div style="display:none;">
<div id="dialogContent">
</div>
</div>
$('.menuitems').click(function() {
$.fancybox({
type: 'inline',
content: '#dialogContent'
});
});
```
**Iframe**:
```
<div id="menuitem" class="menuitems"></div>
$('.menuitems').click(function () {
$.fancybox({
type: 'iframe',
href: 'http://www.abc123.com'
});
});
``` | How can I use fancybox using onclick? | [
"",
"javascript",
"jquery",
"fancybox",
""
] |
Basically, I've got a bunch of music files yoinked from my brother's iPod that retain their metadata but have those absolutely horrendous four character names the iPod seems to like storing them under. I figured I'd write a nice, quick script to just rename them as I wished, but I'm curious about any good libraries for reading ID3 metadata. I'd prefer either Perl or Python. I'm comfortable with Perl since I use it at work, whereas Python I need more practice in and it'll make my Python evangelist friends happy.
Anyway, shortened version: Can you name a good library/module for either Python or Perl that will allow me to easily extract ID3 metadata from a pile of mp3s? | [MP3::Tag](http://search.cpan.org/~ilyaz/MP3-Tag-1.11/lib/MP3/Tag.pm) is a also great. Again, if you are looking for a Perl module, head over to search.cpan.org first.
```
use MP3::Tag;
$mp3 = MP3::Tag->new($filename);
# get some information about the file in the easiest way
($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
# Or:
$comment = $mp3->comment();
$dedicated_to
= $mp3->select_id3v2_frame_by_descr('COMM(fre,fra,eng,#0)[dedicated to]');
$mp3->title_set('New title'); # Edit in-memory copy
$mp3->select_id3v2_frame_by_descr('TALB', 'New album name'); # Edit in memory
$mp3->select_id3v2_frame_by_descr('RBUF', $n1, $n2, $n3); # Edit in memory
$mp3->update_tags(year => 1866); # Edit in-memory, and commit to file
$mp3->update_tags(); # Commit to file
``` | [CPAN Search](http://www.metacpan.org/) turns up several Perl modules when you [search for ID3](http://search.cpan.org/search?query=ID3&mode=all). The answer to almost any Perl question that starts with "Is there a library..." is to check CPAN.
I tend to like [MP3::Tag](http://www.metacpan.org/module/MP3::Tag/), but old people like me tend to find something suitable and ignore all advances in technology until we are forced to change. | Is there a Perl or Python library for ID3 metadata? | [
"",
"python",
"perl",
"id3",
""
] |
I was wondering if it is possible to have a modalpopup show up on page load, saying that the page is loading. I have a page that gets a lot of data from an external source which means it takes a bit before any of the controls are actually filled.
I would like to have a popup or something similar that tells the user the page is loading.
I tried this:
```
<ajax:ModalPopupExtender ID="mpeLoader" runat="server" TargetControlID="btnLoader"
PopupControlID="pnlLoading" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlLoading" runat="server" Width="100px" Style="display: none;">
<div class="detailspopup">
<table>
<tr>
<td><asp:Image ID="imgLoader" runat="server" ImageUrl="~/App_Themes/Main/img/loading.gif" /></td>
</tr>
<tr>
<td>Loading...</td>
</tr>
</table>
</div>
</asp:Panel>
```
with a dummy button btnLoader to allow me to access the show and hide from code behind. I've been toying with the .show method in the page lifecycle but I can't seem to find a way to have the poopup show when the page is loading (and disappear when loading is done). This would also be needed upon filtering the data, thus getting new data based on filter data. | Hard to say what the best solution is without more information, but one possible way to go is to make the first page just act as a "loader" containing the dialog and some javascript that will load the actual page with ajax.
Like I wrote before it depends very much on what you are trying to accomplish :-) !
But one way to do it with jQuery, if the page you are trying to load is very simple like a list without any state / postback controls is to create a "Loader"-page like the code belov and use the **UrlToLoad** query param for what page to load dynamically.
```
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
$("form").load("<%= this.Request["UrlToLoad"] %> form");
});
</script>
</head>
<body>
<form runat="server">
Loading...
</form>
</body>
``` | Have you considered using jQuery? There are some excellent modal dialog plugins available. I've used Eric Martin's [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/) extensively in the past, and have been very happy with it. It has hooks for callbacks both before and after displaying the dialog, so you could perform any checks you need to using functions.
Using the jQuery route - you could have a div that surrounds all the content that is still loading, and have is dimmed out/disabled with a modal dialog showing your 'page loading' message. Then you could make use of the [$document.ready()](http://www.learningjquery.com/2006/09/introducing-document-ready) functionality in jQuery to determine when the page is done loading. At this point, you could remove the dialog and fade the page in. | ASP.net Page Loading popup | [
"",
"c#",
"asp.net",
"ajax",
""
] |
My initial research has come up empty and I am not sure if this is possible. I am looking for a solution using straight up javascript. I cannot use jQuery due to constraints of the device. Basically, I want to attach an event for when an element is removed and provide a function to execute.
**[EDIT]**
We do the DOM manipulation via a function call. Right now, we currently don't traverse down the whole tree to remove every single element. We only remove the parent for instance. I was hoping to provide a shortcut by attaching to an event, but I guess I will have to go the long way around and provide the additional logic in the function. The reason I need this, is because we need to be able to run cleanup operations on the DOM when specific elements are removed.
Right now the priority is only Opera support, but I would like to accomplish a cross browser solution. | If you're interested in cross-browser support, "on element removal" isn't [an HTML 4 event](http://www.w3schools.com/jsref/jsref_events.asp), so I think you might be out of luck here. However, I think you'd have some luck if you adopted an alternate strategy: since you're doing the removing, **constrain the ways in which the element can be removed**. Then simply invoke the callback there instead of in an event handler. | You have something called DOM mutation events defined:
<http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents>
Currently this only works in Firefox, not on Internet Explorer. | Is there a way to be notified by the DOM when an element is removed? | [
"",
"javascript",
""
] |
i have a list of articles, and each article has one or more votes in a collection.
It's a entity framework collection, but i don't think that makes a lot of difference for the problem.
Navigating goes like this:
Article.Votes, where Votes is a collection of vote objects.
What i'm looking for is the Linq statement how i can find the top 5 articles with most votes.
So 1 articles has 100 votes (vote objects in the Votes collection), 3 have 90, 1 have 88, 4 have 78, etc, then i want to select the ones with 100, 90 and 88.
The article collection, btw, is not sorted on the number of votes.
Regards,
Michel | ```
var articles = GetArticleList();
var topArticles = articles.OrderByDescending(a => a.Votes.Count).Take(5);
```
You need the descending clause so you get the highest voted articles first. | ```
var top5 = (from a in articles
orderby a.Votes.Count descending
select a).Take(5);
``` | Linq: get articles with top vote count | [
"",
"c#",
"linq",
""
] |
Can I have a method which takes arguments that are denoted with the same names as the members of the holding class? I tried to use this:
```
class Foo {
public:
int x, y;
void set_values(int x, int y)
{
x = x;
y = y;
};
};
```
... but it doesn't seem to work.
Is there any way of accessing the the instance the namespace of which I'm working in, similar to JavaScript's `this` or Python's `self`? | It's generally a good idea to avoid this kind of confusion by using a naming convention for member variables. For example, camelCaseWithUnderScore\_ is quite common. That way you would end up with `x_ = x;`, which is still a bit funny to read out loud, but is fairly unambiguous on the screen.
If you *absolutely need* to have the variables and arguments called the same, then you can use the `this` pointer to be specific:
```
class Foo {
public:
int x, y;
void set_values(int x, int y)
{
this->x = x;
this->y = y;
}
};
```
By the way, note the trailing semi-colon on the class definition -- that is needed to compile successfully. | Yes, you should be able to write this using the "this" keyword (which is a pointer in C++):
```
class Foo {
public:
int x, y;
void set_values(int x, int y)
{
this->x = x;
this->y = y;
}
}
``` | Members vs method arguments access in C++ | [
"",
"c++",
"class",
"methods",
"arguments",
"instance",
""
] |
I am mapping my database tables to my java objects. Generally I name my tables in the plural form in that a table holding books information is called BOOKS. The java object represents however one book and should be called Book. Similarly for AUTHORS/Author etc.
On the other hand, its kind of simplistic to give the same to the domain object and the table.
Is there some kind of naming convention that people follow? I guess this applies to applications in general and not just while doing O/R mapping. | Your initial thoughts are spot on.
Objects should be singular, as each object is individual.
Tables should be plural, as the table contains all.
Check out the naming conventions built into Ruby on Rails, they're relevant. | We use singular for table names and for OM classes. It makes more sense, to me, to say
> person.last\_name
than
> people.last\_name,
whether I'm writing SQL or Java (where, of course, it would be person.lastName, but you get the point). | naming conventions when doing O/R mapping | [
"",
"java",
"database",
"jpa",
"orm",
""
] |
```
typedef map<wstring , IWString> REVERSETAG_CACHE ;
REVERSETAG_CACHE::iterator revrsetagcacheiter;
.
.
.
wstring strCurTag;
strCurTag = revrsetagcacheiter->second; //Error C2593
```
> Error C2593: Operator = is ambiguous
Why does the above assignment give this error? It works in VC6. Does not compile in VC9. | `revrsetagcacheiter->second` is of type `IWString` .
Hence it won't compile. I don't think it will compile in VC6 also.
**I'll try one final time**: Is your BasicString class c\_str() method ? If so try converting it to wstring using `std::wstring str(iter->second.c_str());` | At a guess, VC6 allows more than one user-defined conversion to be applied, while (correctly) VC9 does not. Take a look at [C++ implicit conversions](https://stackoverflow.com/questions/867462/c-implicit-conversions) for discussion of the general problem.
The general solution is to supply the needed conversion yourself, rather than have the compiler try to do it. | Error C2593: Operator = is ambiguous | [
"",
"c++",
"visual-studio-2008",
"porting",
"visual-c++-6",
"wstring",
""
] |
Once a method is marked as deprecated, are there any tools which replace these methods with non-deprecated workarounds ? | Automated tools could only reasonably handle cases where there's a new preferred method or class to use to accomplish exactly the same task. Any case where a method is deprecated because of defective design (think anything dealing with date's in Java) or because a "better" way is now supported (think AWT to Swing or SWT) requires far to much thought to be automated.
In short, no there are no such tools. I doubt there ever will be any in the future as well. | If you would like to do this automatically - *no*.
The tool is called a *programmer*.
---
The reason is that the tools would need to profoundly understand both the deprecation, the 'un-deprecation' , your program and the target programming language.
For instance, `java.util.Date.setMonth` is deprecated in favour of `Calendar.set(Calendar.MONTH, int month)`.
That is a non-trivial change to apply, since it requires replacing object instantiations, method calls, taking into account synchronisation. Actually nightmarish to do automatically. | Java: De-deprecated-ing Tools | [
"",
"java",
"refactoring",
"deprecated",
""
] |
I've got the following objects using AJAX and stored them in an array:
```
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
```
How do I create a function to sort the objects by the `price` property in *ascending* **or** *descending* order using JavaScript only? | Sort homes by price in ascending order:
```
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
```
Or after ES6 version:
```
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
```
Some documentation can be found [here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
For descending order, you may use
```
homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
``` | Here's a more flexible version, which allows you to create
reusable sort functions, and sort by any field.
```
const sort_by = (field, reverse, primer) => {
const key = primer ?
function(x) {
return primer(x[field])
} :
function(x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
return function(a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
//Now you can sort by any field at will...
const homes=[{h_id:"3",city:"Dallas",state:"TX",zip:"75201",price:"162500"},{h_id:"4",city:"Bevery Hills",state:"CA",zip:"90210",price:"319250"},{h_id:"5",city:"New York",state:"NY",zip:"00010",price:"962500"}];
// Sort by price high to low
console.log(homes.sort(sort_by('price', true, parseInt)));
// Sort by city, case-insensitive, A-Z
console.log(homes.sort(sort_by('city', false, (a) => a.toUpperCase()
)));
``` | Sorting an array of objects by property values | [
"",
"javascript",
"arrays",
"sorting",
""
] |
A while back I wrote a little program in Microsoft Visual C# 2008 Express Edition. In it included a file called "ProblemReport.cs" with it's own form and ProblemReport class.
I'm writing a new program and want to reuse this code. (still working in MS Vis C# 2008 express)
In my new program, in the C# Solution Explorer, I right clicked on my project and chose "Add existing item..." I then added ProblemReport.cs, ProblemReport.designer.cs and ProblemReport.resx.
What step(s) am I missing here? When I go back to the main form in my new program, and try to instantiate a new instance of "ProblemReport", I get the error message:
"The type of namespace name 'ProblemReport' could not be found (are you missing a using directive or an assembly reference?)"
Obviously - I'm supposed to do something else to get this to work... just not sure what it is!
-Adeena | Ensure that all your CS files are within the same namespace. Sounds like the imported one(s) aren't living with your new project.
Ensure that:
```
namespace MyProgram //same as the rest of your project
{
public class ProblemReport
{
}
}
```
meanwhile in your other .cs files....
```
namespace MyProgram
{
public class SomeClass
{
public void DoSomething()
{
ProblemReport. //you should get intellisense here.
}
}
}
``` | You might be better off extracting ProblemReport into it's own class library (separate dll) so you only have one copy of the code.
Create a new class library project, copy ProblemReport.cs, ProblemReport.designer.cs and ProblemReport.resx into that and update the namespace as required. Build it and put the dll somewhere central. Then add a reference to this class library from your two programs. | How do I add a cs file to an existing C# project? | [
"",
"c#",
"visual-studio-2008",
"file",
""
] |
Java's `File.renameTo()` is problematic, especially on Windows, it seems.
As the [API documentation](http://java.sun.com/javase/6/docs/api/java/io/File.html#renameTo%28java.io.File%29) says,
> Many aspects of the behavior of this
> method are inherently
> platform-dependent: The rename
> operation might not be able to move a
> file from one filesystem to another,
> it might not be atomic, and it might
> not succeed if a file with the
> destination abstract pathname already
> exists. The return value should always
> be checked to make sure that the
> rename operation was successful.
In my case, as part of an upgrade procedure, I need to move (rename) a directory that may contain gigabytes of data (lots of subdirectories and files of varying sizes). The move is always done within the same partition/drive, so there's no real need to physically move all the files on disk.
There *shouldn't* be any file locks to the contents of the dir to be moved, but still, quite often, renameTo() fails to do its job and returns false. (I'm just guessing that perhaps some file locks expire somewhat arbitrarily on Windows.)
Currently I have a fallback method that uses copying & deleting, but this sucks because it may take **a lot** of time, depending on the size of the folder. I'm also considering simply documenting the fact that the user can move the folder manually to avoid waiting for hours, potentially. But the Right Way would obviously be something automatic and quick.
So my question is, **do you know an alternative, reliable approach to do a quick move/rename with Java on Windows**, either with plain JDK or some external library. Or if you know an *easy* way to detect and release any file locks for a given folder and *all of its contents* (possibly thousands of individual files), that would be fine too.
---
**Edit**: In this particular case, it seems we got away using just `renameTo()` by taking a few more things into account; see [this answer](https://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows/1006489#1006489). | See also the [`Files.move()`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...)) method in JDK 7.
An example:
```
String fileName = "MyFile.txt";
try {
Files.move(new File(fileName).toPath(), new File(fileName).toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Logger.getLogger(SomeClass.class.getName()).log(Level.SEVERE, null, ex);
}
``` | For what it's worth, some further notions:
1. On Windows, `renameTo()` seems to fail if the target directory exists, even if it's empty. This surprised me, as I had tried on Linux, where `renameTo()` succeeded if target existed, as long as it was empty.
(Obviously I shouldn't have assumed this kind of thing works the same across platforms; this is exactly what the Javadoc warns about.)
2. If you suspect there may be some lingering file locks, waiting a little before the move/rename *might* help. (In one point in our installer/upgrader we added a "sleep" action and an indeterminate progress bar for some 10 seconds, because there might be a service hanging on to some files). Perhaps even do a simple retry mechanism that tries `renameTo()`, and then waits for a period (which maybe increases gradually), until the operation succeeds or some timeout is reached.
In my case, most problems seem to have been solved by taking both of the above into account, so we won't need to do a native kernel call, or some such thing, after all. | Reliable File.renameTo() alternative on Windows? | [
"",
"java",
"windows",
"file",
"file-io",
""
] |
I don't believe this: Just built a very simple form with one combobox, when user select one item, the label will display the selection. Here is my code:
```
<Window x:Class="WpfApplication8.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ComboBox Height="23" Margin="139,0,19,14" Name="comboBox1" Text="Worker"
VerticalAlignment="Bottom" IsReadOnly="True" SelectionChanged="comboBox1_SelectionChanged">
<ComboBoxItem Name="None" Selector.IsSelected="True">Select Target</ComboBoxItem>
<ComboBoxItem Name="Alice">Alice</ComboBoxItem>
<ComboBoxItem Name="Bob">Bob</ComboBoxItem>
<ComboBoxItem Name="Chris">Chris</ComboBoxItem>
<ComboBoxItem Name="Dan">Dan</ComboBoxItem>
</ComboBox>
<Label Height="28" Margin="15,0,0,14" Name="label1"
VerticalAlignment="Bottom" Content="Assign to: " HorizontalAlignment="Left" Width="120"></Label>
</Grid>
</Window>
```
Code behind:
```
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
label1.Content = comboBox1.SelectedValue;
}
``` | Another way also, if you did not want to check if the label is null, is add the selection change handler once the window is loaded, as it would fire one before the label has loaded:
Code Behind:
```
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.SelectionChanged+=new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}
protected void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
label1.Content = ((ComboBoxItem)comboBox1.Items[comboBox1.SelectedIndex]).Content;
}
```
Markup:
```
<Grid>
<ComboBox Height="23" Margin="139,0,19,14" Name="comboBox1" Text="Worker"
VerticalAlignment="Bottom" IsReadOnly="True">
<ComboBoxItem Name="None" Selector.IsSelected="True">Select Target</ComboBoxItem>
<ComboBoxItem Name="Alice">Alice</ComboBoxItem>
<ComboBoxItem Name="Bob">Bob</ComboBoxItem>
<ComboBoxItem Name="Chris">Chris</ComboBoxItem>
<ComboBoxItem Name="Dan">Dan</ComboBoxItem>
</ComboBox>
<Label Height="28" Margin="15,0,0,14" Name="label1"
VerticalAlignment="Bottom" Content="Assign to: " HorizontalAlignment="Left" Width="120"></Label>
</Grid>
```
Andrew | Here's a simplified version all in xaml:
```
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<ComboBox Name="comboBox1" Text="Worker" IsSynchronizedWithCurrentItem="True"
VerticalAlignment="Bottom" IsReadOnly="True" >
<ComboBoxItem Name="None" Selector.IsSelected="True">Select Target</ComboBoxItem>
<ComboBoxItem Name="Alice">Alice</ComboBoxItem>
<ComboBoxItem Name="Bob">Bob</ComboBoxItem>
<ComboBoxItem Name="Chris">Chris</ComboBoxItem>
<ComboBoxItem Name="Dan">Dan</ComboBoxItem>
</ComboBox>
<Label Name="label1" DataContext="{Binding ElementName=comboBox1, Path=SelectedItem}"
VerticalAlignment="Bottom" Content="{Binding Name}" HorizontalAlignment="Left"></Label>
</StackPanel>
</Page>
``` | WPF: XamlParserException for a very simple form? | [
"",
"c#",
".net",
"wpf",
""
] |
**Update 5:** I've downloaded the latest Spring ToolsSuite IDE based on the latest Eclipse. When I import my project as a Maven project, Eclipse/STS appears to use the Maven goals for building my project. This means AspectJ finally works correctly in Eclipse.
**Update 4:** I have ended up just using Maven + AspectJ plugin for compile-time weaving, effectively bypassing Eclipse's mechanism.
**Update 3:** It seems AspectJ's Eclipse plug-in breaks Eclipse's ability to correctly Publish to Tomcat. Only by removing the AspectJ capability on a project can I get it to properly Publish again. Very annoying.
**Update 2:** I have this now working in Eclipse. It makes me very uncomfortable to say this, but I have no idea how I got it working from either Eclipse or Maven builds. It appears to be a compile issue rather than a run-time issue.
**Update 1:** It appears I've gotten this to work via Maven builds, but I have no idea how. Eclipse still doesn't work. The only thing I changed in the *pom.xml* was adding these (insignificant?) configuration parameters:
```
<source>1.6</source>
<complianceLevel>1.6</complianceLevel>
<verbose>true</verbose>
<showWeaveInfo>true</showWeaveInfo>
<outxml>true</outxml>
```
I'm actually worried that I have a repeat of [this problem](https://stackoverflow.com/questions/828747/why-does-springs-configurable-sometimes-work-and-sometimes-not), where everything works inconsistently. I will keep this question updated as I learn more.
With regards to Eclipse, I made some progress by taking the binary aspects I wish to weave - in this case *spring-aspects.jar* - and copying it out of my classpath. I then add this now external jar to my **Aspect Path**. After doing this, Eclipse properly shows me AspectJ markers in my code. It's annoying that I can't just leave **spring-aspects.jar** in my **Java Build Path** which is maintained by Maven for me via the Maven plug-in. For some reason, however, the AspectJ plug-in doesn't see the binary aspects unless they're explicitly added to the **Aspect Path**.
---
**Original Post:** @Configurable is a Spring annotation that allows dependencies to be injected into objects instantiated external to Spring (for example, by Hibernate or some Factory class).
I was using this annotation previously with load-time weaving and it *mostly* worked. Occasionally I would boot up and nothing would get injected. This issue spawned [this StackOverflow question](https://stackoverflow.com/questions/828747/why-does-springs-configurable-sometimes-work-and-sometimes-not). There weren't many answers, but most suggested that I try compile-time weaving instead due to greater reliability.
I installed the AspectJ plug-in for Eclipse and Maven. Both of these produce what appears to be properly compiled classes. I've opened up one of the classes in a text editor before AspectJ compilation and found no references to AspectJ. I opened it up after AspectJ compilation and both Eclipse and Maven generated versions have a reference to **org.aspectj.weaver.MethodDeclarationLineNumber**. This is why I assume it's being properly compiled. The problem is that once deployed, no dependencies get injected.
My Spring *applicationContext.xml* does include the following:
```
<context:spring-configured />
<context:component-scan base-package="com.myapp" />
```
Is the above all that's needed for classes marked @Configurable to have DI done? During the conversion from load-time weaving to compile-time weaving, I removed *META-INF/aop.xml*, *<context:load-time-weaver />* from my *applicationContext.xml*, and Spring's Tomcat weaver from my *context.xml*.
How can I investigate this problem further? What are possible causes? | It works for us on maven using compile time weaving, try adding the following plugins:
```
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerVersion>1.6</compilerVersion>
<fork>true</fork>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<configuration>
<source>1.6</source>
<target>1.6</target>
<verbose>false</verbose>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<configuration>
<source>1.6</source>
<target>1.6</target>
<verbose>false</verbose>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
</plugin>
```
Its done as two separate execution steps to allow you to add different aspect libraries for unit testing and compilation.
You'll also need the following dependency added for the spring-aspects library:
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<scope>compile</scope>
</dependency>
``` | I successfully configured load-time weaving in my app, if this is an alternative for you.
My environment:
* JDK-1.6
* Spring-2.5.6
* JPA with eclipselink-1.1.0
Configuration details:
Spring XML configuration:
```
<context:annotation-config/>
<context:spring-configured/>
<context:load-time-weaver/>
<bean id="baseEntity" class="package.name.BaseEntity" scope="prototype">
<property name="historyHandler" ref="historyHandler" />
</bean>
<bean id="historyHandler" class="package.name.HistoryJpaHandler" scope="prototype">
<property name="historyDao" ref="historyDao" />
</bean>
<bean id="historyDao" class="package.name.HistoryJpaDao">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
```
Spring annotations
```
@Configurable("baseEntity")
public abstract class BaseEntity
@Configurable("historyHandler")
public class HistoryJpaHandler extends SessionEventAdapter implements HistoryHandler
```
Java VM Parameter
```
<JAVA_HOME>/bin/java -javaagent:/full/path/to/spring-agent-2.5.6.jar
```
Instances of historyHandler and baseEntitty are created by ecliselink. historyHandler in baseEntitty and historyDao in historyHandler is set by load-timeweaving.
You can set the VM Parameter in Eclipse run configuration or in Tomcats catalina.sh/bat. | Why doesn't AspectJ compile-time weaving of Spring's @Configurable work? | [
"",
"java",
"maven",
"aop",
"spring-aop",
"compile-time-weaving",
""
] |
I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cache, neither of which would make sense for my particular problem.
I thought I could just use a python global or module-level variable for this, but it turns out that those maintain their state between requests in non-obvious ways.
I also don't think memcache makes sense because it's application wide.
I haven't been able to find a good answer for this in google's docs. Maybe that's because it's either a dumb idea or totally obvious, but it seems like it'd be useful and I'm stumped.
Anybody have any ideas? | What I usually do is just create a new attribute on the request object. However, I use django with AppEngine, so I'm not sure if there is anything different about the appengine webapp framework.
```
def view_handler(request):
if hasattr(request, 'mycache'):
request.mycache['counter'] += 1
else:
request.mycache = {'counter':1,}
return HttpResponse("counter="+str(request.mycache["counter"]))
``` | If you're using the 'webapp' framework included with App Engine (or, actually, most other WSGI-baesd frameworks), a new RequestHandler is instantiated for each request. Thus, you can use class variables on your handler class to store per-request data. | How can I create a variable that is scoped to a single request in app engine? | [
"",
"python",
"google-app-engine",
""
] |
My string looks like so
> February 2009
>
> bla bla
>
> March 2009
>
> doo daa bla lbla
>
> Septemer 2009
So I wrote this regex to split it up into months (which is what I want to do first, I think)
```
$regex = '/(.*)\s(\d){4}/i';
```
This matches them perfectly, except it throws away the actual string they were split on .. i.e. I want that information (as in February 2009, March 2009 etc)
I've tried mucking around with the `preg_split()` flags, but could not get what I wanted.
Should I be using a different approach? Is there an easy to split text via a regex but keep the text that was actually there?
Come to think of it, I could probably use `preg\_match\_all()' here... I hope I just didn't answer my own question in the answer - I'm going to post anyway to see what the community thinks.
Thanks | Put the splitting string into its own capture group. So given your example,
```
$regex = '/(.*)\s(\d){4}/';
```
with a few modifications becomes:
```
$regex = '/(.+?)(\s)(\d{4})/';
```
If your matches array is called "$matches", $matches[0] will contain the whole match, $matches[1] the month, $matches[2] the splitting string, and $matches[3] the year. | preg\_split's 4th option is the flags:
<http://www.php.net/preg-split>
> `PREG_SPLIT_DELIM_CAPTURE` If this
> flag is set, parenthesized expression
> in the delimiter pattern will be
> captured and returned as well.
```
$a = preg_split('/(.*\s\d{4})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($a);
```
prints
```
Array
(
[0] =>
[1] => February 2009
[2] =>
bla bla
[3] => March 2009
[4] =>
doo daa bla lbla
[5] => Septemer 2009
[6] =>
)
```
So that's pretty close. | Can you split a string in PHP with a regex, but easily get the matched string which split the string? | [
"",
"php",
"regex",
""
] |
I'm looking for solution of C++ class design problem. What I'm trying to achieve is having static method method in base class, which would return instances of objects of descendant types. The point is, some of them should be singletons. I'm writing it in VCL so there is possibility of using `__properties`, but I'd prefer pure C++ solutions.
```
class Base {
private:
static Base *Instance;
public:
static Base *New(void);
virtual bool isSingleton(void) = 0;
}
Base::Instance = NULL;
class First : public Base { // singleton descendant
public:
bool isSingleton(void) { return true; }
}
class Second : public Base { // normal descendant
public:
bool isSingleton(void) { return false; }
}
Base *Base::New(void) {
if (isSingleton())
if (Instance != NULL)
return Instance = new /* descendant constructor */;
else
return Instance;
else
return new /* descendant constructor */;
}
```
Arising problems:
* how to declare static variable `Instance`, so it would be static in descendant classes
* how to call descendant constructors in base class
I reckon it might be impossible to overcome these problems the way I planned it. If so, I'd like some advice on how to solve it in any other way.
---
**Edit**: some minor changes in code. I have missed few pointer marks in it. | Just to check we have our terminologies in synch - in my book, a factory class is a class instances of which can create instances of some other class or classes. The choice of which type of instance to create is based on the inputs the factory receives, or at least on something it can inspect. Heres's a very simple factory:
```
class A { ~virtual A() {} };
class B : public A {};
class C : public A {};
class AFactory {
public:
A * Make( char c ) {
if ( c == 'B' ) {
return new B;
}
else if ( c == 'C' ) {
return new C;
}
else {
throw "bad type";
}
}
};
```
If I were you I would start again, bearing this example and the following in mind:
* factorioes do not have to be singletons
* factories do not have to be static members
* factories do not have to be members of the base class for the hierarchies they create
* factory methods normally return a dynamically created object
* factory methods normally return a pointer
* factory methods need a way of deciding which class to create an instance of
I don't see why your factory needs reflection, which C++ does not in any case support in a meaningful way. | Basing this on the answer by @Shakedown, I'll make `Base` be templated on the actual type, using the [CRTP](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern):
```
template <class T>
class Base
{
public:
static std::auto_ptr<Base<T> > construct()
{
return new T();
}
};
class First : public Base<First>
{
};
class Second : public Base<Second>
{
};
```
This is nice because `construct` is now once again a static member. You would call it like:
```
std::auto_ptr<First> first(First::construct());
std::auto_ptr<Second> second(Second::construct());
// do something with first and second...
``` | How to declare factory-like method in base class? | [
"",
"c++",
"oop",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.