Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Assume we have legacy classes, that can't be modified:
```
class Foo
{
public void Calculate(int a) { }
}
class Bar
{
public void Compute(int a) {}
}
```
I want to write a helper with such signature:
```
void Calc(object obj, int a);
```
Notice, that the first argument is of type 'object'. The test code should be some like this:
```
ExampleX.Calc((object)new Foo(), 0);
ExampleX.Calc((object)new Bar(), 0);
```
The question is, what implementation you can imagine in addition to these:
```
// Using If/then
class Example1
{
public static void Calc(object obj, int a)
{
if (obj is Foo)
((Foo)obj).Calculate(a);
else if (obj is Bar)
((Bar)obj).Compute(a);
}
}
// Using reflection
class Example2
{
private static Dictionary<Type, MethodInfo> _methods = new Dictionary<Type, MethodInfo>();
static Example2()
{
_methods.Add(typeof(Foo), typeof(Foo).GetMethod("Calculate"));
_methods.Add(typeof(Bar), typeof(Bar).GetMethod("Compute"));
}
public static void Calc(object obj, int a)
{
_methods[obj.GetType()].Invoke(obj, new object[] { a });
}
}
// Using delegates
class Example3
{
private delegate void CalcDelegate(object obj, int a);
private static Dictionary<Type, CalcDelegate> _methods = new Dictionary<Type, CalcDelegate>();
static Example3()
{
_methods.Add(typeof(Foo), (o, a) => ((Foo)o).Calculate(a));
_methods.Add(typeof(Bar), (o, a) => ((Bar)o).Compute(a));
}
public static void Calc(object obj, int a)
{
_methods[obj.GetType()](obj, a);
}
}
// Using Reflection + overloaded methods
class Example4
{
private delegate void CalcDelegate(object obj, int a);
public static void Calc(object obj, int a)
{
Type[] types = new Type[] {
obj.GetType(), typeof(int)
};
typeof(Example4).GetMethod("Calc", types).Invoke(null, new object[] { obj, a });
}
public static void Calc(Foo obj, int a)
{
obj.Calculate(a);
}
public static void Calc(Bar obj, int a)
{
obj.Compute(a);
}
}
```
Thanks! | I would go for example 1, because its the simplest one and most obvious.
I would use Example 2 only if you expect new types of objects with one of these two methods, and example 3 only if you have a lot (tens if not hundreds) of objects and performance starts being an issue.
Edit: Or extension methods if you are .Net 3 | Use extension methods to essentially add a new function to an existing type.
<http://msdn.microsoft.com/en-us/library/bb383977.aspx> | C#. Add polymorphism for legacy code | [
"",
"c#",
"polymorphism",
"legacy-code",
"duck-typing",
""
] |
I'm struggling to get my head around LINQ and have come to the conclusion that searching through dozens of examples until I find one that is near to my own application in C# is not teaching me how to fish.
So back to the docs where I immediately hit a brick wall.
Can someone please help me decipher the Enumerable.Select method as presented here on msdn
<http://msdn.microsoft.com/en-us/library/bb548891.aspx> and given as a tip by Intellisense?
**Enumerable.Select(TSource, TResult) Method (IEnumerable(TSource>), Func(TSource, TResult))**
Here is the same line broken down with line numbers if it helps to refer:
1. Enumerable.Select
2. (TSource, TResult)
3. Method
4. (IEnumerable(TSource>),
5. Func
6. (TSource, TResult)) | It might help to look at the definition of this method in C#, from the MSDN article you refer to:
```
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
```
The `<`angle brackets`>` denote the type parameters for this generic method, and we can start to explore the purpose of the method simply by looking at what the type parameters are doing.
We begin by looking at the name of the generic method:
```
Select<TSource, TResult>
```
This tells us that the method called `Select` deals with two different types:
* The type `TSource`; and
* The type `TResult`
Let's look at the parameters:
1. The first parameter is `IEnumerable<TSource> source` — a source, providing a `TSource` enumeration.
2. The second parameter is `Func<TSource, TResult> selector` — a selector function that takes a `TSource` and turns it into a `TResult`. (This can be verified by exploring the definition of `Func`)
Then we look at its return value:
```
IEnumerable<TResult>
```
We now know this method will return a `TResult` enumeration.
**To summarise**, we have a function that takes an enumeration of `TSource`, and a selector function that takes individual `TSource` items and returns `TResult` items, and then the whole select function returns an enumeration of `TResult`.
**An example:**
To put this into concrete terms, lets say that `TSource` is of type `Person` (a class representing a person, with a name, age, gender, etc), and `TResult` is of type `String` (representing the person's name). We're going to give the `Select` function a list of `Person`s, and a function that, given a `Person` will select just their name. As the output of calling this `Select` function, we will get a list of `String`s containing just the names of the people.
**Aside:**
The last piece of the puzzle from the original method signature, at the top, is the `this` keyword before the first parameter. This is part of the syntax for defining [Extension Methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx), and all it essentially means is that instead of calling the static Select method (passing in your source enumeration, and selector function) you can just invoke the Select method directly on your enumeration, just as if it had a `Select` method (and pass in only one parameter — the selector function).
I hope this makes it clearer for you? | The way to think of Select is as mapping each element of a sequence. Hence:
`Enumerable.Select<TSource, TResult>`: the Select method is parameterised by its source and result types (the type of thing you are mapping and the type you are mapping it to)
`IEnumerable<TSource>`: the sequence of things to map
`Func<TSource, TResult>`: the mapping function, that will be applied to each element of the source sequence
The result being an `IEnumerable<TResult>`, a sequence of mapping results.
For example, you could imagine (as a trivial example) mapping a sequence of integers to the string representations:
```
IEnumerable<string> strings = ints.Select(i => i.ToString());
```
Here ints is the `IEnumerable<TSource>` (`IEnumerable<int>`) and `i => i.ToString()` is the `Func<TSource, TResult>` (`Func<int, string>`). | How do I decipher the Select method docs on MSDN? | [
"",
"c#",
".net",
"linq",
""
] |
what is the correct syntax to create a new instance of the object as opposed to a pointer to the original? Here is my example:
```
var oItem = { element: null, colIndex: 0 };
var oInputs = { Qty: oItem, Tare: oItem, Rate: oItem, Total: oItem };
for (var oTitle in oInputs) {
oInputs[oTitle].element = ...
```
when I set the value of `oInputs[oTitle].element` for any `oTitle` it sets the value of them all. I know that javascript passes objects by reference, so I am assuming it's because they are all referring to the same object. I tried this but it is obviously wrong.
```
var oInputs = { Qty: new oItem, Tare: new oItem, Rate: new oItem, Total: new oItem };
```
Thanks in advance. | Do the following:
```
function OItem() {
this.colIndex = 0;
}
var oInputs = { Qty: new OItem(), Tare: new OItem(), Rate: new OItem(), Total: new OItem() };
```
and then set your properties:
```
for (var oTitle in oInputs) {
oInputs[oTitle].element = ...
``` | This is another way to create a constructor:
```
function Item(element,colIndex){
if (this instanceof Item){
this.element = element || null;
this.colIndex = colIndex || 0;
} else {
return new Item(element,colIndex);
}
}
```
Now you don't need the new operator for a new instance of Item.
```
var oInputs = { Qty: Item(),
Tare: Item(),
Rate: Item(),
Total: Item() };
``` | Javascript new object reference | [
"",
"javascript",
""
] |
How to add the total page number on every page with iText? | 1. Process the output from a `PdfWriter` to a `bytestream` first with a dummy page count.
2. Create a `PdfReader` from that `bytestream`, calling `PdfReader.getNumberOfPages` to get the actual page count.
3. Recreate the PDF output, knowing what the page count will be, changing the footer accordingly.
It's messy, but there's no easy way to know the page count without a two-pass approach. See the [example code](http://developers.itextpdf.com/examples/columntext-examples-itext5/adding-page-numbers-existing-pdf) for details on manipulating PDFs. | You can create a class that inherits from `PdfPageEventHelper`
then override theses two functions like this :
```
Imports System.Collections.Generic
Imports System.Text
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Namespace PDF_EnteteEtPiedDePage
Public Class EnteteEtPiedDePage
Inherits PdfPageEventHelper
' This is the contentbyte object of the writer
Private cb As PdfContentByte
' we will put the final number of pages in a template
Private template As PdfTemplate
' this is the BaseFont we are going to use for the header / footer
Private bf As BaseFont = Nothing
' This keeps track of the creation time
Private PrintTime As DateTime = DateTime.Now
' we override the onOpenDocument method
Public Overrides Sub OnOpenDocument(writer As PdfWriter, document As Document)
Try
PrintTime = DateTime.Now
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
cb = writer.DirectContent
template = cb.CreateTemplate(50, 50)
Catch de As DocumentException
Catch ioe As System.IO.IOException
End Try
End Sub
Public Overrides Sub OnStartPage(writer As PdfWriter, document As Document)
MyBase.OnStartPage(writer, document)
Dim pageSize As Rectangle = document.PageSize
End Sub
Public Overrides Sub OnEndPage(writer As PdfWriter, document As Document)
MyBase.OnEndPage(writer, document)
Dim pageN As Integer = writer.PageNumber
Dim text As [String] = "Page " & pageN & " de "
Dim len As Single = bf.GetWidthPoint(text, 8)
Dim pageSize As Rectangle = document.PageSize
cb.SetRGBColorFill(100, 100, 100)
cb.BeginText()
cb.SetFontAndSize(bf, 8)
cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30))
cb.ShowText(text)
cb.EndText()
cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30))
cb.BeginText()
cb.SetFontAndSize(bf, 8)
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Imprimé le : " & PrintTime.ToShortDateString() & " à " & PrintTime.ToShortTimeString, pageSize.GetRight(40), pageSize.GetBottom(30), 0)
cb.EndText()
End Sub
Public Overrides Sub OnCloseDocument(writer As PdfWriter, document As Document)
MyBase.OnCloseDocument(writer, document)
template.BeginText()
template.SetFontAndSize(bf, 8)
template.SetTextMatrix(0, 0)
template.ShowText("" & Convert.ToString((writer.PageNumber - 1)))
template.EndText()
End Sub
End Class
End Namespace
```
Then after that just set the value of your `pdfwriter PageEvent` like this :
```
Dim PageEventHandler = New EnteteEtPiedDePage()
aPdfWriter.PageEvent = PageEventHandler
``` | How to add total page number on every page with iText? | [
"",
"java",
"itext",
""
] |
Using java, how do you get the amount of free space on a solaris zfs file system?
I have a SunFire x4140 with built-in hdd mounted as /. It also has a connected JBOD with 7.6TB of HDD space, configured as a ZFS file system and mounted as /app.
I use java.io.File.getUsableSpace or java.io.File.getFreeSpace to get the amount of free space on the file system. On / (the on-board) HDD FS it works correctly.
On /app (the zfs partition) File.getFreeSpace, File.getUsableSpace and File.getTotalSpace all return 0 (zero). Does anyone know why? Does java.io.File.getUsableSpace work on ZFS, and if so, how?
The following shows the zfs file system on the machine in question:
> /usr/sbin/zfs list
```
NAME USED AVAIL REFER MOUNTPOINT
internal 196K 98.4G 1K none
internal/logs 18K 98.4G 18K /logs
j4200-1 442G 7.57T 2.44K none
j4200-1/app 442G 7.57T 153M /app
j4200-1/app@first 442G - 442G -
``` | I don't know why, but you may be take a look at [libzfs](https://zfs.dev.java.net/), that wraps zfs command in a nice java API | The df -kP command returns the free space,
but the most universal way is to use
Apache Commons IO
[FileSystemUtils.freeSpaceKb("/volume");](http://commons.apache.org/io/apidocs/org/apache/commons/io/FileSystemUtils.html#freeSpaceKb%28java.lang.String%29)
it utilize df as well as dir for Windows | Using java, how do you get the amount of free space on a solaris zfs file system? | [
"",
"java",
"file-io",
"zfs",
""
] |
Inside a nested foreach, accessing the same variable is returning different values. This happens when the page is reloaded, not on first load.
```
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
(...)
xmlns:c="http://java.sun.com/jstl/core"
xmlns:h="http://java.sun.com/jsf/html">
(...)
<c:forEach items="#{controller.availableTransitions}" var="transition">
<c:forEach items="#{transition.availableTransitions}" var="transitionItem">
<h:outputText value="1_#{transitionItem.name} 2_#{transitionItem.name}" />
3_#{transitionItem.name} 4_#{transitionItem.name}
</c:forEach>
</c:forEach>
</ui:composition>
```
After page reload, transitionItem.Name returns the correct value for 3 and 4, and different values for 1 and 2. Maybe a JSF-JSTL integration problem? | Found a workaround, by getting rid of the inner forEach loop, thus returning a linear list from the controller. | I see that you are using Facelets.
Maybe you can try to replace your `<c:forEach>` by `<ui:repeat>`...
The code will then become:
```
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
(...)
xmlns:c="http://java.sun.com/jstl/core"
xmlns:h="http://java.sun.com/jsf/html">
(...)
<ui:repeat value="#{controller.availableTransitions}" var="transition">
<ui:repeat value="#{transition.availableTransitions}" var="transitionItem">
<h:outputText value="1_#{transitionItem.name} 2_#{transitionItem.name}" />
3_#{transitionItem.name} 4_#{transitionItem.name}
</ui:repeat>
</ui:repeat>
</ui:composition>
``` | JSF JSTL problem with nested forEach | [
"",
"java",
"jsf",
"jstl",
""
] |
In C#, if a class *has all the correct methods/signatures for an Interface*, but **doesn't** explicitly implement it like:
```
class foo : IDoo {}
```
Can the class still be cast as that interface? | No, it's not like Objective-C and some other languages. You should explicitly declare interface implementation. | **Duck Typing**
What you are alluding to is referred to as "[duck-typing](http://en.wikipedia.org/wiki/Duck_Typing)" (named after the idiom "if it looks like a duck, and quacks like a duck, then it must be a duck").
With duck-typing an interface implementation is implicit once you have implemented the relevant members (just as you describe) however .NET does not currently have any broad support for this.
With the emergent dynamic language features planned for the future, I wouldn't be surprised if this were supported natively by the runtime in the near future.
In the mean time, you can synthesise duck-typing via reflection, with [a library such as this](http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx), which would allow you to do a duck-typed cast like this: `IDoo myDoo = DuckTyping.Cast<IDoo>(myFoo)`
**Some Trivia**
Interestingly, there is one small place where duck-typing is in use in C# today — the `foreach` operator. Krzysztof Cwalina [states](http://blogs.msdn.com/kcwalina/archive/2007/07/18/DuckNotation.aspx) that in order to be enumerable by the `foreach` operator, a class must:
> Provide a public method GetEnumerator
> that takes no parameters and returns a
> type that has two members: a) a method
> MoveMext that takes no parameters and
> return a Boolean, and b) a property
> Current with a getter that returns an
> Object.
Notice that he makes no mention of `IEnumerable` nor `IEnumerator`. Although it is common to implement these interfaces when creating an enumerable class, if you were to drop the interfaces but leave the implementation, your class would still be enumerable by `foreach`. Voila! Duck-typing! ([Example code here](http://www.danielfortunov.com/software/%24daniel_fortunovs_adventures_in_software_development/2009/07/28/duck_typing).) | C# and Interfaces - Explicit vs. Implicit | [
"",
"c#",
".net",
"interface",
"casting",
"duck-typing",
""
] |
I've read that there is some compiler optimization when using `#pragma once` which can result in faster compilation. I recognize that is non-standard, and thus could pose a cross-platform compatibility issue.
Is this something that is supported by most modern compilers on non-windows platforms (gcc)?
I want to avoid platform compilation issues, but also want to avoid the extra work of fallback guards:
```
#pragma once
#ifndef HEADER_H
#define HEADER_H
...
#endif // HEADER_H
```
Should I be concerned? Should I expend any further mental energy on this? | Using `#pragma once` should work on any modern compiler, but I don't see any reason not to use a standard `#ifndef` include guard. It works just fine. The one caveat is that GCC didn't support `#pragma once` before [version 3.4](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11569).
I also found that, at least on GCC, [it recognizes the standard `#ifndef` include guard and optimizes it](http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC8), so it shouldn't be much slower than `#pragma once`. | `#pragma once` does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files. | Is #pragma once a safe include guard? | [
"",
"c++",
"pragma",
"include-guards",
""
] |
Is there a method to do that? Could it be done with an extension method?
I want to achieve this:
```
string s = "foo".CapitalizeFirstLetter();
// s is now "Foo"
``` | A simple extension method, that will capitalize the first letter of a string. As Karl pointed out, this assumes that the first letter is the right one to change and is therefore not perfectly culture-safe.
```
public static string CapitalizeFirstLetter(this String input)
{
if (string.IsNullOrEmpty(input))
return input;
return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) +
input.Substring(1, input.Length - 1);
}
```
You can also use [System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx).
The function will convert the first character of **each word** to upper case. So if your input string is `have fun` the result will be `Have Fun`.
```
public static string CapitalizeFirstLetter(this String input)
{
if (string.IsNullOrEmpty(input))
return input;
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
}
```
See [this question](https://stackoverflow.com/questions/72831/how-do-i-capitalize-first-letter-of-first-name-and-last-name-in-c) for more information. | [System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx)
It has the advantage of being culture-safe. | Is there a CapitalizeFirstLetter method? | [
"",
"c#",
".net",
"string",
""
] |
I tried modifying the second property, but didn't work.
Basically I wanna do:
```
datetime.now().second += 3
``` | Have you checked out timedeltas?
```
from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)
``` | You cannot add seconds to a datetime object. From the [docs](http://pypi.python.org/pypi/DateTime):
> A DateTime object should be considered immutable; all conversion and numeric operations return a new DateTime object rather than modify the current object.
You must create another datetime object, or use the product of the existing object and a timedelta. | How to add seconds on a datetime value in Python? | [
"",
"python",
"datetime",
""
] |
I am writing a REST service in python and django and wanted to use Amazon's AWS authentication protocol. I was wondering if anyone knew of a python library that implemented formation of the header for sending and the validation of the header for recieving? | Try this Library. I think it is the library you are searching for..
[CalNet](https://calnet.berkeley.edu/developers/downloads/CalNetAwsPython.html)
You can find some Python Code Samples [Here](https://calnet.berkeley.edu/news/entry/2005/11/10/01.html) | [boto](http://code.google.com/p/boto/) is a Python library for AWS. I don't know however if it supports what you are asking for. | Is there a python library that implements both sides of the AWS authentication protocol? | [
"",
"python",
"amazon-web-services",
""
] |
I try to insert millions of records into a table that has more than 20 indexes.
In the last run it took more than 4 hours per 100.000 rows, and the query was cancelled after 3½ days...
Do you have any suggestions about how to speed this up.
(I suspect the many indexes to be the cause. If you also think so, how can I automatically drop indexes before the operation, and then create the same indexes afterwards again?)
Extra info:
* The space used by the indexes is about 4 times the space used by the data alone
* The inserts are wrapped in a transaction per 100.000 rows.
---
Update on status:
The accepted answer helped me make it much faster. | You can disable and enable the indexes. Note that disabling them can have unwanted side-effects (such as having duplicate primary keys or unique indices etc.) which will only be found when re-enabling the indexes.
```
--Disable Index
ALTER INDEX [IXYourIndex] ON YourTable DISABLE
GO
--Enable Index
ALTER INDEX [IXYourIndex] ON YourTable REBUILD
GO
``` | This sounds like a data warehouse operation.
It would be normal to drop the indexes before the insert and rebuild them afterwards.
When you rebuild the indexes, build the clustered index first, and conversely drop it last. They should all have fillfactor 100%.
Code should be something like this
```
if object_id('Index') is not null drop table IndexList
select name into Index from dbo.sysindexes where id = object_id('Fact')
if exists (select name from Index where name = 'id1') drop index Fact.id1
if exists (select name from Index where name = 'id2') drop index Fact.id2
if exists (select name from Index where name = 'id3') drop index Fact.id3
.
.
BIG INSERT
RECREATE THE INDEXES
``` | Slow bulk insert for table with many indexes | [
"",
"sql",
"sql-server",
"indexing",
"bulkinsert",
""
] |
I've created the following structure which maps unique double values to one or more pairs of integers:
```
@SuppressWarnings("boxing")
private static final HashMap<Double, Integer[][]> rules =
new HashMap<Double, Integer[][]>() {
private static final long serialVersionUID = 1L;
{
put(-0.6, new Integer[][] { { 1, 3 } });
put(-0.3, new Integer[][] { { 2, 2 } });
put(0.0, new Integer[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
put(0.3, new Integer[][] { { 4, 4 } });
put(0.6, new Integer[][] { { 5, 3 } });
}
};
```
Can I rewrite this so it's simpler - i.e not have to deal with warnings (serialVersionUID, boxing), and it being so verbose? | Using a class for the pairs of integers should be the first. Or is this a coincidence, that all arrays containing a bunch of pairs?
The second thing is, that these initialization-data could be read from a configuration-file.
**Edit:** As I looked again on this code, I realized that Doubles as keys in a Map is somewhat risky. If you produce Doubles as a result of an mathematical operation, it is not clear, if they will be equal for the computer (even if they are equal in a mathematical sense). Floating-point-numbers are represented as approximation in computers. Most likely you want to associate the values with the interval (example 0.0-0.3) and not the value itself. You may avoid trouble, if you always use the same constants as keys in the array. But in this case you could use an enum as well, and no new programmer runs into trouble, if he uses his calculated doubles as keys in the map. | Create another class to hold your pairs of integers, and store them using a list:
```
Map<Double,List<MyPair>>
```
Are these to be arbitrary pairs of integers, or will the represent something? If the latter, then name appropriately. New classes are cheap in Java, and good naming will reduce maintenance costs.
Edit: why are you creating an anonymous subclass of HashMap? | Ugly looking java data structure | [
"",
"java",
"data-structures",
""
] |
I am familiar with the formula to calculate the Great Circle Distance between two points.
i.e.
```
<?php
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
//convert degrees to distance depending on units desired
?>
```
What I need though, is the reverse of this. Given a starting point, a distance, and a simple cardinal NSEW direction, to calculate the position of the destination point. It's been a long time since I was in a math class. ;) | Here's a C implementation that I found, should be fairly straightforward to translate to PHP:
```
#define KmPerDegree 111.12000071117
#define DegreesPerKm (1.0/KmPerDegree)
#define PI M_PI
#define TwoPI (M_PI+M_PI)
#define HalfPI M_PI_2
#define RadiansPerDegree (PI/180.0)
#define DegreesPerRadian (180.0/PI)
#define copysign(x,y) (((y)<0.0)?-fabs(x):fabs(x))
#define NGT1(x) (fabs(x)>1.0?copysign(1.0,x):(x))
#define ArcCos(x) (fabs(x)>1?quiet_nan():acos(x))
#define hav(x) ((1.0-cos(x))*0.5) /* haversine */
#define ahav(x) (ArcCos(NGT1(1.0-((x)*2.0)))) /* arc haversine */
#define sec(x) (1.0/cos(x)) /* secant */
#define csc(x) (1.0/sin(x)) /* cosecant */
/*
** GreatCirclePos() --
**
** Compute ending position from course and great-circle distance.
**
** Given a starting latitude (decimal), the initial great-circle
** course and a distance along the course track, compute the ending
** position (decimal latitude and longitude).
** This is the inverse function to GreatCircleDist).
*/
void
GreatCirclePos(dist, course, slt, slg, xlt, xlg)
double dist; /* -> great-circle distance (km) */
double course; /* -> initial great-circle course (degrees) */
double slt; /* -> starting decimal latitude (-S) */
double slg; /* -> starting decimal longitude(-W) */
double *xlt; /* <- ending decimal latitude (-S) */
double *xlg; /* <- ending decimal longitude(-W) */
{
double c, d, dLo, L1, L2, coL1, coL2, l;
if (dist > KmPerDegree*180.0) {
course -= 180.0;
if (course < 0.0) course += 360.0;
dist = KmPerDegree*360.0-dist;
}
if (course > 180.0) course -= 360.0;
c = course*RadiansPerDegree;
d = dist*DegreesPerKm*RadiansPerDegree;
L1 = slt*RadiansPerDegree;
slg *= RadiansPerDegree;
coL1 = (90.0-slt)*RadiansPerDegree;
coL2 = ahav(hav(c)/(sec(L1)*csc(d))+hav(d-coL1));
L2 = HalfPI-coL2;
l = L2-L1;
if ((dLo=(cos(L1)*cos(L2))) != 0.0)
dLo = ahav((hav(d)-hav(l))/dLo);
if (c < 0.0) dLo = -dLo;
slg += dLo;
if (slg < -PI)
slg += TwoPI;
else if (slg > PI)
slg -= TwoPI;
*xlt = L2*DegreesPerRadian;
*xlg = slg*DegreesPerRadian;
} /* GreatCirclePos() */
```
> ### Source: <http://sam.ucsd.edu/sio210/propseawater/ppsw_c/gcdist.c> | To answer my own question just so it's here for anyone curious, a PHP class as converted from the C function provided by Chad Birch:
```
class GreatCircle
{
/*
* Find a point a certain distance and vector away from an initial point
* converted from c function found at: http://sam.ucsd.edu/sio210/propseawater/ppsw_c/gcdist.c
*
* @param int distance in meters
* @param double direction in degrees i.e. 0 = North, 90 = East, etc.
* @param double lon starting longitude
* @param double lat starting latitude
* @return array ('lon' => $lon, 'lat' => $lat)
*/
public static function getPositionByDistance($distance, $direction, $lon, $lat)
{
$metersPerDegree = 111120.00071117;
$degreesPerMeter = 1.0 / $metersPerDegree;
$radiansPerDegree = pi() / 180.0;
$degreesPerRadian = 180.0 / pi();
if ($distance > $metersPerDegree*180)
{
$direction -= 180.0;
if ($direction < 0.0)
{
$direction += 360.0;
}
$distance = $metersPerDegree * 360.0 - $distance;
}
if ($direction > 180.0)
{
$direction -= 360.0;
}
$c = $direction * $radiansPerDegree;
$d = $distance * $degreesPerMeter * $radiansPerDegree;
$L1 = $lat * $radiansPerDegree;
$lon *= $radiansPerDegree;
$coL1 = (90.0 - $lat) * $radiansPerDegree;
$coL2 = self::ahav(self::hav($c) / (self::sec($L1) * self::csc($d)) + self::hav($d - $coL1));
$L2 = (pi() / 2) - $coL2;
$l = $L2 - $L1;
$dLo = (cos($L1) * cos($L2));
if ($dLo != 0.0)
{
$dLo = self::ahav((self::hav($d) - self::hav($l)) / $dLo);
}
if ($c < 0.0)
{
$dLo = -$dLo;
}
$lon += $dLo;
if ($lon < -pi())
{
$lon += 2 * pi();
}
elseif ($lon > pi())
{
$lon -= 2 * pi();
}
$xlat = $L2 * $degreesPerRadian;
$xlon = $lon * $degreesPerRadian;
return array('lon' => $xlon, 'lat' => $xlat);
}
/*
* copy the sign
*/
private static function copysign($x, $y)
{
return ((($y) < 0.0) ? - abs($x) : abs($x));
}
/*
* not greater than 1
*/
private static function ngt1($x)
{
return (abs($x) > 1.0 ? self::copysign(1.0 , $x) : ($x));
}
/*
* haversine
*/
private static function hav($x)
{
return ((1.0 - cos($x)) * 0.5);
}
/*
* arc haversine
*/
private static function ahav($x)
{
return acos(self::ngt1(1.0 - ($x * 2.0)));
}
/*
* secant
*/
private static function sec($x)
{
return (1.0 / cos($x));
}
/*
* cosecant
*/
private static function csc($x)
{
return (1.0 / sin($x));
}
}
``` | Great Circle Distance question | [
"",
"php",
"latitude-longitude",
"great-circle",
""
] |
We are seeing an older version of a class being used, although we had the latest one deploy. To scan all JAR files in all subfolders of an application server, how do we write a small shell script that prints out the file name of JARS files in which this specific class is found? | Something like:
```
find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep org/jboss/Main; then echo "$jarfile"; fi; done
```
You can wrap that up like this:
```
jarscan() {
pattern=$(echo $1 | tr . /)
find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep "$pattern"; then echo "$jarfile"; fi; done
}
```
And then `jarscan org.jboss.Main` will search for that class in all jar files found under the current directory | Not directly answering your question, but maybe this will solve your problem: you can print out the location (e.g. the jar file) from which a specific class was loaded by adding a simple line to your code:
```
System.err.println(YourClass.class.getProtectionDomain().getCodeSource());
```
Then you will know for sure where it comes from. | JarScan, scan all JAR files in all subfolders for specific class | [
"",
"java",
"class",
"jar",
""
] |
Which operator: `/` or `*` will have the higher priority in `MySQL`? | Like most programming languages, mysql performs `/` and `*` (as well as DIV, % and MOD) from left to right, in the order they occur. For instance:
```
1 / 2 * 3 / 4 / 5 * 6
```
is equivalent to
```
((((1 / 2) * 3) / 4) / 5) * 6
```
See <http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html> for a complete list of operator precedence. | The operators are prioritized as listed from the highest precedence to the lowest:
1. BINARY, COLLATE
2. NOT (logical negation), ! (logical negation)
3. .- (unary minus), ~ (unary bit inversion)
4. ^ (bitwise exclusive OR comparison)
5. .\* (multiplication), / (division), % (modulo)
6. .- (subtraction), + (addition)
7. << (bitwise shift left), >> (bitwise shift right)
8. & (bitwise AND)
9. | (bitwise OR)
10. Comparison operators such as < >
11. BETWEEN, NOT BETWEEN
12. AND && (conjuction - logical addition)
13. XOR (logical exclusive OR comparison)
14. OR || (disjunction - either/or comparison)
As per list, the comparison BINARY operator has precedence over the BETWEEN and ampersand (&) operators. Operators on the same line above have the same level of precedence, and are evaluated in the order of usage.
Source <http://www.learn-mysql-tutorial.com/Expressions.cfm> | operator precedence in mysql | [
"",
"sql",
"mysql",
""
] |
I'd like to get up to speed on web services--
I've found that I really like the video format; I tend to skim when I'm reading (bad habit) and I generally don't get the full value out of the video. I would like to see any kind of good resource that you can recommend though; the best thing to do is to collect the best resources. | Here are some good starts
* <http://www.asp.net/learn/videos/video-280.aspx>
* <http://www.dnrtv.com/default.aspx?showNum=33>
* <http://www.pnpguidance.net/Screencast/DayOfPatternsPracticesScreencastWCSFAJAXDynamicDataMVCFramework.aspx>
* <http://www.pnpguidance.net/Screencast/CreateDataAccessLayerUsingDataAccessGuidancePackageScreencast.aspx>
if you like screen cast these are the places to start looking, also look at <http://www.dimecasts.net/>, but they didn't have any on web services | The [WCF Developer Center](http://msdn.microsoft.com/wcf) on MSDN is a good place to start.
Be sure to stay away from ASMX web services and WSE web services. They are old and obsolete, respectively. | What are the best recources for learning .NET webservices? | [
"",
"c#",
".net",
"asp.net",
"web-services",
""
] |
I would like to perform and atomic read of 64b aligned 64b data on x86 platform (Pentium or above guaranteed).
Is there a way to do this? (And no, I do not want to use a critical section or a mutex for this, I want this to be lock-free). | Use the Interlocked operations, here's some sample code:
```
LONGLONG AtomicRead(LONGLONG* p)
{
return InterlockedCompareExchange64(p, 0, 0);
}
```
This does the compare exchange against zero and sets p to zero if it's already equal to zero -ie, it's a noop. InterlockedCompareExchange returns the original 64 bit value pointed to by p. | [This page](http://www.niallryan.com/node/137) describes how to do it. Basically you just have to use `lock cmpxchg8b`. | How to perform atomic 64b read on x86 (Pentium and above)? | [
"",
"c++",
"winapi",
"x86",
"multicore",
"atomic",
""
] |
Suppose the string is:
```
string item = "t-ewrwerwerwerwer\r-rr\wrjkwlr";
```
I want to Replace all - except when it is preceded by r.
So resut will be
```
string cleanItem = "tewrwerwerwerwer\r-rr\wrjkwlr"'
```
What regular expression can be used? | A replacement on `(?<!r)-` by an empty string should do the trick I think. | I think this regular expression is a little more efficient:
```
-(?<!r-)
```
Or if your language doesn’t support negative look-behind assertions, use this expression:
```
(^|[^r])-
```
and replace it by `\1` (first matching group). | How to form this Regex | [
"",
"c#",
"regex",
""
] |
Is there a way to define a macro (or something similar) that would allow objects to be allocated on the stack or on the heap, cleanly?
eg.
Current code:
```
A a;
a.someFunc();
```
The simplest suggestion might be the following, but as you can see below, it's not very clean to maintain 2 sets of code.
```
#ifdef USE_STACK
A a;
a.someFunc();
#elseif USE_HEAP
A* a = new A();
a->someFunc();
#endif
```
I am looking for a design pattern / proxy class that can be use to compile the code either way, depending on the needs of our customer.
Edit: The code is used to build a library for embedded device / (embedded) Linux / Windows Mobile. Most customers want stack based allocation only. A few others have asked to trade stack for heap.
Thanks,
Charles | **EDIT**: improved to allow calling of wrapped member functions through `operator->`
Expanding on Manuel's answer to make it more complete, try this:
```
#include <iostream>
#define USE_STACK
template <class T>
class HeapWrapper {
#ifdef USE_STACK
T obj_;
#else
T *obj_;
#endif
public:
#ifdef USE_STACK
HeapWrapper() : obj_() {}
template <class A1>
HeapWrapper(const A1 &a1) : obj_(a1) {}
template <class A1, class A2>
HeapWrapper(const A1 &a1, const A2 &a2) : obj_(a1, a2) {}
// etc
#else
HeapWrapper() : obj_(new T()) {}
~HeapWrapper() { delete obj_; }
template <class A1>
HeapWrapper(const A1 &a1) : obj_(new T(a1)) {}
template <class A1, class A2>
HeapWrapper(const A1 &a1, const A2 &a2) : obj_(new T(a1, a2)) {}
// etc
#endif
#ifdef USE_STACK
operator const T &() const { return obj_; }
operator T &() { return obj_; }
T *operator->() { return &obj_; }
T& operator*() { return obj_; }
#else
operator const T &() const { return *obj_; }
operator T &() { return *obj_; }
T *operator->() { return obj_; }
T& operator*() { return *obj_; }
#endif
// cast operators makes this work nicely
HeapWrapper &operator=(const T &rhs) { *obj_ = rhs; return *this;}
};
class A {
public:
void member(int x) {
std::cout << x << std::endl;
}
};
int main() {
HeapWrapper<int> x1(5);
HeapWrapper<int> x2;
HeapWrapper<int> x3 = x1;
HeapWrapper<int> x4 = 3;
std::cout << x1 << " " << x2 << " " << x3 << " " << x4 << std::endl;
// example using a custom class's members..
HeapWrapper<A> a1;
a1->member(5);
}
``` | Something like this could help:
```
template <typename T>
class HeapWrapper
{
#ifdef USE_STACK
T obj_;
#else
T *obj_;
#endif
public:
#ifdef USE_STACK
HeapWrapper() : obj_() {}
#else
HeapWrapper() : obj_(new T()) {}
#endif
#ifdef USE_STACK
const T& obj() const
{ return obj_; }
T& obj() const
{ return obj_; }
#else
const T& obj() const
{ return *obj_; }
T& obj() const
{ return *obj_; }
#endif
};
```
However, note that this either limits you to objects with default constructor only. The wrapped class could provide an `Init(...)` function which could be forwarded by a [variadic template function](http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.html) by the wrapper class (or simply add a `template <typename T1, template T2, [etc]> Init(const T1 &x1, cons tT2 &x2)` for each arity you need):
```
template <typename T1>
void Init(const T1& x1)
{
#ifdef USE_STACK
obj_.Init(x1);
#else
obj_->Init(x1);
#endif
}
template <typename T1, typename T2>
void Init(const T1& x1, const T2& x2)
{
#ifdef USE_STACK
obj_.Init(x1, x2);
#else
obj_->Init(x1, x2);
#endif
}
```
Bonus points if your compiler has [variadic templates](http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.html) already:
```
template<typename... T>
void foo(const T&... values) {
#ifdef USE_STACK
obj_.Init(values...);
#else
obj_->Init(values...);
#endif
}
``` | C/C++ pattern to USE_HEAP or USE_STACK | [
"",
"c++",
"c",
"memory-management",
"stack",
"heap-memory",
""
] |
Using php5.2 and MySQL 4.1.22
I've come across something that, at first, appeared simple but has since evaded me in regards to a simple, clean solution.
We have pre-defined "packages" of product. Package 1 may have products A, B and C in it. Package 2 may have A, C, D and G in it, etc. The packages range in size from 3 to 5 products.
Now, a customer can pick any 10 products available and make a "custom" package. Since we already have certain predefined packages, we'd like to build the custom package with smaller existing packages (for shipping ease) where possible.
So, for instance, a customer selects to create a 'custom package' of products A, B, C, D, E and F. We already have a predefined package that contains A, B and C called Foo. So, the order would then be Foo, D, E and F.
The catch is in having the least amount of individual items, followed by the least amount of packages. For instance:
Custom Package: A, B, C, D, E, F, G, H, I, J.
Predefined Package (1): A, B, C, D, E
Predefined Package (2): A, B, C
Predefined Package (3): D, E, F
If I simply take the largest match, then I have 1 (5pc) package and 5 individual items. Neither Package (2) nor (3) can be built with the remaining items.
If I look deeper, I find that by not building package (1) I can instead build package (2) and package (3). Which means I have 2 packages and 4 individual items (a better choice in this buisiness rule).
As I'm using MySQL, I'm under the restraint of only having one layer of sub select available (to my knowledge). So this sort will need to be performed in php. I've looked at using array\_intersect() to determine matches, but every way I've found grows exponentially in regards to processing as the number of predefined packages grows linearly.
I ran this by a couple other coder friends and again, while it seemed like there should be an easy answer we all found that it wasn't as simple as it seems. So, I thought I'd post it here as a nice noodle stretcher. Thanks much in advance for your time! | The problem is generally a "hard" one (speaking in terms of computational complexity). In fact it rings some bells in the back of my head that it probably reduces to one of those classic algorithm problems like the [Knapsack problem](http://en.wikipedia.org/wiki/Backpack_problem#Further_reading), but I can't attach a proper name to it.
However, with such a small problem space (they can only pick 10 products), it should be fairly quick to just brute-force the thing. When someone submits a custom build, just recursively attack it with all possibilities and see which one is the best.
That is, take the components they've selected, and first try to remove the components of "Package 1" from it. If that's possible, take the remaining components and try to take the components of "Package 2" from it, etc. Keep track of the best solution you've found so far as you go along.
If it's still not fast enough (but I think it probably will be, depending on how many pre-built packages you have), you could apply some [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) methods to speed it up.
---
**Edited to add:**
Depending on the number of possibilities and how long this actually takes to run, you may want to write the code I described above, and then just go ahead and pre-compute all the solutions for every possible combination. Then when someone submits a custom build, you just have to fetch the answer instead of computing it from scratch every time.
Even if you don't want to pre-compute them all, I'd suggest storing the result every time someone does a custom build, then in the future if anyone else does the same custom build you don't have to recalculate the solution. | I suggest you let the customer help. In the product selection screens, show what packaged sets are available, and let them make the combinations (priced appropriately so that the sum of onesies is enough to cover special handling). | Looking for a clean, efficient way to match a set of data against known patterns | [
"",
"php",
"mysql",
"pattern-matching",
""
] |
I've come up against the unlikely scenario when I reference two external assemblies that both have the same namespace and type names. When I try to use the type, the compiler throws an error that it cannot resolve which one I want to use.
I see that C# offers a mechanism to use aliases for references. You can even specify these aliases via the `Property` window of a reference in Visual Studio 2008. How do I use this alias in my code? As I understand, I should be using the `::` operator, but it fails with the following error:
> `CS0432 - Alias not found`
The usual `.` operator fails as well.
In the output window I see that the compiler gets the alias passed correctly in its command line.
Any pointers on what I may be able to try next are greatly appreciated. | ```
extern alias alias1;
using alias1::Namespace;
``` | Try this:
```
extern alias asm1;
extern alias asm2;
namespace Client
{
class Program
{
static void Main(string[] args)
{
asm1.MyNs.MyClass mc1 = null;
asm2.MyNs.MyClass mc2 = null;
}
}
}
```
And add `global,asm1` to the project reference for assembly1 and `global,asm2` for assembly2 | How to get the namespace alias operator :: to work under C#? | [
"",
"c#",
".net",
"namespaces",
"alias",
""
] |
**Single and multiple lists**
Consider the following lists:
```
List<Int32> appleIdentities = new List<int>(new[] { 1, 2, 3 });
List<Int32> chocolateIdentities = new List<int>(new[] { 2, 3, 4 });
List<Int32> icecreamIdentities = new List<int>(new[] { 11, 14, 15, 16 });
```
Using LINQ to SQL; is it possible to wite a statement which translates into:
```
SELECT
DesertsID,
DesertsName
FROM
Deserts
WHERE
Deserts.AppleIdentity IN (1, 2, 3) AND
Deserts.ChocolateIdentity IN (2, 3, 4) AND
Deserts.IcecreamIdentity IN (11, 14, 15m 16)
```
If yes; how would the code look if I wanted to query my database of deserts against just the `appleIdentities` list?
**Arrays**
Consider the following arrays:
```
Int32[] appleIdentities = new[] {1, 2, 3, 4};
String[] chocolateNames = new[] {"Light", "Dark"};
```
Using LINQ to SQL; is it possible to wite a statement which translates into:
```
SELECT
DesertsID,
DesertsName
FROM
Deserts
WHERE
Deserts.AppleIdentity IN (1, 2, 3) AND
Deserts.ChocolateName IN ('Light', 'Dark')
```
If yes; how would the code look if I wanted to query my database of deserts against just the `appleIdentities` array?
**List of objects**
Consider the following:
```
public class Identities
{
public Int32 appleIdentity { get; set; }
public String chokolateName { get; set; }
}
List<Identities> identities = new List<Identities>(new[] {
new Identities { appleIdentity = 1, chokolateName = "Light" },
new Identities { appleIdentity = 2, chokolateName = "Dark" },
});
```
Using LINQ to SQL; is it possible to wite a statement which translates into:
```
SELECT
DesertsID,
DesertsName
FROM
Deserts
WHERE
Deserts.AppleIdentity IN (1, 2) AND
Deserts.ChocolateName IN ('Light', 'Dark')
```
If yes; how would the code look if I wanted to query my database of deserts against just the `appleIdentity`-property on my list of `Identities` objects?
This is branch off of [LINQ to SQL query against a list of entities](https://stackoverflow.com/questions/729899/linq-to-sql-query-against-a-list-of-entities) | Sure - just use `Contains` - using Northwind as an example:
```
var qry = from cust in ctx.Customers
where custIds.Contains(cust.CustomerID)
&& regions.Contains(cust.Region)
select cust; // or your custom projection
``` | > how would the code look if I wanted to
> query my database of deserts against
> just the appleIdentities list?
You can compose a linq query in multiple statements, like so, and select at runtime which filters your want to use in your where clause.
```
var query = db.Desserts;
if (filterbyAppleIdentity)
query = query.Where( q => appleIdentities.Contains(q.DesertsID));
if (filterbyChocolateIdentities)
query = query.Where( q => chocolateIdentities.Contains(q.DesertsID));
if (filterbicecreamIdentities)
query = query.Where( q => icecreamIdentities.Contains(q.DesertsID));
var deserts = query.ToList();
```
you can also write an extension method to do this without if statements: (Edit fixed typo, return type should be IQueriable
```
public static class LinqExtensions {
public IQueriable<T> CondWhere<T>(this IQueriable<T> query, bool condition, Expression<Func<T,bool>> predicate) {
if (condition)
return query.Where(predicate);
else
return query;
}
}
```
and write your linq query like this:
```
var deserts = db.Desserts;
.CondWhere(filterbyAppleIdentity, q => appleIdentities.Contains(q.DesertsID));
.CondWhere(filterbyChocolateIdentities, q => chocolateIdentities.Contains(q.DesertsID));
.CondWhere(filterbicecreamIdentities, q => icecreamIdentities.Contains(q.DesertsID)).ToList();
```
Another way to do it is to union the id lists:
```
var deserts = db.Deserts
.Where( d => appleIdentities.Union(chocolateIdentities).Union(icecreamIdentities).Contains(d.DesertsID);
```
For a list of objects you can use .Select extension method to project your list into a int or string IEnumerable and you can use contains in the query in the same way:
```
var deserts = db.Deserts
.Where(d =>
identities.Select(i => i.appleIdentity).Contains(d => d.DesertID) &&
identities.Select(i => i.chokolateName).Contains(d => d.DesertsName)
)
``` | LINQ to SQL: Advanced queries against lists, arrays and lists of objects | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I am writting a winforms c# 2.0 application that needs to put an XML file into a document library on SharePoint.
I want to use a WebService instead of using the object model (no sharepoint.dll to reference here)
I am currently using the <http://webserver/site/_vti_bin/copy.asmx> webservice.
Here is some code:
```
byte[] xmlByteArray;
using (MemoryStream memoryStream = new MemoryStream())
{
xmlDocument.Save(memoryStream);
xmlBytes = memoryStream.ToArray();
}
string[] destinationUrlArray = new string[] {"http://webserver/site/Doclib/UploadedDocument.xml"};
FieldInformation fieldInfo = new FieldInformation();
FieldInformation[] fields = { fieldInfo };
CopyResult[] resultsArray;
using (Copy copyService = new Copy())
{
copyService.Credentials = CredentialCache.DefaultCredentials;
copyService.Url = "http://webserver/site/_vti_bin/copy.asmx";
copyService.Timeout = 600000;
uint documentId = copyService.CopyIntoItems("", destinationUrlArray, fields, xmlByteArray, out resultsArray);
}
```
When this code runs, I get a single result in the resultsArray out parameter:
```
DestinationURL: "http://webserver/site/Doclib/UploadedDocument.xml"
ErrorCode: UnKnown
ErrorMessage: "Object reference not set to an instance of an object."
```
From my searching, I have found a couple of possible helps.
* [Microsoft TechNet](http://social.technet.microsoft.com/Forums/pt-BR/sharepointdevelopment/thread/5a1ce3c9-ebc7-4ec9-b0fb-b891d076591b) -- "The copy.asmx copyintoitems will only work if the source and destination urls are in the same SPWebApplication (Site Collection)."
* [Microsoft Social](http://social.microsoft.com/Forums/zh-CN/sharepointdevelopment/thread/273528be-b207-48d9-b697-74777416638e) -- "Object reference not set to an instance of an object
error occurs because of SharePoint not able to identified that particular property."
This leads me to believe my source url should be set to something, but what? This is originating from a client workstation and does not have a source URL.
Any help would be appricated.
hank you,
Keith | Here is what is currently working:
```
WebRequest request = WebRequest.Create(“http://webserver/site/Doclib/UploadedDocument.xml”);
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
byte[] buffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
dataFile.MMRXmlData.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
for (int i = memoryStream.Read(buffer, 0, buffer.Length); i > 0;
i = memoryStream.Read(buffer, 0, buffer.Length))
{
stream.Write(buffer, 0, i);
}
}
}
WebResponse response = request.GetResponse();
response.Close();
```
So... Does anyone have an opinion as to if this "PUT" method is better in the SharePoint environment than using a built-in webservice?
Right now I would have to say the "PUT" method is better since it works and I could not get the WebService to work.
Keith | I know this is an old thread but it kept coming up as I was searching for a solution to the same problem.
Check Steve Curran's answer on this thread <http://social.msdn.microsoft.com/Forums/en-SG/sharepointdevelopment/thread/833e38a8-f13c-490d-8ba7-b889b6b25e38>. Looks like Basically the request fails because the destination url can't be resolved.
(Limitations of a new stackflow user - can't post more than one link. See my comment for the rest)
pat | How do you copy a file into SharePoint using a WebService? | [
"",
"c#",
"web-services",
"sharepoint",
"file-upload",
""
] |
I have a standard HTML input that I want to run JavaScript code when it loses focus. Sadly my Google searches did not reveal how to do this.
To make it clear, I'm looking for a way to do this:
```
<input type="text" name="name" value="value" onlosefocus="alert(1);"/>
``` | How about onblur event :
```
<input type="text" name="name" value="value" onblur="alert(1);"/>
``` | `onblur` is the opposite of `onfocus`. | Run JavaScript when an element loses focus | [
"",
"javascript",
"html",
"dom-events",
""
] |
I need to build a windows forms application to measure the time it takes to fully load a web page, what's the best approach to do that?
The purpose of this small app is to monitor some pages in a website, in a predetermined interval, in order to be able to know beforehand if something is going wrong with the webserver or the database server.
**Additional info:**
I can't use a commercial app, I need to develop this in order to be able to save the results to a database and create a series of reports based on this info.
The webrequest solution seems to be the approach I'm goint to be using, however, it would be nice to be able to measure the time it takes to fully load the the page (images, css, javascript, etc). Any idea how that could be done? | If you just want to record how long it takes to get the basic page source, you can wrap a HttpWebRequest around a stopwatch. E.g.
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
```
However, this will not take into account time to download extra content, such as images.
[edit] As an alternative to this, you may be able to use the WebBrowser control and measure the time between performing a .Navigate() and the DocumentCompleted event from firing. I think this will also include the download and rendering time of extra content. However, I haven't used the WebBrowser control a huge amount and only don't know if you have to clear out a cache if you are repeatedly requesting the same page. | Depending on how the frequency you need to do it, maybe you can try using Selenium (a automated testing tool for web applications), since it users internally a web browser, you will have a pretty close measure. I think it would not be too difficult to use the Selenium API from a .Net application (since you can even use Selenium in unit tests).
Measuring this kind of thing is tricky because web browsers have some particularities when then download all the web pages elements (JS, CSS, images, iframes, etc) - this kind of particularities are explained in this excelent book ([http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309/](https://rads.stackoverflow.com/amzn/click/com/0596529309)).
A homemade solution probably would be too much complex to code or would fail to attend some of those particularities (measuring the time spent in downloading the html is not good enough). | How can I measure the response and loading time of a webpage? | [
"",
"c#",
"winforms",
"monitoring",
""
] |
I put a check in a script that makes sure a total is correct. What it does is looks at the total as it is stored in the database and then using other variables, calculates what the total should be.
If these two values - the stored total and the calculated total - are not equal, it's a problem so I want it to send an email alert.
Here's the snippet of the code I use to do this:
```
$storedTotal = $row['total']; # Pulls from a varchar field in the database
$calculatedTotal = $subtotal + $tax + $shipping - $deduct;
# Make sure the stored total equals what it should (the calculated total)
if($storedTotal != $calculatedTotal) {
# Send an alert
mail("admin@domain.com","Total check fail","Stored total:$storedTotal \n\n Calculated total:$calculatedTotal \n\n");
}
```
It seems very simple, however, I repeatedly get emails from it that looks like this:
```
Stored total:23.40
Calculated total:23.40
```
As you can see, the two values appear the same.
Can anyone see any reason why they're not showing as equal? I'm not using a strict equality check so it shouldn't be getting tripped up on types. | Try converting and rounding before you compare them:
```
$storedTotal = round(floatval($storedTotal), 2);
$calculatedTotal = round(floatval($calculatedTotal), 2);
if ($storedTotal != calculatedTotal) {
...
``` | It's most likely a floating point comparison error - there are probably some very insignificant digits which the default `float -> string` conversion routines think aren't worth printing but which are significant enough to cause the comparison to fail. You'll find dozens of similar questions on StackOverflow.
As these appear to be currency amounts, just check that they're within a tenth of a minor unit of each other:
```
$is_equal = (abs($val1 - $val) < 0.001);
``` | Figure out why this simple comparison is showing not equal in PHP | [
"",
"php",
""
] |
What is the best way to compare to Images in the database?
I tried to compare them (@Image is the type Image):
```
Select * from Photos
where [Photo] = @Image
```
But receives the error "The data types image and image are incompatible in the equal to operator". | Since the Image data type is a binary and huge space for storing data, IMO, the easiest way to compare Image fields is hash comparison.
So you need to store hash of the Photo column on your table. | If you need to compare the image you should retrive all the images from the database and do that from the language that you use for accessing the database. This is one of the reasons why it's not a best practice to store images or other binary files in a relational database. You should create unique file name every time when you want to store an image in a database. Rename the file with this unique file name, store the image on the disk and insert in your database it's name on the disk and eventually the original name of the file or the one provided by the user of your app. | Compare Images in SQL | [
"",
"sql",
"stored-procedures",
""
] |
I'm trying to create a method in C# to return a string of a web pages html content from the url. I have tried several different ways, but I am getting the error **System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.**
The following works fine locally, but gets the above error when running on a remote server:
```
public static string WebPageRead(string url)
{
string result = String.Empty;
WebResponse response = null;
StreamReader reader = null;
try
{
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
return result;
}
``` | Thanks for the responses, the problem was due to a DNS issue on the remote server! Just to confirm, I went with the following code in the end:
```
public static string WebPageRead(string url)
{
string content = String.Empty;
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
}
}
}
}
catch (Exception exc)
{
throw exc;
}
}
}
return content;
}
``` | This is probably not the problem, but try the following:
```
public static string WebPageRead(string url)
{
if (String.IsNullOrEmpty(url))
{
return null;
}
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
return null;
}
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader =
new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
```
I echo the earlier answer that suggests you try this with a known good URL. I'll add that you should try this with a known good HTTP 1.1 URL, commenting out the line that sets the version to 1.0. If that works, then it narrows things down considerably. | System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive | [
"",
"c#",
"webrequest",
""
] |
I'm trying to generate a client for some SOAP web services using the JDK 6 tool `wsimport`.
The WSDL was generated by a .NET 2.0 application. For .NET 3.X applications, it works fine.
When I run
```
wsimport -keep -p mypackage http://myservice?wsdl
```
it shows several error messages like this:
> [ERROR] A class/interface with the same name "mypackage.SomeClass" is already in use.
> Use a class customization to resolve this conflict. line ?? of <http://myservice?wsdl>
When I generate the web services client using Axis 1.4 (using the Eclipse WebTools plug-in).
Does anybody know what can I do in order to use the `wsimport` tool? I really don't understand what the "class customization" thing is. | I don't know if this was ever solved, but I spent some time googling for a solution to this same problem.
I found a fix here - <https://jax-ws.dev.java.net/issues/show_bug.cgi?id=228>
The solution is to run wsimport with the `-B-XautoNameResolution` (no spaces) | For anyone reading this using maven, this is how to add it to the .pom file. Note the args in the configuration section. This is not very easily found in documentation. Many thanks to Isaac Stephens for his help with this.
```
<!-- definition for ERPStandardWork service -->
<execution>
<id>ERPStandardWorkService</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<!-- this resolves naming conflicts within the wsdl - there are several copies of fault report objects which clash otherwise. -->
<args>
<arg>-B-XautoNameResolution</arg>
</args>
<wsdlDirectory>${basedir}/src/main/resources/META-INF/wsdl</wsdlDirectory>
<wsdlFiles>
<wsdlFile>ERPStandardWork.wsdl</wsdlFile>
</wsdlFiles>
<wsdlLocation>${basedir}/src/main/resources/META-INF/wsdl/ERPStandardWork.wsdl
</wsdlLocation>
<staleFile>${project.build.directory}/jaxws/ERPStandardWork/.staleFlag
</staleFile>
</configuration>
</execution>
``` | Problem generating Java SOAP web services client with JDK tool wsimport from a WSDL generated by a .NET 2.0 application | [
"",
"java",
".net",
"web-services",
"axis",
"wsimport",
""
] |
How can I force a section of code to be executed on my main thread?
This is why I'd like to know:
I have a custom created message box that at times gets shown from a thread that is not the main thread. However, when the message box constructor is called I get an InvalidOperationException saying "The calling thread must be STA, because many UI components require this." This makes sense, UI elements need to be handled on the main thread.
My MessageBox.ShowMessage(...) function is a static function that creates an instance of my custom message box and shows it. Is there a something I could put in ShowMessage that would force the message box to be created and shown on the main thread? Elsewhere in my code I use the Control.BeginInvoke to handle similar issues, but since it is a static function there is no already existing UI element for me to call BeginInvoke on.
Do I have to call MessageBox.ShowMessage from with a Control.BeginInvoke? I'd prefer the BeginInvoke (or some equivalent) to be called from within ShowMessage. | There are a few options here:
* make the second thread STA (you can only do this for your own `Thread` - not for `ThreadPool` threads) - via `.SetApartmentState(ApartmentState.STA);`
* see if [`SynchronizationContext.Current`](http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.current.aspx) is non-null; if so, use `Send`/`Post`
* pass the form/control in as an [`ISynchronizeInvoke`](http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspx) instance (may not apply to WPF - I'm not 100% sure) | Your thinking is right -- in order to get it to work properly, you're going to need to get it called from the main thread.
The simplest way? When you start your main form, save a reference in a static variable that is visible to your ShowMessage() call. Then, your ShowMessage can do the standard:
```
if(myForm.InvokeRequired)
{
myForm.Invoke(() => ShowMessage(arg1,arg2,arg3));
return;
}
.... other code here....
``` | Forcing code execution on main thread | [
"",
"c#",
"wpf",
"multithreading",
""
] |
I have some code that does a lot of comparisons of 64-bit integers, however it must take into account the length of the number, as if it was formatted as a string. I can't change the calling code, only the function.
The easiest way (besides .ToString().Length) is:
```
(int)Math.Truncate(Math.Log10(x)) + 1;
```
However that performs rather poorly. Since my application only sends positive values, and the lengths are rather evenly distributed between 2 and 9 (with some bias towards 9), I precomputed the values and have if statements:
```
static int getLen(long x) {
if (x < 1000000) {
if (x < 100) return 2;
if (x < 1000) return 3;
if (x < 10000) return 4;
if (x < 100000) return 5;
return 6;
} else {
if (x < 10000000) return 7;
if (x < 100000000) return 8;
if (x < 1000000000) return 9;
return (int)Math.Truncate(Math.Log10(x)) + 1; // Very uncommon
}
}
```
This lets the length be computed with an average of 4 compares.
So, are there any other tricks I can use to make this function faster?
Edit: This will be running as 32-bit code (Silverlight).
Update:
I took Norman's suggestion and changed the ifs around a bit to result in an average of only 3 compares. As per Sean's comment, I removed the Math.Truncate. Together, this boosted things about 10%. Thanks! | Two suggestions:
1. Profile and put the common cases first.
2. Do a binary search to minimize the number of comparions in the worst case. You can decide among 8 alternatives using exactly three comparisons.
This combination probably doesn't buy you much unless the distribution is very skew. | From Sean Anderson's [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10):
**Find integer log base 10 of an integer**
```
unsigned int v; // non-zero 32-bit integer value to compute the log base 10 of
int r; // result goes here
int t; // temporary
static unsigned int const PowersOf10[] =
{1, 10, 100, 1000, 10000, 100000,
1000000, 10000000, 100000000, 1000000000};
t = (IntegerLogBase2(v) + 1) * 1233 >> 12; // (use a lg2 method from above)
r = t - (v < PowersOf10[t]);
```
> The integer log base 10 is computed by
> first using one of the techniques
> above for finding the log base 2. By
> the relationship log10(v) = log2(v) /
> log2(10), we need to multiply it by
> 1/log2(10), which is approximately
> 1233/4096, or 1233 followed by a right
> shift of 12. Adding one is needed
> because the IntegerLogBase2 rounds
> down. Finally, since the value t is
> only an approximation that may be off
> by one, the exact value is found by
> subtracting the result of v <
> PowersOf10[t].
>
> This method takes 6 more operations
> than IntegerLogBase2. It may be sped
> up (on machines with fast memory
> access) by modifying the log base 2
> table-lookup method above so that the
> entries hold what is computed for t
> (that is, pre-add, -mulitply, and
> -shift). Doing so would require a total of only 9 operations to find the
> log base 10, assuming 4 tables were
> used (one for each byte of v).
As far as computing IntegerLogBase2, there are several alternatives presented on that page. It's a great reference for all sorts of highly optimized integer operations.
A variant of your version is also there, except it assumes the values (rather than the log base 10 of the values) are uniformly distributed, and therefore does an exponentially ordered search:
**Find integer log base 10 of an integer the obvious way**
```
unsigned int v; // non-zero 32-bit integer value to compute the log base 10 of
int r; // result goes here
r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
(v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
(v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
```
> This method works well when the input
> is uniformly distributed over 32-bit
> values because 76% of the inputs are
> caught by the first compare, 21% are
> caught by the second compare, 2% are
> caught by the third, and so on
> (chopping the remaining down by 90%
> with each comparision). As a result,
> less than 2.6 operations are needed on
> average. | Fastest way to calculate the decimal length of an integer? (.NET) | [
"",
"c#",
".net",
"performance",
"integer",
""
] |
I have an open source Java application that uses Hibernate and HSQLDB for persistence. In all my toy tests, things run fast and everything is good. I have a client who has been running the software for several months continuously and their database has grown significantly over that time, and performance has dropped gradually. It finally occurred to me that the database could be the problem. As far as I can tell from log statements, all of the computation in the server happens quickly, so this is consistent with the hypothesis that the DB might be at fault.
I know how to do normal profiling of a program to figure out where hot spots are and what is taking up significant amounts of time. But all the profilers I know of monitor execution time within the program and don't give you any help about calls to external resources. What tools do people use to profile programs that are using external db calls to find out where to optimize performance?
A little blind searching around has already found a few hot spots--I noticed a call where I was enumerating all the objects of a particular class in order to find out whether there were any. A one line change to the criterion [.setMaxResults(1)] changed that call from a half-second to virtually instantaneous. I also see places where I ask the same question from the db many times within a single transaction. I haven't figured out how to cache the answer yet, but what I really want is a tool to help me look for these kinds of things more systematically. | Unfortunately, as far as I know, there is no tool for that.
But there are some things you might want to check:
* Are you using eager loading instead of lazy loading? By the description of your problem, it really looks like you are not using lazy loading...
* Have you turned on and properly configured your second-level caching? Including the Query Cache? Hibernate caching mechanism is extremely powerful and flexible.
* Have you consider using Hibernate Search? Depending on your query, Hibernate Search Full Text index on top of Apache Lucene can speed up you queries (since it indexing system is so powerful) | How much data are you storing in HSQLDB? I don't think it performs well when managing large sets of data, since it's just storing everything in files... | How to tune performance of hsqldb/hibernate app | [
"",
"java",
"hibernate",
"profiling",
"hsqldb",
""
] |
I'm currently learning C# and .NET (coming from a UNIX background), and have just started writing a media player. I was hoping for some suggestions on the best way to store the internal database of songs. SQL? Some kind of text file? I don't really have any experience in this area so all points will be really appreciated.
Cheers! | You should probably use SQLite, and you can use LINQ on that to take full advantage of C# 3.5.
<http://www.codeproject.com/KB/linq/linqToSql_7.aspx> | There is also SQL Server Compact. Linq to Sql works with this as well. | Most efficient internal database for a media player | [
"",
"c#",
".net",
"database",
""
] |
On the program I'm writing I have a class `RestrictedUser` and class `User` that is derived from `RestrictedUser.` I'm trying to hide the User specific methods by casting to `RestrictedUser` but when I do the casting the User methods are still available. Also when I run the debugger the type of the variable comes up as `User`.
```
RestrictedUser restricted = regularUser;
```
Does up casting in Java hide the subclass methods and fields or am I doing something wrong? Is there a workaround?
Thanks | If you were to attempt to run this code:
```
User user = new User(...);
RestrictedUser restricted = user;
restricted.methodDefinedInTheUserClass(); // <--
```
you would get a compilation error. That won't be secure in any way, shape, or form, because even if you were to pass around the `RestrictedUser` to, say, another method, that method could do this:
```
if (restricted instanceof User) {
User realUser = (User)restricted;
realUser.methodDefinedInTheUserClass(); // !!
}
```
and your "restricted" user isn't so restricted anymore.
The object is showing up in the debugger as a `User` object because it is as `User` object, even if the object reference is stored in a `RestrictedUser` variable. Basically, putting an instance of a child class in a variable with a parent class's type will indeed "hide" the subclass's methods and fields, but not securely. | I'm not sure exactly what you are asking as the terminology you are using is a little unclear but here goes. If you have a superclass and a subclass you can hide the methods in the superclass from the subclass by making them private. If you need public methods on the superclass to be invisible you are out of luck. If you cast the subclass to the superclass then the public methods on the subclass are no longer visible.
One suggestion that might help you would be to use composition rather than inheritance, extract the sensitive methods into a separate class and then insert an appropriate instance of that class into the object as needed. You can delegate methods from the class to the injected class if you need to. | Does up casting in Java hide the subclass methods and fields? | [
"",
"java",
"upcasting",
""
] |
I'm doing this application in C# using the free Krypton Toolkit but the Krypton Navigator is a paid product which is rather expensive for me and this application is being developed on my free time and it will be available to the public for free.
**So, I'm looking for a free control to integrate better into my Krypton application because the default one doesn't quite fit and it will be different depending on the OS version...**
Any suggestions?
P.S: I know I could owner-draw it but I'm trying not to have that kind of work... I prefer something already done if it exists for free.
**EDIT:**
I just found exactly what I wanted:
<http://www.angelonline.net/CodeSamples/Lib_3.5.0.zip> | If you need an updated lib with Office 2010 Palettes: <http://www.angelonline.net/CodeSamples/Lib_4.2.0.zip> | My first suggestion would be to talk to Phil at ComponentFactory. I find him to be a very reasonable fellow. Maybe he can give you a special deal or make a design suggestion on how to customize the existing tab control.
But your's is more of a design/subjective question that, I think, would benefit from a screenshot to better communicate the design challenge you need to "integrate better". Saying "the default one doesn't quite fit" is pretty vague.
After that, people will have a better starting point for making suggestions. In the mean time, I would look at [the WindowsClient.NET control gallery](http://windowsclient.net/downloads/folders/controlgallery/default.aspx). | Where can I find a nice .NET Tab Control for free? | [
"",
"c#",
".net",
"winforms",
"tabcontrol",
"krypton",
""
] |
I am creating an application which connects to the server using username/password and I would like to enable the option "Save password" so the user wouldn't have to type the password each time the application starts.
I was trying to do it with Shared Preferences but am not sure if this is the best solution.
I would appreciate any suggestion on how to store user values/settings in Android application. | In general SharedPreferences are your best bet for storing preferences, so in general I'd recommend that approach for saving application and user settings.
The only area of concern here is what you're saving. Passwords are always a tricky thing to store, and I'd be particularly wary of storing them as clear text. The Android architecture is such that your application's SharedPreferences are sandboxed to prevent other applications from being able to access the values so there's some security there, but physical access to a phone could potentially allow access to the values.
If possible I'd consider modifying the server to use a negotiated token for providing access, something like [OAuth](http://code.google.com/p/oauth/). Alternatively you may need to construct some sort of cryptographic store, though that's non-trivial. At the very least, make sure you're encrypting the password before writing it to disk. | I agree with Reto and fiXedd. Objectively speaking it doesn't make a lot of sense investing significant time and effort into encrypting passwords in SharedPreferences since any attacker that has access to your preferences file is fairly likely to also have access to your application's binary, and therefore the keys to unencrypt the password.
However, that being said, there does seem to be a publicity initiative going on identifying mobile applications that store their passwords in cleartext in SharedPreferences and shining unfavorable light on those applications. See <http://blogs.wsj.com/digits/2011/06/08/some-top-apps-put-data-at-risk/> and <http://viaforensics.com/appwatchdog> for some examples.
While we need more attention paid to security in general, I would argue that this sort of attention on this one particular issue doesn't actually significantly increase our overall security. However, perceptions being as they are, here's a solution to encrypt the data you place in SharedPreferences.
Simply wrap your own SharedPreferences object in this one, and any data you read/write will be automatically encrypted and decrypted. eg.
```
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
// eg.
prefs.edit().putString("foo","bar").commit();
prefs.getString("foo", null);
```
Here's the code for the class:
```
/**
* Warning, this gives a false sense of security. If an attacker has enough access to
* acquire your password store, then he almost certainly has enough access to acquire your
* source binary and figure out your encryption key. However, it will prevent casual
* investigators from acquiring passwords, and thereby may prevent undesired negative
* publicity.
*/
public class ObscuredSharedPreferences implements SharedPreferences {
protected static final String UTF8 = "utf-8";
private static final char[] SEKRIT = ... ; // INSERT A RANDOM PASSWORD HERE.
// Don't use anything you wouldn't want to
// get out there if someone decompiled
// your app.
protected SharedPreferences delegate;
protected Context context;
public ObscuredSharedPreferences(Context context, SharedPreferences delegate) {
this.delegate = delegate;
this.context = context;
}
public class Editor implements SharedPreferences.Editor {
protected SharedPreferences.Editor delegate;
public Editor() {
this.delegate = ObscuredSharedPreferences.this.delegate.edit();
}
@Override
public Editor putBoolean(String key, boolean value) {
delegate.putString(key, encrypt(Boolean.toString(value)));
return this;
}
@Override
public Editor putFloat(String key, float value) {
delegate.putString(key, encrypt(Float.toString(value)));
return this;
}
@Override
public Editor putInt(String key, int value) {
delegate.putString(key, encrypt(Integer.toString(value)));
return this;
}
@Override
public Editor putLong(String key, long value) {
delegate.putString(key, encrypt(Long.toString(value)));
return this;
}
@Override
public Editor putString(String key, String value) {
delegate.putString(key, encrypt(value));
return this;
}
@Override
public void apply() {
delegate.apply();
}
@Override
public Editor clear() {
delegate.clear();
return this;
}
@Override
public boolean commit() {
return delegate.commit();
}
@Override
public Editor remove(String s) {
delegate.remove(s);
return this;
}
}
public Editor edit() {
return new Editor();
}
@Override
public Map<String, ?> getAll() {
throw new UnsupportedOperationException(); // left as an exercise to the reader
}
@Override
public boolean getBoolean(String key, boolean defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Boolean.parseBoolean(decrypt(v)) : defValue;
}
@Override
public float getFloat(String key, float defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Float.parseFloat(decrypt(v)) : defValue;
}
@Override
public int getInt(String key, int defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Integer.parseInt(decrypt(v)) : defValue;
}
@Override
public long getLong(String key, long defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Long.parseLong(decrypt(v)) : defValue;
}
@Override
public String getString(String key, String defValue) {
final String v = delegate.getString(key, null);
return v != null ? decrypt(v) : defValue;
}
@Override
public boolean contains(String s) {
return delegate.contains(s);
}
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
protected String encrypt( String value ) {
try {
final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);
} catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected String decrypt(String value){
try {
final byte[] bytes = value!=null ? Base64.decode(value,Base64.DEFAULT) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(pbeCipher.doFinal(bytes),UTF8);
} catch( Exception e) {
throw new RuntimeException(e);
}
}
}
``` | What is the most appropriate way to store user settings in Android application | [
"",
"java",
"android",
"encryption",
"preferences",
"credentials",
""
] |
Specifically, I would like to create an Array class and would like to overload the [] operator. | If you are using PHP5 (and you should be), take a look at the [SPL ArrayObject](https://www.php.net/manual/en/class.arrayobject.php) classes. The documentation isn't too good, but I think if you extend ArrayObject, you'd have your "fake" array.
EDIT: Here's my quick example; I'm afraid I don't have a valuable use case though:
```
class a extends ArrayObject {
public function offsetSet($i, $v) {
echo 'appending ' . $v;
parent::offsetSet($i, $v);
}
}
$a = new a;
$a[] = 1;
``` | Actually, the optimal solution is to implement the four methods of the ArrayAccess interface:
<http://php.net/manual/en/class.arrayaccess.php>
If you would also like to use your object in the context of 'foreach', you'd have to implement the 'Iterator' interface:
<http://www.php.net/manual/en/class.iterator.php> | Is it possible to overload operators in PHP? | [
"",
"php",
"operator-overloading",
""
] |
I have a one-to-one relationship but hibernatetool complains when generating the schema. Here's an example that shows the problem:
```
@Entity
public class Person {
@Id
public int id;
@OneToOne
public OtherInfo otherInfo;
rest of attributes ...
}
```
Person has a one-to-one relationship with OtherInfo:
```
@Entity
public class OtherInfo {
@Id
@OneToOne(mappedBy="otherInfo")
public Person person;
rest of attributes ...
}
```
Person is owning side of OtherInfo. OtherInfo is the owned side so person uses `mappedBy` to specify the attribute name "otherInfo" in Person.
I get the following error when using hibernatetool to generate the database schema:
```
org.hibernate.MappingException: Could not determine type for: Person, at table: OtherInfo, for columns: [org.hibernate.mapping.Column(person)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292)
at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:175)
at org.hibernate.cfg.Configuration.iterateGenerators(Configuration.java:743)
at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:854)
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:128)
...
```
Any idea why? Am I a doing something wrong or is this a Hibernate bug? | JPA doesn't allow the *@Id* annotation on a *OneToOne* or *ManyToOne* mapping. What you are trying to do is one-to-one entity association **with shared primary key**. The simplest case is unidirectional one-to-one with shared key:
```
@Entity
public class Person {
@Id
private int id;
@OneToOne
@PrimaryKeyJoinColumn
private OtherInfo otherInfo;
rest of attributes ...
}
```
The main problem with this is that JPA provides no support for shared primary key generation in *OtherInfo* entity. The classic book [Java Persistence with Hibernate by Bauer and King](https://rads.stackoverflow.com/amzn/click/com/1932394885) gives the following solution to the problem using Hibernate extension:
```
@Entity
public class OtherInfo {
@Id @GeneratedValue(generator = "customForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "customForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "person")
)
private Long id;
@OneToOne(mappedBy="otherInfo")
@PrimaryKeyJoinColumn
public Person person;
rest of attributes ...
}
```
Also, see [here](http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships). | This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:
```
@Entity
public class Person {
@Id
@GeneratedValue
public int id;
@OneToOne
@PrimaryKeyJoinColumn
public OtherInfo otherInfo;
rest of attributes ...
}
@Entity
public class OtherInfo {
@Id
public int id;
@MapsId
@OneToOne
@JoinColumn(name="id")
public Person person;
rest of attributes ...
}
```
More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7. | JPA Hibernate One-to-One relationship | [
"",
"java",
"hibernate",
"jpa",
""
] |
I have a very simple properties file test I am trying to get working: (the following is TestProperties.java)
```
package com.example.test;
import java.util.ResourceBundle;
public class TestProperties {
public static void main(String[] args) {
ResourceBundle myResources =
ResourceBundle.getBundle("TestProperties");
for (String s : myResources.keySet())
{
System.out.println(s);
}
}
}
```
and TestProperties.properties in the same directory:
```
something=this is something
something.else=this is something else
```
which I have also saved as `TestProperties_en_US.properties`
When I run TestProperties.java from Eclipse, it can't find the properties file:
```
java.util.MissingResourceException:
Can't find bundle for base name TestProperties, locale en_US
```
Am I doing something wrong? | Put it at the root level of one of your source paths, or fully qualify the resource name in the call to `getBundle`, e.g.
```
ResourceBundle myResources =
ResourceBundle.getBundle("com.example.test.TestProperties");
```
See the docs for [`ResourceBundle.getBundle(String, Locale, ClassLoader)`](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html) for more information. | Do NOT put your propierties files into your src folder! Obviously that works, but basically this is NOT how you should approach your problems. Create a new folder in your project, for instance a 'Resources' folder, add it to the classpath in project properties and put all files other than .java there. | where to put .properties files in an Eclipse project? | [
"",
"java",
"eclipse",
"properties",
""
] |
I'm trying to regexp a line from a webpage. The line is as follows:
```
<tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
```
This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to import 're'.
```
reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.search(htmlbody)
print 'Value is', value
``` | It sounds like you may want to use `findall` rather than `search`:
```
reg = re.compile("<tr><td width=60 bgcolor='#ffffcc'><b>([^<]*)</b></td><td align=center width=80>")
value = reg.findall(htmlbody)
print 'Found %i match(es)' % len(value)
```
I have to caution you, though, that regular expressions are notoriously poor at handling HTML. You're better off using a proper parser using the [HTMLParser module built in to Python](http://docs.python.org/library/htmlparser.html). | There is no surefire way to do this with a regex. See [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166) for why. What you need is an HTML parser like [HTMLParser](http://docs.python.org/library/htmlparser.html):
```
#!/usr/bin/python
from HTMLParser import HTMLParser
class FindTDs(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.level = 0
def handle_starttag(self, tag, attrs):
if tag == 'td':
self.level = self.level + 1
def handle_endtag(self, tag):
if tag == 'td':
self.level = self.level - 1
def handle_data(self, data):
if self.level > 0:
print data
find = FindTDs()
html = "<table>\n"
for i in range(3):
html += "\t<tr>"
for j in range(5):
html += "<td>%s.%s</td>" % (i, j)
html += "</tr>\n"
html += "</table>"
find.feed(html)
``` | Python Regexp problem | [
"",
"python",
"html",
"regex",
""
] |
I usually do this in Perl:
whatever.pl
```
while(<>) {
#do whatever;
}
```
then `cat foo.txt | whatever.pl`
Now, I want to do this in Python. I tried `sys.stdin` but I have no idea how to do as I have done in Perl. How can I read the input? | Try this:
```
import fileinput
for line in fileinput.input():
process(line)
``` | ```
import sys
def main():
for line in sys.stdin:
print line
if __name__=='__main__':
sys.exit(main())
``` | How do I iterate over all lines of files passed on the command line? | [
"",
"python",
"stdin",
""
] |
I'm working with a legacy WebLogic application that contains a web-service application and a standalone, command-line application. Both need access to a common database and I would like to try and get the command-line application use a pooled connection to the web-server's JDBC connection. (The standalone application can only be run when the server is active and both will be run on the same physical machine.)
I've been trying to use a JNDI lookup to the JDBC driver as follows:
```
try {
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
ctx = new InitialContext(ht);
DataSource ds = (DataSource) ctx.lookup ("dbOracle");
Connection conn = null;
conn = ds.getConnection(); // <-- Exception raised here
// conn = ds.getConnection(username, password); // (Also fails)
// ...
} catch (Exception e) {
// Handle exception...
}
```
I've confirmed the JNDI name is correct. I am able to connect to the database with other web-applications but my standalone application continues to have difficulties. - I got the idea for this from a [WebLogic app note](http://download.oracle.com/docs/cd/E12840_01/wls/docs103/jdbc/programming.html).
Any ideas on what I have overlooked?
**EDIT 1.1:** I'm seeing a "java.lang.ClassCastException: java.lang.Object" exception.
**EDIT 2:** When I perform the following:
```
Object dsObj = ctx.lookup("dbOracle");
System.out.println("Obj was: " + dsObj.getClass().getName());
```
In the standalone-application, it reports:
```
"Obj was: weblogic.jdbc.common.internal._RemoteDataSource_Stub"
```
I attempted to test the same chunk of code (described in original question) in the web-application and was able to connect to the datasource (i.e. it seems to "work"). This working test reports:
```
"Obj was: weblogic.jdbc.common.internal.RmiDataSource"
```
Also, here's a stack-trace for when it's failing:
```
####<Apr 22, 2009 10:38:21 AM EDT> <Warning> <RMI> <mlbdev16> <cgServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1240411101452> <BEA-080003> <RuntimeException thrown by rmi server: weblogic.jdbc.common.internal.RmiDataSource.getConnection()
java.lang.ClassCastException: java.lang.Object.
java.lang.ClassCastException: java.lang.Object
at weblogic.iiop.IIOPOutputStream.writeAny(IIOPOutputStream.java:1584)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2222)
at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:413)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)
at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1957)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1992)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2253)
at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:224)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:479)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:475)
at weblogic.rmi.internal.BasicServerRef.access$300(BasicServerRef.java:59)
at weblogic.rmi.internal.BasicServerRef$BasicExecuteRequest.run(BasicServerRef.java:1016)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
``` | This exception looks like it is generated on the server side. The first thing I would do is verify the version of WebLogic Server and check the classpath of the client application. You need to make sure your client app has the same version of the WebLogic client jar files as the WebLogic Server. You are including weblogic client jar files in the classpath of your client, right? Since your are using WebLogic's RMI driver, I don't believe you need any Oracle jar files in the classpath of the client. Your client is essentially speaking RMI to the WebLogic Server. The WebLogic Server connection pool you configured knows how to speak to Oracle. It shouldn't matter what JDBC driver you use in your connection pool. | Hard to tell what is going on with such limited information.
Did you set the application up as a thin client? When you are not operating within one of the Java EE containers, the context and means of doing lookups does not work the same way (varies by vendor). You may want to research how to do lookups of resources with Weblogic from such a client, as well as how to set it up correctly. | Application using Pooled JDBC Connections | [
"",
"java",
"jdbc",
"weblogic",
"jndi",
""
] |
I'm using the following code in my testing framework:
```
testModules = ["test_foo", "test_bar"]
suite = unittest.TestLoader().loadTestsFromNames(testModules)
runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
results = runner.run(suite)
return results.wasSuccessful()
```
Is there a way to make the reporting (`runner.run`?) abort after the first failure to prevent excessive verbosity? | Nine years after the question was asked, this is still one of the top search results for "python unit test fail early" and, as I discovered when looking at the other search results, these answers are no longer correct for more recent versions of the unittest module.
The documentation for the unittest module <https://docs.python.org/3/library/unittest.html#command-line-options> and <https://docs.python.org/2.7/library/unittest.html#command-line-options> show that there is an argument, failfast=True, that can be added to unittest.main, or equivalently a command line option, -f, or --failfast, to stop the test run on the first error or failure. This option was added in version 2.7. Using that option is a lot easier than the previously-necessary workarounds suggested in the other answers.
That is, simply change your
```
unittest.main()
```
to
```
unittest.main(failfast=True)
``` | Based on Eugene's guidance, I've come up with the following:
```
class TestCase(unittest.TestCase):
def run(self, result=None):
if result.failures or result.errors:
print "aborted"
else:
super(TestCase, self).run(result)
```
While this works fairly well, it's a bit annoying that each individual test module has to define whether it wants to use this custom class or the default one (a command-line switch, similar to `py.test`'s `--exitfirst`, would be ideal)... | PyUnit: stop after first failing test? | [
"",
"python",
"unit-testing",
""
] |
In other words could it be possible to create assembly, which does not even compile (assuming the checking code is not removed ) if each one of the Classes does not have ( "must have" ) custom attributes ( for example Author and Version ) ?
Here is the code I have used for querying during run time :
```
using System;
using System.Reflection;
using System.Collections.Generic;
namespace ForceMetaAttributes
{
[System.AttributeUsage ( System.AttributeTargets.Method, AllowMultiple = true )]
class TodoAttribute : System.Attribute
{
public TodoAttribute ( string message )
{
Message = message;
}
public readonly string Message;
}
[System.AttributeUsage ( System.AttributeTargets.Class |
System.AttributeTargets.Struct, AllowMultiple = true )]
public class AttributeClass : System.Attribute
{
public string Description { get; set; }
public string MusHaveVersion { get; set; }
public AttributeClass ( string description, string mustHaveVersion )
{
Description = description;
MusHaveVersion = mustHaveVersion ;
}
} //eof class
[AttributeClass("AuthorName" , "1.0.0")]
class ClassToDescribe
{
[Todo ( " A todo message " )]
static void Method ()
{ }
} //eof class
//how to get this one to fail on compile
class AnotherClassToDescribe
{
} //eof class
class QueryApp
{
public static void Main()
{
Type type = typeof(ClassToDescribe);
AttributeClass objAttributeClass;
//Querying Class Attributes
foreach (Attribute attr in type.GetCustomAttributes(true))
{
objAttributeClass = attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of AnyClass:\n{0}",
objAttributeClass.Description);
}
}
//Querying Class-Method Attributes
foreach(MethodInfo method in type.GetMethods())
{
foreach (Attribute attr in method.GetCustomAttributes(true))
{
objAttributeClass = attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of {0}:\n{1}",
method.Name,
objAttributeClass.Description);
}
}
}
//Querying Class-Field (only public) Attributes
foreach(FieldInfo field in type.GetFields())
{
foreach (Attribute attr in field.GetCustomAttributes(true))
{
objAttributeClass= attr as AttributeClass;
if (null != objAttributeClass)
{
Console.WriteLine("Description of {0}:\n{1}",
field.Name,objAttributeClass.Description);
}
}
}
Console.WriteLine ( "hit Enter to exit " );
Console.ReadLine ();
} //eof Main
} //eof class
} //eof namespace
//uncomment to check whether it works with external namespace
//namespace TestNamespace {
// class Class1 { }
// class Class2 { }
//}
```
Edit: Just to justify my choice for answer.
I think casperOne provided the correct answer of the question.
However the reasons for asking the question seemed to be [weak](https://stackoverflow.com/questions/753255/is-it-possible-to-query-custom-attributes-in-c-during-compile-time-not-run-tim/753301#753301). Probably I should start to use some external tool such as :
[FinalBuilder](http://www.finalbuilder.com/Demos/FinalBuilder_basic_viewlet_swf.html)
or create unit tests checking for this "requirement", using Pex , Nunit or other unit testing frameworks ...
**EDIT**
I added a small [code snippet](https://stackoverflow.com/questions/753255/is-it-possible-to-query-custom-attributes-in-c-during-compile-time-not-run-tim/763010#763010) of a console program at the end of the answers that performs the check ... feel free to comment, criticize or suggest improvements
Once more I realized that this "requirement" should be implemented as part of the unit testing just before the "check in" | No, it is not possible to hook into the compilation of the assembly and check if it exists.
*However* you can hook into the build process, which is made up of more than just running the compiler. You could create a custom MSBUILD task (or NAnt, if you are using that) which checks the assembly through reflection after it is built and then fail the build if it doesn't have the required attributes.
Of course, you should probably *still* verify this in code as well. What you are trying to do is not a good substitute for a proper runtime check. | You can run a post-build step that reflects on the DLL to do what you want.
You will have to write a command-line app that loads the DLL and reflects on the types. You then run that command-line app as a post-build step. I have done this in the past. It is not terribly difficult to do, assuming you understand the reflection API.
[PostSharp](http://www.postsharp.org/) does this to achieve aspect oriented programming. Pretty cool, actually. | Is it possible to query custom Attributes in C# during compile time ( not run-time ) | [
"",
"c#",
"custom-attributes",
""
] |
Let me just start out by saying I am completely new to Java web apps, so I'm sorry if this is a very basic question.
I am writing an app that has the ability for users to login to an account. The top part of each page contains an info bar (kind of like the top bar in GMail) with something like:
```
Logged in as <userid> | Settings | Help
```
Since that part is going to be on every page, it makes sense to me to split that functionality out so I do not duplicate my code.
I did some searching, and found that I could use this:
```
<jsp:include page="userInfoBar.jsp" flush="true" />
```
in the middle of another JSP. I got into problems for my userSettings.jsp page though, which also gets some User detail from the database. Not only am I duplicating some code between the 2 JSPs, but I have a feeling that I am doing double the work during the render of the web page.
For example (Pseudo code):
```
userInfoBar.jsp:
user = getCurrentUser
if ( user ) {
print Logged in as user.userid | Settings | Help
}
userSettings.jsp:
<jsp:include page="userInfoBar.jsp" flush="true" />
user = getCurrentUser
Change settings for user.userid
```
So in that little example, getCurrentUser gets called twice (I think, unless Java somehow optimizes that).
How can I avoid this duplication of work, but still keep the userInfoBar somewhat separate from each JSP?
Thanks in advance!
Brian | The problem is that you have java code in your JSPs. Most evil things happen when you do that. You should look up the MVC pattern on google.
Anyway, the good way to do this would be to use the MVC pattern, and do your heavy lifting in the controller, after the heavy lifting is done, you can pass the strings/lists to display the view, which displays them and NOTHING MORE.
Also, if you start using MVCs with JSTL, a lot more people will be able to help you, because everyone knows how to do that stuff, and hopefully not many people still do inline java in their JSPs | Try using [JSF](http://java.sun.com/javaee/javaserverfaces/). This allows for easy implementation of MVC.
You can point two front-ends to the same session-scoped bean to get user information. | How do I include jsp pages in a Java web app without duplicating code? | [
"",
"java",
"jsp",
"include",
""
] |
I want to add an xml:base declaration to an xml file in java. I currently have the xml output in an OutputStream that was generated by some third party code.
The file starts out like this:
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns="http://www.mycompany.com/myNS#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
```
And I want it to look like this:
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns="http://www.mycompany.com/myNS#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xml:base="http://www.mycompany.com/myNS">
```
I must be having a brain fart or something, because I can't think of a good way to do this pragmatically.
Any ideas? | The ByteArrayInputStream won't scale for large files, and I didn't like the idea of using a temp file. I also thought it was overkill to load the whole file into the DOM just to add the `xml:base` tag.
Here's an alternate solution using pipes and a simple hand rolled parsing code to add the tag.
```
PipedInputStream pipedInput = new PipedInputStream();
PipedOutputStream pipedOutput = new PipedOutputStream(pipedInput);
new Thread(new ModelExportThread(model, pipedOutput)).start();
int bufferSize = 1024;
byte[] bytes = new byte[bufferSize];
StringBuffer stringBuffer = new StringBuffer();
int bytesRead = pipedInput.read(bytes, 0, bufferSize);
boolean done = false;
String startRDF = "<rdf:RDF";
while (bytesRead > 0) {
if (!done) {
stringBuffer.append(new String(bytes, 0, bytesRead));
int startIndex = stringBuffer.indexOf(startRDF);
if ((startIndex >= 0)) {
stringBuffer.insert(startIndex + startRDF.length(), " xml:base=\"" + namespace + "\"");
outputStream.write(stringBuffer.toString().getBytes());
stringBuffer.setLength(0);
done = true;
}
} else {
outputStream.write(bytes, 0, bytesRead);
}
bytesRead = pipedInput.read(bytes, 0, bufferSize);
}
outputStream.flush();
```
Here's the threaded code to write to the output pipe.
```
public class ModelExportThread implements Runnable {
private final OntModel model;
private final OutputStream outputStream;
public ModelExportThread(OntModel model, OutputStream outputStream) {
this.model = model;
this.outputStream = outputStream;
}
public void run() {
try {
model.write(outputStream, "RDF/XML-ABBREV");
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(OntologyModel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
``` | You can change the `xml:base` used in RDF/XML serialization by obtaining the appropriate RDFWriter and setting its `xmlbase` property to your chosen `xmlbase`. The following code reads a model from a string (the important part of this question is about how to write the model, not where it comes frm) and then writes it in RDF/XML twice, each time with a different `xml:base`.
```
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFWriter;
public class ChangeBase {
public static void main(String[] args) throws IOException {
final String NS = "http://example.org/";
final String text = "" +
"@prefix ex: <"+NS+">.\n" +
"ex:foo a ex:Foo .\n" +
"ex:foo ex:frob ex:bar.\n";
final Model model = ModelFactory.createDefaultModel();
try ( final InputStream in = new ByteArrayInputStream( text.getBytes() )) {
model.read( in, null, "TTL" );
}
// get a writer for RDF/XML-ABBREV, set its xmlbase to the NS, and write the model
RDFWriter writer = model.getWriter( "RDF/XML-ABBREV" );
writer.setProperty( "xmlbase", NS );
writer.write( model, System.out, null );
// change the base to example.com (.com, not .org) and write again
writer.setProperty( "xmlbase", "http://example.com" );
writer.write( model, System.out, null );
}
}
```
The output is (notice that in the first case, the base is `htttp://example.org/` and in the second, it's `http://example.com` (the difference is .org vs. .com):
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:ex="http://example.org/"
xml:base="http://example.org/">
<ex:Foo rdf:about="foo">
<ex:frob rdf:resource="bar"/>
</ex:Foo>
</rdf:RDF>
```
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:ex="http://example.org/"
xml:base="http://example.com">
<ex:Foo rdf:about="http://example.org/foo">
<ex:frob rdf:resource="http://example.org/bar"/>
</ex:Foo>
</rdf:RDF>
``` | add xml:base to xml file in java | [
"",
"java",
"xml",
"jena",
""
] |
I would like to write a program that sets an environment variable in an instance of the shell (cmd.exe) it was called from. The idea is that I could store some state in this variable and then use it again on a subsequent call.
I know there are commands like SetEnvironmentVariable, but my understanding is that those only change the variable for the current process and won't modify the calling shell's variables.
Specifically what I would like to be able to do is create a command that can bounce between two directories. Pushd/Popd can go to a directory and back, but don't have a way of returning a 2nd time to the originally pushed directory. | A common techniques is the write an env file, that is then "call"ed from the script.
```
del env.var
foo.exe ## writes to env.var
call env.var
``` | [MSDN states the following](http://msdn.microsoft.com/en-us/library/ms682653(VS.85).aspx):
> Calling `SetEnvironmentVariable` has no
> effect on the system environment
> variables. To programmatically add or
> modify system environment variables,
> add them to the
> `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
> Manager\Environment` registry key, then
> broadcast a `WM_SETTINGCHANGE` message
> with `lParam` set to the string
> "Environment". This allows
> applications, such as the shell, to
> pick up your updates. Note that the
> values of the environment variables
> listed in this key are limited to 1024
> characters.
Considering that there are two levels of environment - System and Process - changing those in the shell would constitute changing the environment of another process. I don't believe that this is possible. | How can I change Windows shell (cmd.exe) environment variables from C++? | [
"",
"c++",
"windows",
"cmd",
"environment-variables",
""
] |
the line "if(arg2 & 1)" in C++(arg2 is DWORD) is equal to "if(arg2 & 1==0)" in C#(arg2 is Uint32),right?
I am trying to translate a function from C++ to C#,but I get an error:
```
Operator '&' cannot be applied to operands of type 'uint' and 'bool'
```
I'd be also thankful if you could see further in the whole function for any other mistakes.
C++
```
DWORD Func_X_4(DWORD arg1, DWORD arg2, DWORD arg3)
{
LARGE_INTEGER result = {1, 0};
LARGE_INTEGER temp1 = {0};
LARGE_INTEGER temp2 = {0};
LARGE_INTEGER temp3 = {0};
LARGE_INTEGER temp4 = {0};
for(int x = 0; x < 32; ++x)
{
if(arg2 & 1)
{
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp2.QuadPart = temp1.QuadPart * result.QuadPart;
temp3.LowPart = arg1;
temp3.HighPart = 0;
temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
result.QuadPart = temp4.QuadPart;
}
arg2 >>= 1;
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp1.QuadPart *= temp1.QuadPart;
temp2.LowPart = arg1;
temp2.HighPart = 0;
temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
arg3 = temp3.LowPart;
if(!arg2)
break;
}
return result.LowPart;
}
```
Converted to C#
LARGE\_INTEGER structure:
```
[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct LARGE_INTEGER
{
[FieldOffset(0)]
public Int64 QuadPart;
[FieldOffset(0)]
public UInt32 LowPart;
[FieldOffset(4)]
public Int32 HighPart;
}
```
Function:
```
public static UInt32 X4(UInt32 arg1, UInt32 arg2, UInt32 arg3)
{
LARGE_INTEGER result = new LARGE_INTEGER();
result.LowPart = 1;
result.HighPart = 0;
LARGE_INTEGER temp1 = new LARGE_INTEGER();
LARGE_INTEGER temp2 = new LARGE_INTEGER();
LARGE_INTEGER temp3 = new LARGE_INTEGER();
LARGE_INTEGER temp4 = new LARGE_INTEGER();
for (int x = 0; x < 32; ++x)
{
if (arg1 & 1 ==0)
{
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp2.QuadPart = temp1.QuadPart * result.QuadPart;
temp3.LowPart = arg1;
temp3.HighPart = 0;
temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
result.QuadPart = temp4.QuadPart;
}
arg2 >>= 1;
temp1.LowPart = arg3;
temp1.HighPart = 0;
temp1.QuadPart *= temp1.QuadPart;
temp2.LowPart = arg1;
temp2.HighPart = 0;
temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
arg3 = temp3.LowPart;
if (arg2==0)
break;
}
return result.LowPart;
}
```
This is what I'm not sure yet:
1. Whether a DWORD in C++ is UInt32 or Int32 in C#?
2. if(integer & integer) means if(integer and integer ==0)? //this is where the error i described above is placed.
3. if(!integer) means if(integer != 0)?
4. Why operator & cannot be used logically in C# ,meaning it requires a boolean?
5. "LARGE\_INTEGER result = {1, 0}" means result.lowpart is 1 and result.highpart is 0 or result.Quadpart = 1?
Thanks in advance! | Where you write :
if (arg1 & arg2==0)
The compiler understands :
```
if (arg1 & (arg2==0))
```
You should write :
```
if ((arg1 & arg2) == 0)
```
This is the way the C++ statement should be translated to C# :
```
if (arg2 & 1) // C++ (arg2 is DWORD)
if ((arg2 & 1) != 0) // C# (arg2 is Uint32)
```
Or, in a more generic way:
```
if (Flags & FlagToCheck) // C++
if ((Flags & FlagToCheck) != 0) // C#
```
---
In C/C++, 0 is false, everything else is true.
1. You should check the definition of DWORD, it should be (unsigned int), which is UInt32 in C#
2. if (integer & integer), in C/C++ means "if the result of the bitwise and between the two integers is not 0" (0 is false, everything else is true).
3. if (!integer) means if (integer == 0) (again, 0 is false, everything else is true)
4. in C#, like in Java I think, booleans and numbers are two different things, you can only use booleans in "if" statements, there is not implicit conversion if you use an int : it won't compile.
5. I'll leave this one to someone else, I'd need to test to be sure... | 1. `DWORD` is `uint32_t` in C++, thus `UInt32` in C#.
2. `if(a & b)` converts to `if((a & b) != 0)`. `!=` is evaluated before `&` thus the `&` expression needs parentheses around it.
3. `if(x)` converts to `if(x != 0)`
4. `&` is a 'bitwise and' in C#, like in C++.
5. Depends on your C++ structure. | How to use the & operator in C#? Is the the translation of the code correct? | [
"",
"c#",
"operators",
"bitwise-operators",
"conditional-statements",
""
] |
In another Bruce Eckels exercise in calculating velocity, `v = s / t` where s and t are integers. How do I make it so the division cranks out a float?
```
class CalcV {
float v;
float calcV(int s, int t) {
v = s / t;
return v;
} //end calcV
}
public class PassObject {
public static void main (String[] args ) {
int distance;
distance = 4;
int t;
t = 3;
float outV;
CalcV v = new CalcV();
outV = v.calcV(distance, t);
System.out.println("velocity : " + outV);
} //end main
}//end class
``` | Just cast one of the two operands to a float first.
```
v = (float)s / t;
```
The cast has higher [precedence](https://introcs.cs.princeton.edu/java/11precedence/) than the division, so happens before the division.
The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. [Java Language Specification, §4.2.4](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.4) and [§15.17](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17) | Try:
```
v = (float)s / (float)t;
```
Casting the ints to floats will allow floating-point division to take place.
You really only need to cast one, though. | How to make the division of 2 ints produce a float instead of another int? | [
"",
"java",
""
] |
EDIT: Issue solved, answered it below. Lame error. Blah
So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback:
<http://dpaste.com/37391/> - This happens on any page I try to go to.
I've modified my urls.py to include the admin in the new method:
> from django.contrib import admin
>
> admin.autodiscover()
>
> .... urlpatterns declaration
>
> (r'^admin/', include(admin.site.urls)),
I've tried fidgeting with paths and the like but nothing fixes my problem and I can't figure it out.
Has something major changed since Django 1.1 alpha -> Django 1.1 beta that I am missing? Apart from the admin I can't see what else is new. Are urls still stored in a urls.py within each app?
Thanks for the help in advance, this is beyond frustrating. | I figured it out. I was missing a urls.py that I referenced (for some reason, SVN said it was in the repo but it never was fetched on an update) and it simply said could not find urls (with no reference to notes.urls which WAS missing) so it got very confusing.
Either way, fixed -- Awesome! | Try this:
```
(r'^admin/(.*)', admin.site.root),
```
[More info](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Mergednewforms-adminintotrunk) | Django blows up with 1.1, Can't find urls module | [
"",
"python",
"django",
"django-1.1",
""
] |
I'm trying to validate that a parameter is both an out parameter and extends an interface (ICollection). The reflection api doesn't seem to want to give me the "real" type of the parameter, only the one with an "&" at the end which will not evaluate correctly in an IsAssignableFrom statement. I've written some c# code that works but it seems like there should be a better way to do this.
```
bool isCachedArg(ParameterInfo pInfo)
{
if (!pInfo.IsOut)
return false;
string typeName = pInfo.ParameterType.FullName;
string nameNoAmpersand = typeName.Substring(0, typeName.Length - 1);
Type realType = Type.GetType(nameNoAmpersand);
if (!typeof(ICollection).IsAssignableFrom(realType))
return false;
return true;
}
```
Is there a way to get realType without reloading the Type from its string name? I'm still on .NET 2.1.
Thanks,
Randy | An `out` parameter is "by ref" - so you'll find `pInfo.ParameterType.IsByRef` returns true. To get the underlying not-by-ref type, call `GetElementType()`:
```
Type realType = pInfo.ParameterType.GetElementType();
```
(You should only do that if it *is* by ref, of course. This applies for `ref` parameters too.) | Is pInfo.ParameterType not the type you are looking for ?
According to docs, the ParamterType property of the PropertyInfo class is:
["*The Type object that represents the Type of this parameter.*"](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.parametertype.aspx)
Also, the following code gives the expected output:
```
Type t = typeof (X);
var mi = t.GetMethod("Method");
var parameters = mi.GetParameters();
foreach(Type parameterType in parameters.Select(pi => pi.ParameterType))
Console.WriteLine(parameterType.IsByRef ? parameterType.GetElementType() : parameterType);
```
**Edit:** As John Skeet points out, if the parameter is by ref; you should use GetElementType to get the correct type. I updated the code sample. | .NET Reflection - How to get "real" type from out ParameterInfo | [
"",
"c#",
".net",
"reflection",
""
] |
A new feature in C# / .NET 4.0 is that you can change your enumerable in a `foreach` without getting the exception. See Paul Jackson's blog entry *[An Interesting Side-Effect of Concurrency: Removing Items from a Collection While Enumerating](https://web.archive.org/web/20160308065012/www.lovethedot.net/2009/03/interesting-side-effect-of-concurrency.html)* for information on this change.
What is the best way to do the following?
```
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable)
{
item.Add(new item2)
}
}
```
Usually I use an `IList` as a cache/buffer until the end of the `foreach`, but is there better way? | The collection used in foreach is immutable. This is very much by design.
As it says on [MSDN](http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx):
> The foreach statement is used to
> iterate through the collection to get
> the information that you want, but can
> not be used to add or remove items
> from the source collection to avoid
> unpredictable side effects. **If you
> need to add or remove items from the
> source collection, use a for loop.**
The post in the [link](http://www.lovethedot.net/2009/03/interesting-side-effect-of-concurrency.html) provided by Poko indicates that this is allowed in the new concurrent collections. | Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.
```
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable.ToList())
{
item.Add(item2)
}
}
``` | What is the best way to modify a list in a 'foreach' loop? | [
"",
"c#",
".net",
"list",
"enumeration",
"enumerable",
""
] |
I'm rather new to Java. After just reading some info on path finding, I read about using an empty class as an "`interface`", for an unknown object type.
I'm developing a game in Java based on hospital theme. So far, the user can build a reception desk and a GP's office. They are two different types of object, one is a `Building` and one is a `ReceptionDesk`. (In my class structure.)
My class structure is this:
```
GridObject-->Building
GridObject-->Item-->usableItem-->ReceptionDesk.
```
The problem comes when the usable item can be rotated and the building cannot. The mouse click event is on the grid, so calls the same method. The GP's office is a `Building` and the reception desk is a `ReceptionDesk`. Only the `ReceptionDesk` has the method `rotate`. When right clicking on the grid, if in building mode, I have to use this "if" statement:
```
if (currentBuilding.getClass.equals(ReceptionDesk.getClass)
```
I then have to create a new `ReceptionDesk`, use the `rotate` method, and the put that
reception desk back into the `currentBuilding GridObject`.
I'm not sure if I'm explaining myself very well with this question. Sorry. I am still quite new to Java. I will try to answer any questions and I can post more code snippits if need be. I didn't know that there might be a way around the issue of not knowing the class of the object, however I may also be going about it the wrong way.
I hadn't planned on looking into this until I saw how fast and helpful the replies on this site were! :)
Thanks in advance.
Rel | You don't want to check the class of an object before doing something with it in your case. You should be using [polymorphism](http://www.uweb.ucsb.edu/~cdecuir/Polymorphism.html). You want to have the Interface define some methods. Each class implement those methods. Refer to the object by its interface, and have the individual implementations of those objects return their values to the caller.
If you describe a few more of the objects you think you need, people here will have opinions on how you should lay them out. But from what you've provided, you may want a "Building" interface that defines some general methods. You may also want a "UsableItem" interface or something more generic. Hospital could be a class that implements building. ReceptionDesk could implement UsableItem. Building could have a grid of UsableItem inside it.
If rotate() was a common method to all furniture that actually did some work, you may consider making an AbstractUsableItem class that was an abstract class implementing UsableItemand providing the rotate() method. If rotate was different in each implementing class, you would have that method in the interface, but each class, like ReceptionDesk would do its own thing with the rotate() method. Your code would do something like:
```
UsableItem desk = new ReceptionDesk();
desk.rotate()
```
In your example, if your mouse click on a screen rotated the object under it, and you really did need to check to see if the object could be rotated before doing something like that, you'd do
```
if (clickedObject instanceOf UsableItem) {
((UsableItem) clickedObject).rotate();
}
```
where UsableItem was the interface or abstract class. Some people feel that all design should be done via an interface contract and suggest an interface for every type of class, but I don't know if you have to go that far. | You might consider moving in a totally different direction and having the objects themselves decide what kind of action to take. For example, the GridObject interface might specify function declarations for handleRightClick(), handleLeftClick(), etc. What you'd be saying in that case is "any class who calls themselves a GridObject needs to specify what happens when they are right-clicked".
So, within the Building class, you might implement handleRightClick to do nothing (or to return an error). Within the ReceptionDesk class, you would implement handleRightClick to rotate the desk.
Your code snippet would then become:
```
currentBuilding.handleRightClick(... any necessary parameters ...);
``` | Would this be the correct place to use the java keyword "interface"? | [
"",
"java",
"interface",
"keyword",
""
] |
Hopefully someone can help us as we're reaching as far as investigation can go!
We've got a simple asynchronous socket server written in C# that accepts connections from an ASP.NET web application, is sent a message, performs some processing (usually against a DB but other systems too) and then sends a response back to the client. The client is in charge of closing the connection.
We've been having issues where if the system is under heavy load over a long period of time (days usually), CLOSE\_WAIT sockets build up on the server box (netstat -a) to an extent that the process will not accept any further connections. At that point we have to bounce the process and off it runs again.
We've tried running some load tests of our ASP.NET application to attempt to replicate the problem (because inferring some issue from the code wasn't possible). We think we've managed this and ended up with a WireShark [packet trace](http://drop.io/close_wait3793) of the issue manifesting itself as a SocketException in the socket server's logs:
> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
> at System.Net.Sockets.Socket.BeginSend(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
I've tried to reproduce the issue from the packet trace as a single threaded process directly talking to the socket server (using the same code the ASP.NET app does) and am unable.
Has anybody got any suggestions of next things to try, check for or obvious things we may be doing wrong? | Look at the diagram
```
http://en.wikipedia.org/wiki/File:Tcp_state_diagram_fixed.svg
```
Your client closed the connection by calling close(), which sent FIN to the server socket, which ACKed the FIN and the state of which now changed to CLOSE\_WAIT, and stays that way unless the server issues close() call on that socket.
Your server program needs to detect whether the client has aborted the connection, and then close() it immediately to free up the port. How? Refer to read(). Upon reading end-of-file (meaning FIN is received), zero is returned. | If your server is accumulating `CLOSE_WAIT` sockets then it's not closing its socket when the connection is complete. If you take a look at the state diagram in the comment to Chris' post you'll see that `CLOSE_WAIT` transitions to `LAST_ACK` once the socket is closed and the `FIN` has been sent.
You say that it's complex to determine where to do this due to the async nature? This shouldn't be a problem, you should close the socket if the callback from your recv returns 0 bytes (assuming you have nothing else to do once your client closes its side of the connection). If you do need to worry about continuing to send then do a Shutdown(recv) here and make a note that your client has closed, once you're done sending do a Shutdown(send) and a Close.
You MAY be issuing a new read in the callback from the read which returns 0 indicating that the client has closed and this may be causing you problems? | TCP Socket Server Builds Up CLOSE_WAITs Occasionally Over Time Until Inoperable | [
"",
"c#",
"performance",
"sockets",
"crash",
"wireshark",
""
] |
I need to rename a file in the IsolatedStorage. How can I do that? | There doesn't appear to anyway in native C# to do it (there might be in native Win32, but I don't know).
What you could do is open the existing file and copy it to a new file and delete the old one. It would be slow compared to a move, but it might be only way.
```
var oldName = "file.old"; var newName = "file.new";
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))
using (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))
using (var reader = new StreamReader(readStream))
using (var writer = new StreamWriter(writeStream))
{
writer.Write(reader.ReadToEnd());
}
``` | In addition to the copy to a new file, then delete the old file method, starting with Silverlight 4 and .NET Framework v4, IsolatedStorageFile exposes MoveFile and MoveDirectory methods. | Rename File in IsolatedStorage | [
"",
"c#",
"isolatedstorage",
""
] |
In a function is there a way to get a reference to the object that called it? I have the same instance of a Flash object on the page twice, each one can make calls to JS through ExternalInterface, I cannot code the Flash objects to each pass a different ID because it is 2 instances of the same Flash object, so it there a way for JS to get a reference to which one called the function?
Thanks! | Can't you pass an ID to the Flash object when you instantiate it? (via a query string or params). Then you could use that ID in your JavaScript function calls. | I don't know about ExternalInterface but have you tried examine the `this` object during the execution of your function?
Of course you could always use a closure. Ultimately you have to give the Flash object a function to be executed. For example I have `myObj1` and `myObj2` that take a callback method `fnCallback` but for some reason does not set the `this` context when executing this functions to themselves. Hence I can do this:-
```
function setCallback(obj, fn)
{
obj.callback = function() {fn.apply(obj, arguments);}
}
setCallback(myObj1, fnCallback);
setCallback(myObj2, fnCallback);
```
Now I can code fnCallback using `this` as a reference to the specific object that is calling the function. | JS: Is there a way to tell what object called a function? | [
"",
"javascript",
""
] |
How do I programmatically get the revision description and author from the SVN server in c#? | Using [SharpSvn](http://sharpsvn.net/):
```
using(SvnClient client = new SvnClient())
{
Collection<SvnLogEventArgs> list;
// When not using cached credentials
// c.Authentication.DefaultCredentials = new NetworkCredential("user", "pass")l
SvnLogArgs la = new SvnLogArgs { Start = 128, End = 132 };
client.GetLog(new Uri("http://my/repository"), la, out list);
foreach(SvnLogEventArgs a in list)
{
Console.WriteLine("=== r{0} : {1} ====", a.Revision, a.Author);
Console.WriteLine(a.LogMessage);
}
}
``` | You will need to find a C# SVN API to use. A quick Google search found [SharpSVN](http://sharpsvn.open.collab.net/).
To get message and author for specific revision
```
SvnClient client = new SvnClient();
SvnUriTarget uri = new SvnUriTarget("url", REV_NUM);
string message, author;
client.GetRevisionProperty(uri, "svn:log", out message);
client.GetRevisionProperty(uri, "svn:author", out author);
``` | How to programmatically get SVN revision description and author in c#? | [
"",
"c#",
"svn",
""
] |
I want to add a button to one of our web sites that will allow the user to file a bug with our bug tracking system.
One of the feature requests is that a screen cap of the page in question be sent along.
Without installing something on the end users machine, how can I do this? Does javascript have some sort of screen cap api? | You may grab the `innerHTML` of the page and then process it on the server:
```
document.getElementsByTagName('html')[0].innerHTML;
// this would also be interactive (i.e. if you've
// modified the DOM, that would be included)
``` | No, javascript does not have anything like this.
I'm afraid that this will be quite hard. I can not think anything that would do this without installing on users computer.
I'd like to be proven wrong, but atleast this is an answer for you. | How to take a screen shot of a web page? | [
"",
"javascript",
"screen",
"capture",
""
] |
How do I execute a string containing Python code in Python?
---
Editor's note: [**Never use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) If you are here because you want to create multiple variables in your Python program following a pattern, **you almost certainly have an [XY problem](https://xyproblem.info)**. Do not create those variables at all - instead, [use a list or dict appropriately](https://stackoverflow.com/questions/1373164). | In the example a string is executed as code using the exec function.
```
import sys
import StringIO
# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()
code = """
def f(x):
x = x + 1
return x
print 'This is my output.'
"""
# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr
exec code
# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print f(4)
s = codeErr.getvalue()
print "error:\n%s\n" % s
s = codeOut.getvalue()
print "output:\n%s" % s
codeOut.close()
codeErr.close()
``` | For statements, use [`exec(string)`](https://docs.python.org/library/functions.html#exec) (Python 3) or [`exec string`](https://docs.python.org/2/reference/simple_stmts.html#grammar-token-exec-stmt) (Python 2):
```
>>> my_code = 'print("Hello world")'
>>> exec(my_code)
Hello world
```
When you need the value of an expression, use [`eval(string)`](http://docs.python.org/library/functions.html#eval):
```
>>> x = eval("2+2")
>>> x
4
```
However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs. | How do I execute a string containing Python code in Python? | [
"",
"python",
"string",
"exec",
""
] |
I'v e built a basic DAL which can retrieve data and a businesslayer with several objects using this DAL. Once I mapped the data into the business objects and done something with it, I also want to write the data back to the database. Some of the business objects have a lot of properties, so passing every value of a business object as parameter to a method of the corresponding dataservice is not a possibility.
Other ways I've been thinking of:
1. pass the business object to the the corresponding data service, there execute a SP with all the values as parameters. - sucks, because I have to pass a business object to the DAL (violating the separation) and probably end up with SPs with >50 parameters
2. create an empty (?) dataset within the business object, fill it with the values from the business object, pass that dataset to the data service and update the db via a dataadapter. I thought of creating an empty dataset with a "... WHERE 0"-SQL String. Would that be a good practice?
This is the first time I do something like this. The latter sounds better to me, but maybe there are other, better approaches? Or The first one is better for some reasons I don't know?
Thank you very much!
[edit:] I can't use LinQ2SQL, cuz I use C# Express (which only supports querying local DBs, while mine is a remote one) | Pass your object into your DAL. If your writting the DAL layer manually your DAL layer should know how to take an Entity and persist it to the DB, and how to return an Entity from the database. The DAL is about persistance of your entities to a non-volatile medium. | You haven't mentioned using LINQ. Is that because you're not using .NET 3.5 yet?
Also, you don't have to make your DAL that generic. The callers of your DAL aren't trying to update all properties of the business object, are they? They probably want to update parts of it, so you should present an API that does this. For instance, they might just want to add an address to a Contact object, or possibly even update a phone number. You need to have a tradeoff between doing what the caller is really trying to do, and the number of separate methods you'd need in order to do that. | update DB from layered architecture: best approach? | [
"",
"c#",
"database",
"data-access-layer",
""
] |
I've overridden Equals and GetHashCode in an abstract base class to implement value equality based on an object's key property. My main purpose is to be able to use the Contains method on collections instead of Find or FirstOrDefault to check if an instance has already been added to a collection.
```
public abstract class Entity
{
public abstract Guid Id { get; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj.GetType() != GetType())
{
return false;
}
var entity = (Entity)obj;
return (entity.Id == Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
```
The problem with this approach is that all my objects are equal before they've been persisted and acquired an Id (generated by NHibernate). Am I doing it wrong? I could generate the Id in the constructor, but I would like to implement the same pattern for other projects that use int ids, so that obviously won't work.
It seems to me that any object that overrides Equals will be equal to any other instance of the same object immediately after the objects have been instantiated.
**Edited to add:**
Here's the scenario that concerns me: In the Add method for my collections, I am checking to make sure that the collection does not already contain the object to be added. If all new'ed up objects are equal, then I can never add two new objects to the collection. | NHibernate gurantees that object reference identity of entities assocciated with the same context is the same as database identity. So there is no need to override Equals() and GetHashCode(), because this is the same identity you want to implement.
See `10.3. Considering object identity` of the [NHibernate Reference Documentation](http://www.hibernate.org/hib_docs/nhibernate/nhibernate_reference.pdf).
Further, assocciating a new entity using database generated keys with a context should immideatly persist the entity to the database and set the key of the entity to the generated key. | You should obtain your ID, or at least some sort of identificator, in the constructor.
If the ID is not set (or is the default value); obviously the Equals method will return true for any object of the same type (that also has not set the ID). | Value equality comparisons on new objects | [
"",
"c#",
".net",
"oop",
"domain-driven-design",
""
] |
I have a very large number I need to calculate, and none of the inbuilt datatypes in C# can handle such a large number.
Basicly I want to solve this:
**Project Euler 16:**
> 2^15 = 32768 and the sum of its digits
> is 3 + 2 + 7 + 6 + 8 = 26.
>
> What is the sum of the digits of the
> number 2^1000?
I have already written the code, but, as said before, the number is too large for c# datatypes. The code has been tested and verified with small numbers (such as 2^15) and it works perfectly.
```
using System;
namespace _16_2E1000
{
class Program
{
static void Main(string[] args)
{
ulong sum = 0;
ulong i = 1 << 1000;
string s = i.ToString();
foreach (char c in s)
{
sum += (ulong) Convert.ToInt64(c.ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
``` | You can use BigInteger from the J# classes. [First question in this article](http://msdn.microsoft.com/en-us/magazine/cc163696.aspx) tells you how. It's a bit of pain b/c then you have to provide the [J# redistributable](http://www.microsoft.com/downloads/details.aspx?familyid=f72c74b3-ed0e-4af8-ae63-2f0e42501be1&displaylang=en) when you roll out tho. | First to answerer you exact question, look for a `BigInt` or `BigNum` type
Second, from what I know of Project Euler, there will be a cool, tricky way to do it that is much easier.
As a first guess I'd compute the answerer for 2^1 -> 2^n (for whatever n you can get to work) and look for patterns. Also look for patterns in the sequences
```
V(0) = 2^p
V(n) = floor(V(n - 1) / 10)
D(n) = V(n) % 10
``` | High precision integer math in C#? | [
"",
"c#",
"types",
""
] |
I'm looking for the number of free bytes on my HD, but have trouble doing so on python.
I've tried the following:
```
import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
```
But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.
What's the best way to get to this figure? | Try using `f_frsize` instead of `f_bsize`.
```
>>> s = os.statvfs('/')
>>> (s.f_bavail * s.f_frsize) / 1024
23836592L
>>> os.system('df -k /')
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/disk0s2 116884912 92792320 23836592 80% /
``` | On UNIX:
```
import os
from collections import namedtuple
_ntuple_diskusage = namedtuple('usage', 'total used free')
def disk_usage(path):
"""Return disk usage statistics about the given path.
Returned valus is a named tuple with attributes 'total', 'used' and
'free', which are the amount of total, used and free space, in bytes.
"""
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return _ntuple_diskusage(total, used, free)
```
Usage:
```
>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>
```
For Windows you might use [psutil](http://code.google.com/p/psutil/). | Find free disk space in python on OS/X | [
"",
"python",
"diskspace",
""
] |
I can't seem to get rid of these seemingly random compiles errors in one of my classes.
I get about 4 errors such as:
```
multiple definition of `draw_line(float, float, float, float)'
```
and
```
multiple definition of `near_far_clip(float, float, float*, float*, float*, float*, float*, float*)'
```
that are flagged in the middle of the method.
I also consistently get `` multiple definition of `stack' `` in the middle of another method. `stack` is a global variable in a totally different file. It isn't even mentioned in the file I'm getting the error in.
I tried separating the error prone file into .h and .cpp files (was originally just a .cpp) and nothing about the error changed...
I don't have duplicate methods. I only have one `#include` of lines.h and there is an `#ifndef` clause at the beginning. All these errors appear in the .cpp file.
Any ideas what it could be?
Alright, I got the code up:
* [lines.cpp](http://code.bulix.org/wrmmiw-70109)
* [ThreeD.cpp](http://code.bulix.org/l2milw-70110)
* [ThreeD.h](http://code.bulix.org/e50rga-70111)
* [makefile](http://code.bulix.org/3ctuqy-70112)
The lines.cpp is a converted .c file I received from my instructor. I included the makefile just in case, because I always have problems with it. I also annotated exactly where the errors were flagged in the file, but they seem pretty random so I don't know if it's particularly important. I abandoned the .h file because it wasn't solving anything or helping. I believe it will be easier to find the mistake without it.
Here is the requested [main.cpp file](http://code.bulix.org/9img79-70113) (there is no .h).
---
I remade the lines.h file due to and I'm still receiving the:
```
multiple definition of `draw_line(float, float, float, float)'
```
and
```
multiple definition of `near_far_clip(float, float, float*, float*, float*, float*, float*, float*)'
```
errors in the lines.cpp file, but the `` multiple definition of `stack' `` error is now in a random place in the ThreeD.cpp file (and is marked by a comment now). **Update:** This error has been fixed and the files have been revised to show this:
* [lines.h](http://code.bulix.org/pl0ha3-70114)
* [lines.cpp](http://code.bulix.org/en2iiq-70124)
* [ThreeD.cpp](http://code.bulix.org/ec1l4c-70125)
* [ThreeD.h](http://code.bulix.org/cm691a-70117)
I messed around with labeling some the global variables extern, but it didn't seem to affect anything. | Why do you #include lines.cpp in ThreeD.cpp? This is very unusual.
Your makefile wants lines.o, so you're going to compile lines.cpp. Anything defined in lines.cpp will be in lines.o and also in ThreeD.o.
There is an intriguing comment in lines.cpp:
```
Don't forget to put declarations in your .h files.
```
I think the instructor wants you to break lines.cpp into a .h and a .cpp.
Excerpt from lines.cpp:
```
/* These go in your .h file or in lines.h */
/*
Line drawing header.
*/
void draw_line(float, float, float, float);
int near_far_clip(float, float, float *, float *, float *, float *,
float *, float *);
```
I suspect that these two declarations are the only thing that should be in lines.h. | You are likely including the function definitions in a header file. Include the `inline` keyword so they are not exported by each object file. Alternatively, put the functions in their own `.cpp` file.
For your global variable, you need to use the `extern` keyword in your header file. Otherwise, each object file exports their own variable and the linker gets confused as to which is the correct one to use. | "Multiple definition of" C++ compiler error | [
"",
"c++",
"linker",
""
] |
I have a checkbox and radiobuttonlist defined as follows:
```
<asp:CheckBox id="chkChange" runat="server" text="Enable" />
<br />
<asp:RadioButtonList id="rblConsole" runat="server" cssclass="console">
<asp:ListItem text="XBox 360" value="xbox" />
<asp:ListItem text="Playstation 3" value="playstation" />
</asp:RadioButtonList>
```
These controls are in a content page with a master page so the actual html rendered is:
```
<table id="ctl00_ContentPlaceHolder1_rblConsole" class="console" border="0">
<tr>
<td><input id="ctl00_ContentPlaceHolder1_rblConsole_0" type="radio" name="ctl00$ContentPlaceHolder1$rblConsole" value="xbox" /><label for="ctl00_ContentPlaceHolder1_rblConsole_0">XBox 360</label>
</td>
</tr>
<tr>
<td><input id="ctl00_ContentPlaceHolder1_rblConsole_1" type="radio" name="ctl00$ContentPlaceHolder1$rblConsole" value="playstation" /><label for="ctl00_ContentPlaceHolder1_rblConsole_1">Playstation 3</label>
</td>
</tr>
</table>
```
On the javascript onclick on the checkbox I want to disable the radio buttons in the rblConsole radiobutton list.
I'm trying to get at the radio buttons via the jQuery endswith selector:
```
function ToggleEnabled() {
var isChecked = $("*[id$='chkChange']").is(":checked");
if (isChecked) {
$("*[name$='rblConsole'").removeAttr("disabled");
} else {
$("*[name$='rblConsole'").attr("disabled", "disabled");
}
}
```
So, how to disable these via jQuery? | I was missing the closing square bracket in the selector. It should be:
```
$("*[name$='rblConsole']").attr("disabled", "disabled");
```
Doh! My bad. | first, remove the apostrophy in the attribute selector
```
function ToggleEnabled() {
var isChecked = $("*[id$='chkChange']").is(":checked");
if (isChecked) {
$("*[name$=rblConsole").removeAttr("disabled");
} else {
$("*[name$=rblConsole").attr("disabled", "disabled");
}
}
```
second, it is better tu use the ClientID property of the controls to get the elements ids:
```
function ToggleEnabled() {
var isChecked = $("#<%=chkChange.ClientID %>").is(":checked");
if (isChecked) {
$("#<%=rblConsole.ClientID %>").removeAttr("disabled");
} else {
$("#<%=rblConsole.ClientID %>").attr("disabled", "disabled");
}
}
``` | How to disable asp.net radiobuttonlist via jQuery | [
"",
"asp.net",
"javascript",
"jquery",
"radiobuttonlist",
""
] |
I've got a thread that's polling a piece of hardware.
```
while not hardware_is_ready():
pass
process_data_from_hardware()
```
But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a `yield` function or something that allows a thread to tell the scheduler "Give the other threads a chance."
```
while not hardware_is_ready():
threading.yield() # This function doesn't exist.
process_data_from_hardware()
```
But I can't find any reference to something like this in the threading documentation. Python does have a `yield` statement, but I'm pretty sure that's something else entirely (to do with generators).
What's the correct thing to do here? | `time.sleep(0)` is sufficient to yield control -- no need to use a positive epsilon. Indeed, `time.sleep(0)` MEANS "yield to whatever other thread may be ready". | Read up on the Global Interpreter Lock (GIL).
For example: <http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/>
Also: <http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html>
Do this in your code if you must do **Busy Waiting** (e.g. polling a device).
```
time.sleep( 0.0001 )
```
This will yield to the thread scheduler.
Also, I collected some notes and references in <http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081031204203/index.html> | How does a threading.Thread yield the rest of its quantum in Python? | [
"",
"python",
"multithreading",
"yield",
""
] |
I have asked a [similar question](https://stackoverflow.com/questions/780236/limit-the-return-of-non-unique-values) before and while the answers I got were spectacular I might need to clearify.
Just like [This question](https://stackoverflow.com/questions/104971/sql-query-help-selecting-rows-that-appear-a-certain-number-of-times) I want to return N number of rows depending on a value in a column.
My example will be I have a blog where I want to show my posts along with a preview of the comments. The last three comments to be exact.
I have have I need for my posts but I am racking my brain to get the comments right. The comments table has a foreign key of post\_id which obviously multiple comments can be attached to one post so if a post has 20 comments then I just want to return the last three. What makes this somewhat tricky is I want to do it in one query and not a "limit 3" query per blog post which makes rendering a page with a lot of posts very query heavy.
```
SELECT *
FROM replies
GROUP BY post_id
HAVING COUNT( post_id ) <=3
```
This query does what I want but only returns one of each comment and not three. | ```
SELECT l.*
FROM (
SELECT post_id,
COALESCE(
(
SELECT id
FROM replies li
WHERE li.post_id = dlo.post_id
ORDER BY
li.post_id, li.id
LIMIT 2, 1
), CAST(0xFFFFFFFF AS DECIMAL)) AS mid
FROM (
SELECT DISTINCT post_id
FROM replies dl
) dlo
) lo, replies l
WHERE l.replies >= lo.replies
AND l.replies <= lo.replies
AND l.id <= lo.mid
```
Having an index on `replies (post_id, id)` (in this order) will greatly improve this query.
Note the usage of `l.replies >= lo.replies AND l.replies <= lo.replies`: this is to make the index to be usable.
See the article in my blog for details:
* [**Advanced row sampling**](http://explainextended.com/2009/03/06/advanced-row-sampling/) (how to select `N` rows from a table for each `GROUP`) | following ian Jacobs idea
declare @PostID int
```
select top 3 post_id, comment
from replies
where post_id=@PostID
order by createdate desc
``` | Select N rows from a table with a non-unique foreign key | [
"",
"sql",
"mysql",
"database",
""
] |
Eclipse CDT provides two indexers for C/C++ code (Preferences > C/C++ > Indexer). Does anybody know what the exact difference is between these two?
The help file isn't exactly enlightening:
> "CDT supports the contribution of
> additional indexers, with 2 indexers
> being provided with the default CDT
> release:
>
> * Fast C/C++ Indexer : provides fastest indexing capabilities - both
> declarations and cross reference
> information. This is the recommended
> indexer.
> * Full C/C++ Indexer : provides even more accurate indexing
> capabilities at the cost of
> performance - both declarations and
> cross reference information."
What does it mean to be more *accurate*: does it index more things, and if so which ones? | Here is an excerpt from the CDT page describing their parsing and indexing([CDT/designs/Overview of Parsing](http://wiki.eclipse.org/CDT/designs/Overview_of_Parsing)). It gives a pretty good description of what the differences are and where the fast indexer can fail:
> Parsing and binding resolution is a
> slow process, this is a problem
> because the user expects code editing
> features such as content assist to be
> fast. For this reason CDT stores
> binding information in an on-disk
> cache called “the index” or “the PDOM”
> (Persisted Document Object Model) in
> order to be able to provide features
> that respond quickly to user requests.
>
> Building the index involves parsing
> all the code in a project, resolving
> all the bindings and writing those
> bindings to the index. The index is
> then incrementally updated every time
> the user edits a file.
>
> Older versions of CDT support three
> different indexing modes, fast
> indexing, full indexing and no
> indexing. The default setting being
> the fast indexer because indexing a
> large project can be a time consuming
> process. The difference between the
> fast and full indexers is that the
> fast indexer will skip header files
> that have already been parsed once,
> while the full indexer will always
> re-parse a header file every time it
> is included. However it is important
> to understand that the full indexer,
> despite its name, is still not fully
> accurate.
>
> When a header file is included in a
> source file it is subject to any
> macros that have been defined at that
> point. Some library headers use macros
> in conjunction with preprocessor
> conditionals (#ifdefs) to partially
> include a header file. Sometimes such
> a header file is included more than
> once in a project, if the macros that
> the header depends on are different
> each time the header is included then
> different parts of the header may be
> included in different source files.
> Neither indexer will be accurate in
> this scenario because it will only
> index the header the first time it is
> encountered.
>
> The Full indexer will re-parse headers
> it has already encountered, but it
> will not re-index them. Therefore
> source files that include a header may
> be parsed more accurately, but the
> header itself will only be indexed the
> one time. The full indexer is much
> slower than the fast indexer because
> of the extra parsing it does, but it
> is only marginally more accurate. For
> this reason the Full indexer is not
> recommended and has been removed from
> the current version of CDT.
>
> Each project has a single PDOM
> associated with it. The PDOM is stored
> on disk as a flat binary file. The
> indexer will only index headers that
> are included by source files, so if
> there is a .h file in the project that
> is not being included by any .c or
> .cpp file, then normally it won’t get
> indexed. However there is a preference
> setting for indexing all files in the
> project. | I believe it always reparses any found/included files without "caching". The reason if that the contents of the files might depend on the preprocessor definitions so it is always reparsed. Fast parser assumes nothing has changed since the file was first encountered.
(but I could be wrong) | Eclipse has two C/C++ indexers (fast & full): what's the difference? | [
"",
"c++",
"c",
"eclipse",
"eclipse-cdt",
"indexer",
""
] |
I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that.
Is there a case insensitive version of replace()? | You can supply the flag re.IGNORECASE to functions in the re module as described in the [docs](http://docs.python.org/library/re.html).
```
matcher = re.compile(myExpression, re.IGNORECASE)
``` | Using `re` is the best solution even if you think it's complicated.
To replace all occurrences of `'abc'`, `'ABC'`, `'Abc'`, etc., with `'Python'`, say:
```
re.sub(r'(?i)abc', 'Python', a)
```
Example session:
```
>>> a = 'abc asd Abc asd ABCDE XXAbCXX'
>>> import re
>>> re.sub(r'(?i)abc', 'Python', a)
'Python asd Python asd PythonDE XXPythonXX'
>>>
```
Note how embedding `(?i)` at the start of the regexp makes it case sensitive. Also note the `r'...'` string literal for the regexp (which in this specific case is redundant but helps as soon as your regexp has backslashes `(\)` in them. | Case insensitivity in Python strings | [
"",
"python",
""
] |
I am just learning python on my ubuntu 8.04 machine which comes with
python 2.5 install. Is 2.5 too dated to continue learning? How much
of 2.5 version is still valid python code in the newer version? | Basically, python code, for the moment, will be divided into python 2.X code and python 3 code. Python 3 breaks many changes in the interest of cleaning up the language. The majority of code and libraries are written for 2.X in mind. It is probably best to learn one, and know what is different with the other. On an ubuntu machine, the `python3` package will install Python 3, which can be run with the command `python3`, at least on my 8.10 install.
To answer your question, learning with 2.5 is fine, just keep in mind that 3 is a significant change, and learn the changes - ask yourself as you code, "how would this be different in 3, if at all?".
(As an aside, I do wish Ubuntu would upgrade to 2.6 though. It has a nice compatibility mode which tries and points out potential difficulties. But python is in such big use on a modern Linux distro, it can be a difficult change to make)
[Here's an article describing 2.6 -> 3's changes](http://docs.python.org/3.0/whatsnew/3.0.html) | Python 2.5 will be fine for learning purposes. In the interest of learning you will probably want to look into the [differences](http://docs.python.org/3.0/whatsnew/3.0.html) that python 3.0 has introduced, but I think most of the Python community is still using Python 2, as the majority of libraries haven't been ported over yet.
If your interested in 2.6 [here](http://www.saltycrane.com/blog/2008/10/installing-python-26-source-ubuntu-hardy/) is a blog post on compiling it on Hardy, there may even be a package for it somewhere out there on the internets.
Follow up, if there is a package I'm not finding it. Self compiling is pretty simple for most things, though I've never tried to compile Python. | python 2.5 dated? | [
"",
"python",
""
] |
EDIT: WOW. This question is 12 years old now.
As someone stated, it can be done with a one-liner since 2016: <https://stackoverflow.com/a/69322509/80907>
---
The original:
I'm wondering if there's a way to change the text of anything in HTML without using innerHTML.
Reason I'm asking is because it's kinda frowned upon by the W3C.
I know it's nitpicking, but I just wanna know, is there a way?
EDIT: people seem to misunderstand what I'm asking here: I want to find a way to effectivly change the text being displayed.
If I have:
```
<div id="one">One</a>
```
innerHTML allows me to do this:
```
var text = document.getElementsById("one");
text.innerHTML = "Two";
```
And the text on my screen will have changed.
I do not wish to append more text, I wish to change allready existing text. | The recommended way is through DOM manipulation, but it can be quite verbose. For example:
```
// <p>Hello, <b>World</b>!</p>
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));
// <b>
var b = document.createElement('b');
b.appendChild(document.createTextNode('World');
para.appendChild(b);
para.appendChild(document.createTextNode('!'));
// Do something with the para element, add it to the document, etc.
```
**EDIT**
In response to your edit, in order to replace the current content, you simply remove the existing content, then use the code above to fill in new content. For example:
```
var someDiv = document.getElementById('someID');
var children = someDiv.childNodes;
for(var i = 0; i < children.length; i++)
someDiv.removeChild(children[i]);
```
But as someone else said, I'd recommend using something like jQuery instead, as not all browsers fully support DOM, and those that do have quirks which are dealt with internally by JavaScript libraries. For example, jQuery looks something like this:
```
$('#someID').html("<p>Hello, <b>World</b>!</p>");
``` | The better way of doing it is to use [`document.createTextNode`](https://developer.mozilla.org/en/DOM/document.createTextNode). One of the main reasons for using this function instead of `innerHTML` is that all HTML character escaping will be taken care of for you whereas you would have to escape your string yourself if you were simply setting `innerHTML`. | Alternative for innerHTML? | [
"",
"javascript",
"w3c",
"innerhtml",
""
] |
I have a table which has a clustered index on two columns - the primary key for the table.
It is defined as follows:
```
ALTER TABLE Table ADD CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED
(
[ColA] ASC,
[ColB] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
```
I want to remove this clustered index PK and add a clustered index like follows and add a primary key constraint using a non-clustered index, also shown below.
```
CREATE CLUSTERED INDEX [IX_Clustered] ON [Table]
(
[ColC] ASC,
[ColA] ASC,
[ColD] ASC,
[ColE] ASC,
[ColF] ASC,
[ColG] ASC
)WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 90, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
ALTER TABLE Table ADD CONSTRAINT
PK_Table PRIMARY KEY NONCLUSTERED
(
ColA,
ColB
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
```
I was going to just drop the PK clustered index, then add the new clustered index and then add the non-clustered primary key index, but I learned that dropping the existing clustered index would cause the table data to be reordered (see answer here [What happens when I drop a clustered primary key in SQL 2005](https://stackoverflow.com/questions/705504/what-happens-when-i-drop-a-clustered-primary-key-in-sql-2005)), which I don't think should be necessary. The table is knocking 1 TB, so I really want to avoid any unnecessary reordering.
My question is, what is the best way to go from the existing structure to the desired structure?
EDIT: Just want to clarify. The table is 1TB and I unfortunately do not have space to create a temporary table. If there is a way to do it without creating a temp table then please let me know. | If your table is getting up to 1 TB in size and probably has LOTS of rows in it, I would strongly recommend NOT making the clustered index that much fatter!
First of all, dropping and recreating the clustered index will shuffle around ALL your data at least once - that alone will take ages.
Secondly, the big compound clustered index you're trying to create will significantly increase the size of all your non-clustered indices (since they contain the whole clustered index value on each leaf node, for the bookmark lookups).
The question is more: why are you trying to do this?? Couldn't you just add another non-clustered index with those columns, to potentially cover your queries? Why does this have to be the clustered index?? I don't see any advantage in that....
For more information on indexing and especially the clustered index debate, see [Kimberly Tripp's blog](http://sqlskills.com/BLOGS/KIMBERLY/category/Indexes.aspx) on SQL Server indexes - very helpful!
Marc | This isn't a complete answer to your question, but make sure that if you have any other indexes on the table that you drop those first. Otherwise SQL Server will have to rebuild them all when you remove the clustered index then rebuild them all again when you add back a new clustered index. The usual steps are:
1. Remove all non-clustered indexes
2. Remove clustered index
3. Add new clustered index
4. Add back all non-clustered indexes | Best way to change clustered index (PK) in SQL 2005 | [
"",
"sql",
"sql-server-2005",
"indexing",
"primary-key",
"clustered-index",
""
] |
I need to display float as
```
1.00
1.50
1.55
1.60
```
The following is what I see using f2 format.
```
1.
1.5
1.55
1.6
```
Is there a way to force the trailing 0 to appear?
(I'm using a DevExpress SpinEdit control and trying to set the display and edit format.) | ```
yourNumber.ToString("N2");
``` | You can use syntax like this:
```
String.Format("{0:0.00}", n)
``` | c#: how to force trailing zero in numeric format string? | [
"",
"c#",
"devexpress",
""
] |
> ## Duplicate
>
> [Use of var keyword in C#](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c)
> [C# - Do you use "var"?](https://stackoverflow.com/questions/633474/c-do-you-use-var)
> [Should I *always* favour implictly typed local variables in C# 3.0?](https://stackoverflow.com/questions/17032/)
Would you prefer to write your code like this:
```
var myVar = new MyClass();
```
or
```
MyClass myVar = new MyClass();
```
I don't object to use the `var` *keyword* in example above; however, in the code below I don't like the usage of `var`.
```
var files = Files.GetFiles();
```
In this example it's not obvious what type variable `files` is going to be.
What's your preference for using the `var` *keyword*? | I tend to use 'var' in places where I, reading the sourcecode, can infer the type of the variable without having to navigate to other places in the sourcecode.
For example, any time I new up an object:
```
var c = new Customer();
```
Or when calling a method in which the return type is clear:
```
var c = Customers.GetCustomerByID(5);
```
Also, 'var' *must* be used in the case of anonymous types:
```
var t = new { Key = "One", Value = 1 };
```
And I also use it with LINQ of course:
```
var q = from c in Customers
where c.CustomerID == 5
select c;
```
In the case above 'q' is of type IQueryable (assuming Customers is an enumeration of Customer objects).
Also 'foreach' statements as well - GREAT please to use 'var':
```
foreach (var i in intArray) { /* use i */ }
```
Other examples abound I'm sure - but these cover my most frequent use cases. | If it's a situation where either would work (which excludes the anonymous type situation), I try to use whatever will make the code easier to understand in the future. Sometimes that means using var if the usage scope is small or the type being assigned to is unwieldy (e.g., somekind of nested generic) to repeat and adds clutter. I also tend to use var where most people expect to see (e.g. as the declaration of a linq query). | How do you use the var keyword? | [
"",
"c#",
"c#-3.0",
""
] |
1. I want to send a message to userID=3 by going to /MyController/Message/3
2. This executes `Message()` [get] action, I enter some text in the text area and click on Save to post the form
3. `Message()` [post] action saves the changes, resets the value of SomeText to empty string and returns to the view.
At this point I expect the text area to be empty because I have set `ViewData["SomeText"]` to `string.Empty`.
**Why is text area value not updated to empty string after post action?**
Here are the actions:
```
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Message(int ID)
{
ViewData["ID"] = ID;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Message(int ID, string SomeText)
{
// save Text to database
SaveToDB(ID, SomeText);
// set the value of SomeText to empty and return to view
ViewData["SomeText"] = string.Empty;
return View();
}
```
And the corresponding view:
```
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm())
{ %>
<%= Html.Hidden("ID", ViewData["ID"])%>
<label for="SomeText">SomeText:</label>
<%= Html.TextArea("SomeText", ViewData["SomeText"]) %>
<input type="submit" value="Save" />
<% } %>
</asp:Content>
``` | The problem is the HtmlHelper is retrieving the ModelState value, which is filled with the posted data. Rather than hacking round this by resetting the ModelState, why not redirect back to the [get] action. The [post] action could also set a temporary status message like this:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Message(int ID, string SomeText)
{
// save Text to database
SaveToDB(ID, SomeText);
TempData["message"] = "Message sent";
return RedirectToAction("Message");
}
```
This seems to me like more correct behaviour. | The problem is that your ModelState is re-filled with the posted values.
What you can do is clear it on the Action that has the Post attribute :
```
ModelState.Clear();
``` | Reset the value of textarea after form submission | [
"",
"c#",
"asp.net-mvc",
"forms",
""
] |
There's a SecureZeroMemory() function in WinAPI that is designed for erasing the memory used for storing passwords/encryption keys/similar stuff when the buffer is no longer needed. It differs from ZeroMemory() in that its call will not be optimized out by the compiler.
Is it really so necessary to erase the memory used for storing sensitive data? Does it really make the application more secure?
I understand that data could be written into swapfile or into hibernation file and that other processes could possibly read my program's memory. But the same could happen with the data when it is still in use. Why is *use, then erase* better than just *use*? | It does. Hibernation file is not encrypted, for example. And if you don't securely clear the memory, you might end up with trouble. It's just a single example, though. You should always hold secret stuff in memory only as long as needed. | It exists for a reason. :)
If you keep sensitive data in memory, then other processes can potentially read it.
Of course, in your application, passwords or other secure data may not be so critical that this is required. But in some applications, it's pretty essential that malicious code can't just snoop your passwords or credit card numbers or whatever other data the application uses. | Does using SecureZeroMemory() really help to make the application more secure? | [
"",
"c++",
"security",
"winapi",
""
] |
Am trying to move an antique C++ code base from gcc 3.2 to gcc 4.1, as I have run into a few issues. Of all the issues, the following is left me clueless (I guess I spent too much time with Java or I might have forgotten the basics of C++ :-P ).
I have a template class
```
template < class T > class XVector < T >
{
...
template < class T > T
XVector < T >::getIncrement ()
{
...
}
template < class T > int
XVector < T >::getValue (size_t index, T& value)
{
...
//The problematic line
value = (T) (first_value + getIncrement())
* (long) (index - first_index);
....
}
}
```
This class is based on the STL std::vector. I have a second class TypeValue and its defined as below which can hold one of int, long and their unsigned variants, float, double, std::string. Also overloads almost all possible operators.
```
class TypeValue
{
union
{
long* _int_value;
double* _real_value;
string* _text_value;
} _value;
TypeValue();
explicit TypeValue(long _long);
explicit TypeValue(int _int);
explicit TypeValue(unsigned long _ulong);
...
//similarly for all the remaining supported types.
TypeValue(const TypeValue& ) //Copy constructor
virtual TypeValue& operator=(const TypeValue &rhs);
TypeValue& operator+ (TypeValue& )const;
TypeValue& operator* (TypeValue& )const;
...
//For all the basic operators
operator long() const;
operator int() const;
operator unsigned long() const;
operator unsigned int() const;
...
}
```
And finally I have another class, lets call it the build\_breaker, which creates an object as `XVector < TypeValue > a_variable;`. Now when I compile this on gcc 3.2 this compiles without any problems. But when I try compiling this on gcc 4.1 I get errors saying ambigous overload for `operator*` in the class `XVector` and the candidates being
```
operator*(long int, long int)
operator*(int, long int)
operator*(long unsigned int, long int)
operator*(unsigned int, long int)
operator*(double, long int)
operator*(float, long int)
```
If the compiler said it had problems finding a match for T \* long, that would have made sense, but, why is it trying to typecast it to native type and then perform the arithmetic operation?
Please help me on this.
Thanks in advance. | The second operand type is `long [int]`. The first is `TypeValue`, I expect, but there is no operator`*` that takes those two exact types. There are lots of other type combinations for that operator, though, which the compiler can select by doing an implicit conversion on the first operand. The language allows the compiler to do that to try to find a match.
But which of the many conversions should it choose? The compiler has no way to choose whether `int` is better than `long int`. (You might argue that since the second operand is `long int`, that should be the preferred conversion target, but that's not the way things work.)
So, some advice: First, don't supply so many implicit conversions. Since the class can only hold `long`, `double`, and `string`, those are the only three conversions I'd supply. That alone probably won't solve your problem, but it may reduce the size of the error output and make other things more manageable.
Instead of converting `(index - first_index)` to type `long`, consider converting it to type `T` (i.e., `TypeValue`) instead, since that seems to be the operation you really wanted to perform in the first place. | I would change all the conversion operators to named functions so that:
```
operator long() const;
```
becomes
```
long ToLong() const;
```
Implicit conversiopns via cast operators cause all sorts of problems, and my own programming standards bans their use. | C++ operator overloading resolution ambiguity | [
"",
"c++",
"templates",
"gcc",
""
] |
We all know that
```
$a1 = array('foo');
$a2 = $a1;
$a2[0] = 'bar';
// now $a1[0] is foo, and $a2[0] is bar. The array is copied
```
However, what I remember reading, but cannot confirm by Googling, is that the array is, internally, not copied until it is modified.
```
$a1 = array('foo');
$a2 = $a1; // <-- this should make a copy
// but $a1 and $a2 point to the same data internally
$a2[0] = 'bar';
// now $a1[0] is foo, and $a2[0] is bar. The array is really copied
```
I was wondering if this is true. If so, that would be good. It would increase performance when passing around a big array a lot, but only reading from it anyway (after creating it once). | It may be more than you wanted to know, but [this article](http://derickrethans.nl/files/phparch-php-variables-article.pdf) gives a good description of the way variables work in PHP.
In general, you're correct that variables aren't copied until it's absolutely necessary. | I seem to have confirmed it:
```
<?php
ini_set('memory_limit', '64M');
function ttime($m) {
global $s;
echo $m.': '.(microtime(true) - $s).'<br/>';
$s = microtime(true);
}
function aa($a) {
return $a;
}
$s = microtime(true);
for ($i = 0; $i < 200000; $i++) {
$array[] = $i;
}
ttime('Create');
$array2 = aa($array); // or $array2 = $array
ttime('Copy');
$array2[1238] = 'test';
ttime('Modify');
```
Gives:
```
Create: 0.0956180095673
Copy: 7.15255737305E-6
Modify: 0.0480329990387
``` | performance of array cloning | [
"",
"php",
"performance",
"arrays",
""
] |
I'm looking for C# code that translates a 271 health care eligibility benefit response to a more usable format so I can display certain segments and values into a datagridview. I'm looking for code that I can use to break this thing apart as it's not really difficult, just very tedious and was wondering if anybody else has done this and is willing to share.
Thanks!! | There is an open source X12 parser (OopFactory X12 Parser: <https://x12parser.codeplex.com>) that does this for you.
To convert any X12 document to Xml:
```
FileStream fstream = new FileStream("Sample1.txt", FileMode.Open, FileAccess.Read);
var parser = new X12Parser();
Interchange interchange = parser.Parse(fstream);
string xml = interchange.Serialize();
```
To convert any X12 document to Html:
```
var htmlService = new X12HtmlTransformationService(new X12EdiParsingService(suppressComments: false));
Stream ediFile = new FileStream("Sample.txt", FileMode.Open, FileAccess.Read);
string html = htmlService.Transform(new StreamReader(ediFile).ReadToEnd());
```
More details here: <https://x12parser.codeplex.com/wikipage?title=Parsing%20an%20837%20Transaction&referringTitle=Documentation>
To load an X12 271 response into a .Net object, you can use:
```
FileStream fstream = new FileStream("Sample1.txt", FileMode.Open, FileAccess.Read);
var service = new EligibilityTransformationService();
EligibilityBenefitDocument eligibilityBenefitDocument = service.Transform271ToBenefitResponse(fstream);
``` | DataDirect Technologies sells a [converter](http://www.xmlconverters.com/standards/hipaa) that will translate it into XML. | Anyone translate a X12 271 Healthcare response | [
"",
"c#",
"edi",
"x12",
""
] |
I am trying to implement PayPal IPN functionality. The basic protocol is as such:
1. The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment.
2. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc.
3. I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '\_notify-validate'.
When I try to urllib.urlencode the params which PayPal has sent to me, I get a:
```
While calling send_response_to_paypal. Traceback (most recent call last):
File "<snip>/account/paypal/views.py", line 108, in process_paypal_ipn
verify_result = send_response_to_paypal(params)
File "<snip>/account/paypal/views.py", line 41, in send_response_to_paypal
params = urllib.urlencode(params)
File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode
v = quote_plus(str(v))
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128)
```
I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method)
**Details:**
I read the params in PayPal's original request as follows (the GET is for testing):
```
def read_ipn_params(request):
if request.POST:
params= request.POST.copy()
if "ipn_auth" in request.GET:
params["ipn_auth"]=request.GET["ipn_auth"]
return params
else:
return request.GET.copy()
```
The code I use for sending back the request to PayPal from the processing page is:
```
def send_response_to_paypal(params):
params['cmd']='_notify-validate'
params = urllib.urlencode(params)
req = urllib2.Request(PAYPAL_API_WEBSITE, params)
req.add_header("Content-type", "application/x-www-form-urlencoded")
response = urllib2.urlopen(req)
status = response.read()
if not status == "VERIFIED":
logging.warn("PayPal cannot verify IPN responses: " + status)
return False
return True
```
Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range. | Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode:
```
params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))
```
Of course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to unicode first, then encode it:
```
params['foo'] = my_raw_input.decode('iso-8859-1')
params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))
``` | Instead of encoding to `utf-8`, one should encode to what ever the paypal is using for the post.
It is available under key 'charset' in the form paypal sends.
So the following code worked for me:
> `data = dict([(k, v.encode(data['charset'])) for k, v in data.items()])` | Python interface to PayPal - urllib.urlencode non-ASCII characters failing | [
"",
"python",
"unicode",
"paypal",
"urllib2",
"urllib",
""
] |
How do you add CSS rules (eg `strong { color: red }`) by use of Javascript? | You can also do this using DOM Level 2 CSS interfaces ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets)):
```
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
```
...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:
```
sheet.addRule('strong', 'color: red;', -1);
```
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement. | The simple-and-direct approach is to create and add a new `style` node to the document.
```
// Your CSS as text
var styles = `
.qwebirc-qui .ircwindow div {
font-family: Georgia,Cambria,"Times New Roman",Times,serif;
margin: 26px auto 0 auto;
max-width: 650px;
}
.qwebirc-qui .lines {
font-size: 18px;
line-height: 1.58;
letter-spacing: -.004em;
}
.qwebirc-qui .nicklist a {
margin: 6px;
}
`
var styleSheet = document.createElement("style")
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
``` | How do you add CSS with Javascript? | [
"",
"javascript",
"css",
""
] |
I have a .NET Compact Framework 3.5 program that is used as a 'Occasionally Connected' line of business (LOB) application. If it can see an online webservice, it will use that for data access, but if network connection is lost it will use a local cache.
What is the best way to handle all of the connection options and state changes?
* OpenNetCF's ConnectionManager class?
* Microsoft.WindowsBile.State.SystemState?
* API calls?
How do you get it to understand the difference between WiFi, Cradle, and GPRS and use the best method available?
Anyone have any guidance on this? | I just create a simple shared class that I can call like this:
```
If MyConnectionClass.IsConnected then
'Do connected stuff
Else
'Do local save
End If
```
Then all of my actual business classes/functions can use this to hide this nastiness from the UI code.
The MyConnectionClass' IsConnected property would have something like this:
```
Public ReadOnly Property IsConnected As Boolean
Get
Try
Dim HostName As String = Dns.GetHostName()
Dim thisHost As IPHostEntry = Dns.GetHostByName(HostName)
Dim thisIpAddr As String = thisHost.AddressList(0).ToString
return (thisIpAddr <> Net.IPAddress.Parse("127.0.0.1").ToString())
Catch ex As Exception
Return False
End Try
End Get
End Property
```
It is also recommended that you poll for connection status using a background thread and then fire an event back to the main app thread when the state changes. Here is the detailed writeup:
[Testing for and responding to network connections in the .NET Compact Framework](http://msdn.microsoft.com/en-us/library/aa446548.aspx)
**EDIT:**
Now, for **GPRS** support:
If you are using Web Requests or Web Services, the framework will handle the connection for you. If you are diving deeper into TCPClient or UDPClient, you need to handle it with the Connection manager API's yourself like so:
```
public class GPRSConnection
{
const int S_OK = 0;
const uint CONNMGR_PARAM_GUIDDESTNET = 0x1;
const uint CONNMGR_FLAG_PROXY_HTTP = 0x1;
const uint CONNMGR_PRIORITY_USERINTERACTIVE = 0x08000;
const uint INFINITE = 0xffffffff;
const uint CONNMGR_STATUS_CONNECTED = 0x10;
static Hashtable ht = new Hashtable();
static GPRSConnection()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.Handle = ConnMgrApiReadyEvent();
mre.WaitOne();
CloseHandle(mre.Handle);
}
~GPRSConnection()
{
ReleaseAll();
}
public static bool Setup(Uri url)
{
return Setup(url.ToString());
}
public static bool Setup(string urlStr)
{
ConnectionInfo ci = new ConnectionInfo();
IntPtr phConnection = IntPtr.Zero;
uint status = 0;
if (ht[urlStr] != null)
return true;
if (ConnMgrMapURL(urlStr, ref ci.guidDestNet, IntPtr.Zero) != S_OK)
return false;
ci.cbSize = (uint) Marshal.SizeOf(ci);
ci.dwParams = CONNMGR_PARAM_GUIDDESTNET;
ci.dwFlags = CONNMGR_FLAG_PROXY_HTTP;
ci.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
ci.bExclusive = 0;
ci.bDisabled = 0;
ci.hWnd = IntPtr.Zero;
ci.uMsg = 0;
ci.lParam = 0;
if (ConnMgrEstablishConnectionSync(ref ci, ref phConnection, INFINITE, ref status) != S_OK &&
status != CONNMGR_STATUS_CONNECTED)
return false;
ht[urlStr] = phConnection;
return true;
}
public static bool Release(Uri url)
{
return Release(url.ToString());
}
public static bool Release(string urlStr)
{
return Release(urlStr, true);
}
private static bool Release(string urlStr, bool removeNode)
{
bool res = true;
IntPtr ph = IntPtr.Zero;
if (ht[urlStr] == null)
return true;
ph = (IntPtr)ht[urlStr];
if (ConnMgrReleaseConnection(ph, 1) != S_OK)
res = false;
CloseHandle(ph);
if (removeNode)
ht.Remove(urlStr);
return res;
}
public static void ReleaseAll()
{
foreach(DictionaryEntry de in ht)
{
Release((string)de.Key, false);
}
ht.Clear();
}
[StructLayout(LayoutKind.Sequential)]
public struct ConnectionInfo
{
public uint cbSize;
public uint dwParams;
public uint dwFlags;
public uint dwPriority;
public int bExclusive;
public int bDisabled;
public Guid guidDestNet;
public IntPtr hWnd;
public uint uMsg;
public uint lParam;
public uint ulMaxCost;
public uint ulMinRcvBw;
public uint ulMaxConnLatency;
}
[DllImport("cellcore.dll")]
private static extern int ConnMgrMapURL(string pwszURL, ref Guid pguid, IntPtr pdwIndex);
[DllImport("cellcore.dll")]
private static extern int ConnMgrEstablishConnectionSync(ref ConnectionInfo ci, ref IntPtr phConnection, uint dwTimeout, ref uint pdwStatus);
[DllImport("cellcore.dll")]
private static extern IntPtr ConnMgrApiReadyEvent();
[DllImport("cellcore.dll")]
private static extern int ConnMgrReleaseConnection(IntPtr hConnection, int bCache);
[DllImport("coredll.dll")]
private static extern int CloseHandle(IntPtr hObject);
}
```
And to use it, do this:
```
public void DoTcpConnection()
{
string url = "www.msn.com";
bool res = GPRSConnection.Setup("http://" + url + "/");
if (res)
{
TcpClient tc = new TcpClient(url, 80);
NetworkStream ns = tc.GetStream();
byte[] buf = new byte[100];
ns.Write(buf, 0, 100);
tc.Client.Shutdown(SocketShutdown.Both);
ns.Close();
tc.Close();
MessageBox.Show("Wrote 100 bytes");
}
else
{
MessageBox.Show("Connection establishment failed");
}
}
```
This was from Anthony Wong's blog here:
[Anthony Wong](http://blogs.msdn.com/anthonywong/archive/2006/03/13/550686.aspx)
And remember you only need this for lower level TCP or UDP stuff. HTTPRequests don't need this. | What about using the [SystemState](http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.systemstate.aspx) class at the Microsoft.WindowsMobile.Status namespace? You can monitor the current state of the system and get notifications, when the state changes. See this [post](http://forum.soft32.com/pda/connection-type-ftopict63639.html) for some code.
SystemState is only about the status of the connections. You can use a specific connection through the ConnectionManager. I recommend reading this [article](http://msdn.microsoft.com/en-us/library/bb840031.aspx). If you are using .NET Compact Framework 3.5, a managed API is included. You can also use OpenNetCF ConnectionManager. | Best way to manage network state in Windows Mobile | [
"",
"c#",
"windows-mobile",
"compact-framework",
""
] |
i have a few batch java command-line applications which are planned to be deployed as:
```
batch_apps
app_1
batch1.jar
run_batch1.sh
app_2
batch2.jar
run_batch3.sh
{...etc...}
```
what would be the best practice on organizing a shared library pool - for example log4j:
```
batch_apps
app_1
batch1.jar
run_batch1.sh
app_2
batch2.jar
run_batch3.sh
libs
log4j.jar
ojdbc.jar
```
?
and include individual log4j.xml's in each app's own jar file?
i understand i would need to add 'libs' to the classpath either in manifests or in run\_batchX.sh
(which way is preferable?)
I am mostly wondering what would be the most efficient setup performance-wise.
thanks | Having a shared libs directory at the root of your install dir is definitely the way to go. Since libs will be loaded in memory once, when the JVM launches, there is no impact on performance whatever solution you choose.
I would not put the classpath in the jar files, as this would force you to change your jars if you need to relocate your lib dir. Editing a script is much simpler.
I would not include the log4j conf file in your jar files either, for the same reason. | It appears your applications don't share a single JVM instance. (i.e. They are individually started via 'java -jar batch1.jar' or some such.) Therefore, sharing library .jar files only saves you DISK space not RAM.
**If the apps are not sharing a single JVM** then ease-of-deployment should take precedence over disk space. (Your time is worth more than a few "wasted" MB.)
In this instance I would recommend making each application self contained, in either a single .jar file including all its libraries, or a single folder of .jar files. (i.e. Put the libs for each app in a folder for that app.)
**If the apps were sharing a single JVM** then I would recommend the shared library folder option. | How to share log4j library most effectively | [
"",
"java",
"batch-file",
"jar",
""
] |
I'm getting the LNK2005: already defined in (...) error when building my project in Visual Studio 2008. I've referenced other related questions, but mine seems to be a bit more complicated due if nothing else to the number of files I'm working with.
First, I think it will be helpful for me to map out the #include statements I have in the files of my project in the format [current\_file] ->includes\_this\_file
All my header files are guarded with the standard #ifndef [Header] #define [Header] ... #endif.
[Modulator.h]
prototypes for Modulator class
[ChorusUnit.h] ->Modulator.h
prototypes for Chorus classes which have member objects of type Modulator
[AudioHandler.h] ->ChorusUnit.h
prototypes for AudioHandler class which has member objects of Chorus classes
[Chorus.cpp] ->AudioHandler.h
definitions for the members of Modulator and Chorus classes
[AudioHandler.cpp] ->Chorus.cpp
definitions for the members of AudioHandler class
[ChorusUnit.cpp] ->AudioHandler.cpp
the file containing the main() function that actually runs the code of my project.
The ordering of includes is because all the definitions of functions to the classes found in Modulator.h, ChorusUnit.h, and AudioHandler.h need to reference members of the other classes, so I needed the prototypes defined first for all the classes to see each other.
The error specifically says that every single definition found in Chorus.cpp and AudioHandler.cpp in file Chorus.obj is already defined in AudioHandler.obj.
Also there is another set of the same error type that says every single definition found in Chorus.cpp and AudioHandler.cpp in file ChorusUnit.obj is already defined in AudioHandler.obj.
There is probably a pretty straightforward solution, but I am not particularly experience (being mostly a Java programmer) in linking in general. As far as my limited knowledge on the subject goes, I only defined everything once and everything was only included once so I'm personally at a loss as to why these are already defined. Some please enlighten me! | The error is probably that you say you #include Chorus.cpp in AudioHandle.cpp - this is not what you probably want.
The reason is, that all .cpp files (unless you've done something special in your IDE) are compiled separately, then linked. When you #include another .cpp file, the file's text is literally included; therefore, all objects defined in the included file appear in the including file as well. When you link the two files, the common objects cause a conflict. | > [AudioHandler.cpp] ->Chorus.cpp
>
> definitions for the members of AudioHandler class
This is wrong. Include `ChorusUnit.hpp` for prototypes. | Complicated error LNK2005: already defined C++ | [
"",
"c++",
"visual-studio-2008",
"linker",
""
] |
I'm using MAMP just for my development environment and haven't really understood the folder structure of /var/www/project-name/ on a web server. I'm wondering whether you're meant to point the web server to the htdocs folder or it's supposed to point to the root of the project folder?
The reason I ask is because libraries are meant to exist outside of the htdocs folder for security purposes, but how are they pointed to from the web application itself? Surely the web application can't access folders outside of the htdocs folder if the web server is pointing to the htdocs folder for the web application? | A simple solution is to have a folder structure like so:
```
/var/www/project-name/
+ webroot/
+ libraries/
```
Point your apache2 `DocumentRoot` to the `webroot` directory. Keep all the libraries that you don't want accessible from the web in the `libraries` directory. In your php code, use the include directive to access the libraries code.
The trick is to understand that php can include any file on your system it has read access to. A person browsing your website can only access files inside your webroot directory. | If you have multiple vhosts on the same server, it's pretty common to have each site in a directory under `/var/www`, and each of these have a `htdocs` folder, which is mounted as the web root. You can then have logs and application-specific libraries in a folder above the web root. Eg.:
```
/var/www/lolcats.com
/var/www/lolcats.com/htdocs
/var/www/lolcats.com/htdocs/index.php
/var/www/lolcats.com/lib
/var/www/lolcats.com/log
``` | /var/www/ folder structure for PHP project | [
"",
"php",
"mamp",
""
] |
I'm running a (mostly) single threaded program (there's a main thread that does everything, the others only read stuff). I can get the application to run fine in VS2008 after a minor change (I changed the text of a form, and tab order of another form), but I can no longer get it to work outside of the debugger. Does anyone know what would cause this?
**Clarification:** Release mode, launched with debugger (F5) works. Debug mode, lanuched with debugger (F5) works. Debug executable, or release executable launched outside of VS or with Ctrl+F5 fail.
It uses Microsoft's Virtual Earth 3D, and it seems to crash just when the 'ring of hope' (loading ring) is about to complete.
**Event log** says: ".NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (000006427F44AA6E) (80131506)"
**Culprit:** this line:
```
this.loader = PlugInLoader.CreateLoader(this.globeControl.Host);
```
Causes it to fail. However, the form that was working uses the exact same line without an issue. This line is nesseccary for the program to function. I have no idea what it's doing.
**Another Lead** the error seems to be inside the .NET framework. Application worked on another machine, attempting reinstall. **Update:** didn't make a difference, although when I repaired VS it kept telling me Visual Studio was crashing even though I wasn't running it.
---
**Error**
When I launch the program after a couple minutes I get:
Application has generated an exception that could not be handled.
Proccess ID=0x9CC (2508), Thread ID =0xF0C(3852).
Click OK to terminate the application.
Click CANCEL to debug the application.
---
The disassembly is bizarre:
```
0000000077EF2A90 int 3
0000000077EF2A91 int 3
0000000077EF2A92 int 3
0000000077EF2A93 int 3
0000000077EF2A94 int 3
0000000077EF2A95 int 3
0000000077EF2A96 xchg ax,ax
0000000077EF2A9A xchg ax,ax
0000000077EF2A9E xchg ax,ax
0000000077EF2AA0 int 3 <-- Crashes here
0000000077EF2AA1 ret
```
It repeats that same code block several times (minus on ax exchanging with itself)
---
**Besides my computer, it has worked on every machine I've tested it on, except for a VM on my machine which won't install the .NET framework because setup downloads 0 bytes out of 0 bytes for the framework)...lovely windows.** | I fixed it, the .NET 2.0 Framework was corrupt and when I reinstalled it, everything magically started working again. | I've had similar issues where timing conflicts were causing the failure, and my debugging (breakpoints and stepping through the code) forced the code to run in the correct order. | C# app runs with debugging, but not without | [
"",
"c#",
".net",
"winforms",
"debugging",
""
] |
I'm looking for an easy (no database) method of listing how many users are active on a website. The easiest way I can come up with is by counting the number of open sessions.
This code *should work:*
```
$number_of_users = count(scandir(ini_get("session.save_path")));
```
Of course it won't because of the security constraints on that directory (as there should be!!). Does anyone know another way to access this number without changing directory permissions.
**Note:** I'm looking for an option that **does not involve databases** or reducing the security on PHP sessions.
**End Note:** For anyone coming to this question, I ended up using a cronjob (running every minute) from root that did something similar to:
```
ls /var/lib/php5/ | wc -l > /var/www/sessioncount
```
Make sure the `/var/www/sessioncount` file is readable by the apache user. Then you can just read the file in PHP:
```
$number_of_users = file_get_contents("/var/www/sessioncount");
``` | Easy does not mean no database in this case. Also relying on session to see how many users are active is not reliable.
If you wanted to go that route, you could do a cronjob that is run by a safe process every few minutes and saves that count into a file or db, which PHP reads.
But i recommend going the database route. | ```
<?
// you must set your own accessible session path atop every page.
session_save_path("/home/some/other/location/"); # SECURITY VIOLATION!!!
session_start();
function session_count() {
$filter = "sess_";
$files = scandir(session_save_path());
$count = 0;
foreach ($files as $file) {
if(strpos($file,$filter)===0) {
$count += 1;
}
}
return $count;
}
echo session_count();
?>
``` | Find Number of Open Sessions | [
"",
"php",
"session",
""
] |
I have a question regarding this code. I'm a beginner and enjoy learning C#. But then I'm on the topic now called Array which is quite difficult and I need your help. I would like to understand the code.
What I don't understand here is what does the part 1, 2, 3, 4 and 5 here mean?
I don't understand what is the function of "const" and "byte" here?
I would appreciate your explanation?
Thanks & regards;-)
1)
```
const byte numbers = 5;
byte[] myNumbers = new byte[numbers];
byte additionalNumbers;
Random coincidenceNumbers = new Random();
```
2)
```
string yourPassword;
Console.WriteLine("Please enter your password:");
yourPassword = Console.ReadLine();
if (yourPassword != "helloWorld")
{
Console.WriteLine("\nWrong password\n");
return;
}
else
{
Console.WriteLine();
Console.WriteLine("Welcome to my world!");
for (int i=0; i < myNumbers.Length; ++i)
{
myNumbers[i]=(byte)(coincidenceNumbers.Next(1,50));
}
}
```
3)
```
additionalNumbers=(byte) (coincidenceNumbers.Next(1,50));
```
4)
```
Array.Sort(myNumbers);
Console.WriteLine("\nThe Number is:\n");
```
5)
```
foreach (byte elem in myNumbers)
{
Console.WriteLine("\t" + elem);
Console.WriteLine();
Console.WriteLine("Additional Number is: " + additionalNumbers);
}
``` | const is a reserver word meaning that "variable" will not vary, instead, its value will not change, if you try to change
```
const byte numbers = 5;
numbers = 6; // will fail
```
byte is a type for storing small numbers
Then,
```
byte[] myNumbers = new byte[numbers];
```
creates an array of numbers (5) positions. You can for example, assign values to any position within the array, like this:
```
myNumbers[0] = 4; // position 1
myNumbers[1] = 45; // position 2
myNumbers[2] = 25; // position 3
myNumbers[3] = 0; // position 4
myNumbers[4] = 12; // position 5
myNumbers[5] = 3; // will fail, array just have 5 positions
```
**[Edit]**
```
additionalNumbers=(byte) (coincidenceNumbers.Next(1,50));
```
Here, coincidenceNumbers is a Random object, so it will generate random numbers. Its "Next" function will generate an integer number. It receives 2 parameters: minimum value and maximum value. So, here it will generate a random number between 1 and 50.
Integer is very big compared with byte, so there is a "casting"... the integer number will be converted to byte.
If integer number less than 255, no problem, in other case you will loss precision
If you try to do this
```
int x = 500;
byte y = (byte) x;
Console.WriteLine(y); // 244, precision lost
``` | You need to read some basic education material on arrays, try [MSDN Arrays Tutorial](http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx) for example. | question about Arrays | [
"",
"c#",
"random",
"numbers",
""
] |
Compare the following two pieces of code, the first using a reference to a large object, and the second has the large object as the return value. The emphasis on a "large object" refers to the fact that repeated copies of the object, unnecessarily, is wasted cycles.
Using a reference to a large object:
```
void getObjData( LargeObj& a )
{
a.reset() ;
a.fillWithData() ;
}
int main()
{
LargeObj a ;
getObjData( a ) ;
}
```
Using the large object as a return value:
```
LargeObj getObjData()
{
LargeObj a ;
a.fillWithData() ;
return a ;
}
int main()
{
LargeObj a = getObjData() ;
}
```
The first snippet of code does not require copying the large object.
In the second snippet, the object is created inside the function, and so in general, a copy is needed when returning the object. In this case, however, in `main()` the object is being declared. Will the compiler first create a default-constructed object, then copy the object returned by `getObjData()`, or will it be as efficient as the first snippet?
I think the second snippet is easier to read but I am afraid it is less efficient.
**Edit:** Typically, I am thinking of cases `LargeObj` to be generic container classes that, for the sake of argument, contains thousands of objects inside of them. For example,
```
typedef std::vector<HugeObj> LargeObj ;
```
so directly modifying/adding methods to `LargeObj` isn't a directly accessible solution. | The second approach is more idiomatic, and expressive. It is clear when reading the code that the function has no preconditions on the argument (it does not have an argument) and that it will actually create an object inside. The first approach is not so clear for the casual reader. The call implies that the object will be changed (pass by reference) but it is not so clear if there are any preconditions on the passed object.
About the copies. The code you posted is not using the assignment operator, but rather copy construction. The C++ defines the [return value optimization](http://en.wikipedia.org/wiki/Return_value_optimization) that is implemented in all major compilers. If you are not sure you can run the following snippet in your compiler:
```
#include <iostream>
class X
{
public:
X() { std::cout << "X::X()" << std::endl; }
X( X const & ) { std::cout << "X::X( X const & )" << std::endl; }
X& operator=( X const & ) { std::cout << "X::operator=(X const &)" << std::endl; }
};
X f() {
X tmp;
return tmp;
}
int main() {
X x = f();
}
```
With g++ you will get a single line *X::X()*. The compiler reserves the space in the stack for the *x* object, then calls the function that constructs the *tmp* over *x* (in fact *tmp* **is** *x*. The operations inside *f()* are applied directly on *x*, being equivalent to your first code snippet (pass by reference).
If you were not using the copy constructor (had you written: *X x; x = f();*) then it would create both *x* and *tmp* and apply the assignment operator, yielding a three line output: *X::X()* / *X::X()* / *X::operator=*. So it could be a little less efficient in cases. | Use the second approach. It may seem that to be less efficient, but the C++ standard allows the copies to be evaded. This optimization is called [Named Return Value Optimization](http://www.google.com/search?q=NRVO) and is implemented in most current compilers. | Returning Large Objects in Functions | [
"",
"c++",
""
] |
I'm getting the following error trying to define a list of "Lines":
> line-clip.cpp:44: error: expected
> initializer before '<' token
```
#include <list>
using namespace std;
class Line {
public:
Point p1;
Point p2;
Line(Point P1, Point P2)
{
p1 = P1;
p2 = P2;
}
}
// Line List
list <Line> lineList;
```
How do you define a generic List of type "Line"? | You need a semicolon after your class declaration :-).
```
class Line {
...
}; // put a semicolon here.
``` | Your missing a semicolon at the end of your class. | How do I define a generic std::list of a custom type? | [
"",
"c++",
"list",
""
] |
I'm currently trying to optimize my website, which is run on the Google App Engine. It's not an easy task, because I'm not using any powerful tool.
Does anyone have experience in optimizing Python code for this purpose?
Have you find a good Python profiler? | I have found [Gprof2Dot](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret.
Gprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each function (function name, percentage of time spend on this function, and number of calls).
[An example graph (1429x1896px)](http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png)
I've not done much with the App Engine, but when profiling non-webapp scripts, I tend to profile the script that runs all the unittests, which may not be very accurate to real-world situations
One (better?) method would be to have a script that does a fake WSGI request, then profile that.
WSGI is really simple protocol, it's basically a function that takes two arguments, one with request info and the second with a callback function (which is used for setting headers, among other things). Perhaps something like the following (which is possible-working pseudo code)...
```
class IndexHandler(webapp.RequestHandler):
"""Your site"""
def get(self):
self.response.out.write("hi")
if __name__ == '__main__':
application = webapp.WSGIApplication([
('.*', IndexHandler),
], debug=True)
# Start fake-request/profiling bit
urls = [
"/",
"/blog/view/hello",
"/admin/post/edit/hello",
"/makeanerror404",
"/makeanerror500"
]
def fake_wsgi_callback(response, headers):
"""Prints heads to stdout"""
print("\n".join(["%s: %s" % (n, v) for n, v in headers]))
print("\n")
for request_url in urls:
html = application({
'REQUEST_METHOD': 'GET',
'PATH_INFO': request_url},
fake_wsgi_callback
)
print html
```
Actually, the App Engine documentation explains a better way of profiling your application:
From <http://code.google.com/appengine/kb/commontasks.html#profiling>:
> To profile your application's performance, first rename your application's `main()` function to `real_main()`. Then, add a new main function to your application, named `profile_main()` such as the one below:
>
> ```
> def profile_main():
> # This is the main function for profiling
> # We've renamed our original main() above to real_main()
> import cProfile, pstats
> prof = cProfile.Profile()
> prof = prof.runctx("real_main()", globals(), locals())
> print "<pre>"
> stats = pstats.Stats(prof)
> stats.sort_stats("time") # Or cumulative
> stats.print_stats(80) # 80 = how many to print
> # The rest is optional.
> # stats.print_callees()
> # stats.print_callers()
> print "</pre>"
> ```
>
> [...]
>
> To enable the profiling with your application, set `main = profile_main`. To run your application as normal, simply set `main = real_main`. | [App Engine Mini Profiler](https://github.com/kamens/gae_mini_profiler) is a new, drop-in app engine performance tool that gives both API call perf information (via Appstats) and standard profiling data for all function calls (via cProfiler)
<https://github.com/kamens/gae_mini_profiler> | Best way to profile/optimize a website on Google App Engine | [
"",
"python",
"google-app-engine",
""
] |
Before asking you my question directly, I'm going to describe the nature of my prolem.
I'm coding a 2D simulation using C++/OpenGL with the GLFW library. And I need to manage a lot of threads properly. In GLFW we have to call the function:
thread = glfwCreateThread(ThreadFunc, NULL); (the first parameter is the function that'll execute the thread, and the second represents the parameters of this function).
And glfwCreateThread, has to be called every time! (ie: in each cycle). This way of working, doesn't really help me, because it breaks the way i'm building my code because i need to create threads out of the main loop scope. So I'm creating a ThreadManager class, that'll have the following prototype :
```
class ThreadManager {
public:
ThreadManager();
void AddThread(void*, void GLFWCALL (*pt2Func)(void*));
void DeleteThread(void GLFWCALL (*pt2Func)(void*));
void ExecuteAllThreads();
private:
vector<void GLFWCALL (*pt2Func)(void*)> list_functions;
// some attributs
};
```
So for example, if I want to add a specific thread I'll just need to call AddThread with the specific parameters, and the specific function. And the goal is just to be able to call: ExecuteAllThreads(); inside the main loop scope. But for this i need to have something like:
```
void ExecuteAllThreads() {
vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter_end = list_functions.end();
for(vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(&(iter*), param);
}
}
```
And inside AddThread, I'll just have to add the function referenced by the pt2Func to the vector : list\_functions.
Alright, this is the general idea of what i want to do.. is it the right way to go ? You have a better idea ? How to do this, really ? (I mean the problem is the syntax, i'm not sure how to do this).
Thank you ! | You need to create threads in each simulation cycle? That sounds suspicious. Create your threads once, and reuse them.
Thread creation isn't a cheap operation. You definitely don't want to do that in every iteration step.
If possible, I'd recommend you use Boost.Thread for threads instead, to give you type safety and other handy features. Threading is complicated enough without throwing away type safety and working against a primitive C API.
That said, what you're asking is possible, although it gets messy. First, you need to store the arguments for the functions as well, so your class looks something like this:
```
class ThreadManager {
public:
typedef void GLFWCALL (*pt2Func)(void*); // Just a convenience typedef
typedef std::vector<std::pair<pt2Func, void*> > func_vector;
ThreadManager();
void AddThread(void*, pt2Func);
void DeleteThread(pt2Func);
void ExecuteAllThreads();
private:
func_vector list_functions;
};
```
And then ExecuteAllThreads:
```
void ExecuteAllThreads() {
func_vector::const_iterator iter_end = list_functions.end();
for(func_vector::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(iter->first, iter->second);
}
}
```
And of course inside AddThread you'd have to add a pair of function pointer and argument to the vector.
Note that Boost.Thread would solve most of this a lot cleaner, since it expects a thread to be a functor (which can hold state, and therefore doesn't need explicit arguments).
Your thread function could be defined something like this:
```
class MyThread {
MyThread(/* Pass whatever arguments you want in the constructor, and store them in the object as members */);
void operator()() {
// The actual thread function
}
};
```
And since the operator() doesn't take any parameters, it becomes a lot simpler to start the thread. | What about trying to store them using boost::function ?
They could simulate your specific functions, since they behave like real objects but in fact are simple functors. | How to maintain a list of functions in C++/STL? | [
"",
"c++",
"multithreading",
"vector",
"glfw",
""
] |
What is the best and easiest method that can be used for inter-process communication in a very large project?
My requirement is to communicate between a normal Windows Forms Application and Windows Services.
Methods that are easy to maintain and implement are preferred.
Thanks | From the tags I understand that we are talking about .NET. Perhaps you should try Microsoft WCF. It unifies this issue, abstracting specific inter-process (inter-service) communication technology from actual code. So generally you'll design and write the interfaces that your processes will use to talk to each other and then you'll configure a specific communication technology in XML config file. That is, you have rather clear separation between "what do the processes talk about" and "how is this communication implemented specifically".
WCF supports SOAP, TCP\IP communication, MSMQ etc., you processes can be IIS-hosted web-services, usual Windows services, console applications etc. - all this under unified framework. I think, this is exactly what you are looking for. | It really depends on the project as there are a large number of methods.
This may depend on where the different portions of the project run (They could run on different servers, or different technology stacks altogether.).
The most common method is probably web services. Although these come with an overhead, so it may be worth looking at a simple interface API via a DLL.
Whatever you do it should probably be thought about and designed carefully, considering security and performance, and how you will extend or modify it in the future. | Best and Easiest Method for inter-process communication in large project | [
"",
"c#",
".net",
"ipc",
""
] |
What I am trying to do is find out which fields were updated and record the change to a different table.
```
DECLARE
@BillNo int,
@column_name varchar(500)
SELECT @BillNo = BillNo FROM INSERTED
DECLARE HistoryMonitorLoop CURSOR FOR
SELECT
column_name
FROM
information_schema.columns
WHERE
table_name = 'Shipment';
OPEN HistoryMonitorLoop
FETCH next FROM HistoryMonitorLoop INTO @column_name
WHILE @@Fetch_status = 0
BEGIN
DECLARE
@OldValue varchar(500),
@NewValue varchar(500)
SET @OldValue = (SELECT @column_name FROM Deleted);
SET @NewValue = (SELECT @column_name FROM Inserted);
IF(@OldValue != @NewValue)
BEGIN
DECLARE @Comment varchar(5000)
SELECT @Comment = @column_name + ' Changed from ' + @OldValue + ' to ' + @NewValue
EXEC ShipmentNote_Insert @BillNo=@BillNo,@CoordinatorID=1,@Comment=@Comment
END
FETCH next FROM HistoryMonitorLoop INTO @column_name
END
CLOSE HistoryMonitorLoop
DEALLOCATE HistoryMonitorLoop
```
what is happening is the
```
SET @OldValue = (SELECT @column_name FROM Deleted);
SET @NewValue = (SELECT @column_name FROM Inserted);
```
are setting the `@OldValue` and `@NewValue` = to the columnname instead of the value of the column – sql is processing it as `SET @OldValue = (SELECT 'column_name' FROM Deleted);` | See this [Pop on the Audit Trail](http://www.simple-talk.com/sql/database-administration/pop-rivetts-sql-server-faq-no.5-pop-on-the-audit-trail/) It uses a query in a loop as opposed to a cursor, to do just what you're wanting to do. | > What I am trying to do is find out which fields were updated
In SQL Server there are two functions that does exactly what you are looking for.
* [Columns\_Updated()](http://msdn.microsoft.com/en-us/library/ms186329.aspx) - Check if one or more column(s) is/are inserted/deleted within trigger
* [Update()](http://msdn.microsoft.com/en-us/library/ms187326.aspx) - Check if a single column is updated within trigger | Trigger based history | [
"",
"sql",
"triggers",
"history",
"tracking",
"sql-update",
""
] |
I'm working on a project with a DLL and an EXE in visual studio 2005. Amongst the code for the DLL is a template for a growable array class:
```
template <class Type>
class GArray
{
Type *p;
uint32 len;
uint32 alloc;
protected:
bool fixed;
public:
/// Constructor
GArray(int PreAlloc = 0)
{
p = 0;
len = 0;
fixed = false;
alloc = PreAlloc;
if (alloc)
{
int Bytes = sizeof(Type) * alloc;
p = (Type*) malloc(Bytes);
if (p)
{
memset(p, 0, Bytes);
}
else
{
alloc = 0;
}
}
}
/// Destructor
~GArray()
{
Length(0);
}
/// Returns the number of used entries
uint32 Length() const
{
return len;
}
/// Sets the length of available entries
bool Length(uint32 i)
{
if (i > 0)
{
if (i > len && fixed)
return false;
uint nalloc = alloc;
if (i < len)
{
// Shrinking
}
else
{
// Expanding
int b;
for (b = 4; (1 << b) < i; b++)
;
nalloc = 1 << b;
LgiAssert(nalloc >= i);
}
if (nalloc != alloc)
{
Type *np = (Type*)malloc(sizeof(Type) * nalloc);
if (!np)
{
return false;
}
if (p)
{
// copy across common elements
memcpy(np, p, min(len, i) * sizeof(Type));
free(p);
}
p = np;
alloc = nalloc;
}
if (i > len)
{
// zero new elements
memset(p + len, 0, sizeof(Type) * (i - len));
}
len = i;
}
else
{
if (p)
{
int Length = len;
for (uint i=0; i<Length; i++)
{
p[i].~Type();
}
free(p);
p = 0;
}
len = alloc = 0;
}
return true;
}
GArray<Type> &operator =(const GArray<Type> &a)
{
Length(a.Length());
if (p && a.p)
{
for (int i=0; i<len; i++)
{
p[i] = a.p[i];
}
}
return *this;
}
/// \brief Returns a reference a given entry.
///
/// If the entry is off the end of the array and "fixed" is false,
/// it will grow to make it valid.
Type &operator [](uint32 i)
{
static Type t;
if
(
i < 0
||
(fixed && i >= len)
)
{
ZeroObj(t);
return t;
}
#if 0
if (i > 15000000)
{
#if defined(_DEBUG) && defined(_MSC_VER)
LgiAssert(0);
#endif
ZeroObj(t);
return t;
}
#endif
if (i >= alloc)
{
// increase array length
uint nalloc = max(alloc, GARRAY_MIN_SIZE);
while (nalloc <= i)
{
nalloc <<= 1;
}
// alloc new array
Type *np = (Type*) malloc(sizeof(Type) * nalloc);
if (np)
{
// clear new cells
memset(np + len, 0, (nalloc - len) * sizeof(Type));
if (p)
{
// copy across old cells
memcpy(np, p, len * sizeof(Type));
// clear old array
free(p);
}
// new values
p = np;
alloc = nalloc;
}
else
{
static Type *t = 0;
return *t;
}
}
// adjust length of the the array
if (i + 1 > len)
{
len = i + 1;
}
return p[i];
}
/// Delete all the entries as if they are pointers to objects
void DeleteObjects()
{
for (uint i=0; i<len; i++)
{
DeleteObj(p[i]);
}
Length(0);
}
/// Delete all the entries as if they are pointers to arrays
void DeleteArrays()
{
for (int i=0; i<len; i++)
{
DeleteArray(p[i]);
}
Length(0);
}
/// Find the index of entry 'n'
int IndexOf(Type n)
{
for (uint i=0; i<len; i++)
{
if (p[i] == n) return i;
}
return -1;
}
/// Returns true if the item 'n' is in the array
bool HasItem(Type n)
{
return IndexOf(n) >= 0;
}
/// Deletes an entry
bool DeleteAt
(
/// The index of the entry to delete
uint Index,
/// true if the order of the array matters, otherwise false.
bool Ordered = false
)
{
if (p && Index >= 0 && Index < len)
{
// Delete the object
p[Index].~Type();
// Move the memory up
if (Index < len - 1)
{
if (Ordered)
{
memmove(p + Index, p + Index + 1, (len - Index - 1) * sizeof(Type) );
}
else
{
p[Index] = p[len-1];
}
}
// Adjust length
len--;
return true;
}
return false;
}
/// Deletes the entry 'n'
bool Delete
(
/// The value of the entry to delete
Type n,
/// true if the order of the array matters, otherwise false.
bool Ordered = false
)
{
int i = IndexOf(n);
if (p && i >= 0)
{
return DeleteAt(i, Ordered);
}
return false;
}
/// Appends an element
void Add
(
/// Item to insert
const Type &n
)
{
(*this)[len] = n;
}
/// Appends multiple elements
void Add
(
/// Items to insert
Type *s,
/// Length of array
int count
)
{
if (!s || count < 1)
return;
int i = len;
Length(len + count);
Type *d = p + i;
while (count--)
{
*d++ = *s++;
}
}
/// Inserts an element into the array
bool AddAt
(
/// Item to insert before
int Index,
/// Item to insert
Type n
)
{
// Make room
if (Length(len + 1))
{
if (Index < len - 1)
{
// Shift elements after insert point up one
memmove(p + Index + 1, p + Index, (len - Index - 1) * sizeof(Type) );
}
else if (Index >= len)
{
// Add at the end, not after the end...
Index = len - 1;
}
// Insert item
p[Index] = n;
return true;
}
return false;
}
/// Sorts the array
void Sort(int (*Compare)(Type*, Type*))
{
typedef int (*qsort_compare)(const void *, const void *);
qsort(p, len, sizeof(Type), (qsort_compare)Compare);
}
/// \returns a reference to a new object on the end of the array
Type &New()
{
return (*this)[len];
}
/// Returns the memory held by the array and sets itself to empty
Type *Release()
{
Type *Ptr = p;
p = 0;
len = alloc = 0;
return Ptr;
}
};
```
I've reused this code in the EXE in several places. However when I use it in one particular file I start getting duplicate symbol link errors:
```
2>lgi8d.lib(Lgi8d.dll) : error LNK2005: "public: int __thiscall GArray<char *>::Length(void)" (?Length@?$GArray@PAD@@QAEHXZ) already defined in FrameStore.obj
2>D:\Home\matthew\network_camera\src\vod_test\Debug\vod_test.exe : fatal error LNK1169: one or more multiply defined symbols found
```
I've used the same class in other files in the EXE without error. e.g. in Camera.cpp I have:
```
void DeleteFromArray(GArray<char> &a, int Start, int Len)
{
assert(Len >= 0);
int64 StartTs = LgiCurrentTime();
int Del = min(Len, a.Length() - Start);
if (Del > 0)
{
int Remain = a.Length() - Start - Del;
if (Remain > 0)
{
memmove(&a[Start], &a[Start+Del], Remain);
MoveBytes += Remain;
a.Length(Start+Remain);
}
else a.Length(Start);
}
int64 End = LgiCurrentTime();
DeleteTime += End - StartTs;
}
```
which compiles and links ok... but in FrameStore.cpp:
```
void Scan()
{
if (!Init)
{
Init = true;
GAutoString Path = FrameFile::GetPath();
GAutoPtr<GDirectory> Dir(FileDev->GetDir());
GArray<char*> k;
int64 Size = 0;
for (bool b = Dir->First(Path); b; b = Dir->Next())
{
if (!Dir->IsDir())
{
char *e = LgiGetExtension(Dir->GetName());
if (e && !stricmp(e, "mjv"))
{
char p[MAX_PATH];
Dir->Path(p, sizeof(p));
k.Add(NewStr(p));
Size += Dir->GetSize();
}
}
}
GAutoPtr<Prog> p(new Prog(Size));
for (int i=0; i<k.Length(); i++)
{
Files.Add(new FrameFile(k[i], p));
}
k.DeleteArrays();
}
}
```
Causes the link error on the line with "k.Length()" in it... if I comment out that it links! Yet I'm using other methods in the GArray class in the same code and they don't cause a problem.
Why should a template class thats defined entirely in a header be having this issue in the first place? | The problem:
There is another class defined in Lgi.dll that exports the GArray instantiation.
```
#ifdef LGI_DLL
#define LgiClass __declspec(dllexport)
#else
#define LgiClass __declspec(dllimport)
#endif
class LgiClass GToken : public GArray<char*>
{
/// stuff...
};
```
The solution:
Include that GToken header in my EXE, specifically the FrameStore.cpp file that uses the GArray implementation, then the compile will import those symbols from the DLL instead of duplicate them.
It would have been nice if the compiler could give me more of a hint at where the DLL was defining the symbol. Simply saying "there a duplicate somewhere" is not very helpful. | Why don't you use std::vector instead? | C++ Multiply defined symbols using a header defined template class | [
"",
"c++",
"templates",
"visual-studio-2005",
""
] |
What would be the best way to reverse the order of space-separated words in a string?
```
Hello everybody in stackoverflow
```
becomes
```
stackoverflow in everybody Hello
``` | Try this:
```
$s = 'Hello everybody in stackoverflow';
echo implode(' ', array_reverse(explode(' ', $s)));
``` | In prose that is:
* First turn the string into an array of words
```
$words = explode(' ', $string);
```
* Second, inverse the order of the elements in that array
```
$reversed_string = implode(' ', array_reverse($words));
```
Reading the whole list of string and array functions in PHP is VERY helpful and will save tons of time. | Reverse the order of space-separated words in a string | [
"",
"php",
"string",
"reverse",
""
] |
What types of exceptions should be thrown for invalid or unexpected parameters in .NET? When would I choose one instead of another?
## Follow-up:
Which exception would you use if you have a function expecting an integer corresponding to a month and you passed in '42'? Would this fall into the "out of range" category even though it's not a collection? | I like to use: `ArgumentException`, `ArgumentNullException`, and `ArgumentOutOfRangeException`.
* [`ArgumentException`](http://msdn.microsoft.com/en-us/library/system.argumentexception(loband).aspx) – Something is wrong with the argument.
* [`ArgumentNullException`](http://msdn.microsoft.com/en-us/library/system.argumentnullexception(loband).aspx) – Argument is null.
* [`ArgumentOutOfRangeException`](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception(loband).aspx) – I don’t use this one much, but a common use is indexing into a collection, and giving an index which is to large.
There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:
* [`InvalidOperationException`](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception(loband).aspx) – The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote [his answer](https://stackoverflow.com/a/774149) up as well.
* [`NotSupportedException`](http://msdn.microsoft.com/en-us/library/system.notsupportedexception(loband).aspx) – The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.
The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.
I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. [“Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”](http://support.microsoft.com/kb/927917). When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.
Thanks to STW (ex Yoooder) again for the comments.
---
In response to your followup, I would throw an [`ArgumentOutOfRangeException`](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception(loband).aspx). Look at what MSDN says about this exception:
> `ArgumentOutOfRangeException` is thrown
> when a method is invoked and at least
> one of the arguments passed to the
> method is not null
> reference (`Nothing` in Visual Basic)
> and does not contain a valid value.
So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say `ArgumentOutOfRangeException`, another developer might say `ArgumentException`. Make it easy and document the behavior. | I voted for [Josh's answer](https://stackoverflow.com/questions/774104/what-exceptions-should-be-thrown-for-invalid-or-unexpected-parameters-in-net/774116#774116), but would like to add one more to the list:
System.InvalidOperationException should be thrown if the argument is valid, but the object is in a state where the argument shouldn't be used.
**Update** Taken from MSDN:
> InvalidOperationException is used in
> cases when the failure to invoke a
> method is caused by reasons other than
> invalid arguments.
Let's say that your object has a PerformAction(enmSomeAction action) method, valid enmSomeActions are Open and Close. If you call PerformAction(enmSomeAction.Open) twice in a row then the second call should throw the InvalidOperationException (since the arugment was valid, but not for the current state of the control)
Since you're already doing the right thing by programming defensively I have one other exception to mention is ObjectDisposedException. **If** your object implements IDisposable then you should always have a class variable tracking the disposed state; if your object has been disposed and a method gets called on it you should raise the ObjectDisposedException:
```
public void SomeMethod()
{
If (m_Disposed) {
throw new ObjectDisposedException("Object has been disposed")
}
// ... Normal execution code
}
```
**Update:** To answer your follow-up: It is a bit of an ambiguous situation, and is made a little more complicated by a generic (not in the .NET Generics sense) data type being used to represent a specific set of data; an enum or other strongly typed object would be a more ideal fit--but we don't always have that control.
I would personally lean towards the ArgumentOutOfRangeException and provide a message that indicates the valid values are 1-12. My reasoning is that when you talk about months, assuming all integer representations of months are valid, then you are expecting a value in the range of 1-12. If only certain months (like months that had 31 days) were valid then you would not be dealing with a Range per-se and I would throw a generic ArgumentException that indicated the valid values, and I would also document them in the method's comments. | What exceptions should be thrown for invalid or unexpected parameters in .NET? | [
"",
"c#",
".net",
"vb.net",
"exception",
""
] |
I learned the [intersperse function](http://haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v:intersperse) from Haskell, and have been looking for an implementation in c#.
Intersperse takes 2 arguments, an IEnumerable<T> source and a T element. It returns an IEnumerable with element inserted between every element of source.
One possible use-case is to put an arbitrary integer in between a list of integers, for example:
```
// returns: {1, 0, 2, 0, 3}
(List<int>() {1, 2, 3}).Intersperse(0);
```
This is a general case of string.Join(...). | Something the others have missed: if you only want it in between items, and not also in front or behind, you need to do an extra check:
```
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
bool first = true;
foreach (T value in source)
{
if (!first) yield return element;
yield return value;
first = false;
}
}
```
or
```
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
var e = source.GetEnumerator();
bool b = e.MoveNext();
if (b) yield return e.Current;
while (e.MoveNext())
{
yield return element;
yield return e.Current;
}
}
``` | I've coded up a solution that is lazy, in the spirit of Linq solutions! Other solutions I came up with involved traversing the entire list before returning data, and then returning the resulting list.
Some of the other answers have an if check on every iteration of the loop.
```
public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> source, T element)
{
using (var enumerator = source.GetEnumerator()) {
if (enumerator.MoveNext()) {
yield return enumerator.Current;
while (enumerator.MoveNext()) {
yield return element;
yield return enumerator.Current;
}
}
}
}
``` | Extension method for Enumerable.Intersperse? | [
"",
"c#",
"ienumerable",
""
] |
I'm using the PHP `mail()` function to send email from a contact form. The function returns `true` so should be fine. But I'm not receiving the email.
I've seen posts that say you should always use the *From* and *Reply-To* headers in PHP mail to make sure it's delivered. I've tried various configs but nothing is working yet.
Is there any other way to debug the `mail()` function? | Most of the time this problem is due to headers, the mail might get send but the SMTP server might never deliver it at all because of faulty headers
I'd suggest you to use a mailing class for PHP such as [phpMailer](http://phpmailer.codeworxtech.com/) which handles all of your problems with headers and has a really nice interface to use
cheers | If you are on windows you will need to install an SMTP server.
If you are on linux you will need to enable sendmail and ensure the user account PHP is installed on has access to the sendmail binary.
Ask your host if your account has sufficient permissions to access the binary.
Posting your code here might also help in case it is an error in there you overlooked. | Reasons why PHP mail might not be working | [
"",
"php",
"email",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.