Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Lets say, user go to "profile.php" page, but it requires login. Then it redirects to login page. But after login, it should redirect back to profile.php page. How do i do that?
How to get current URL in php?
$\_SERVER['URI']???? | Most sites simply pass a variable to the login form like this:
```
redirect(login.php?returnUrl=original_page.php);
```
Then after the login is processed, it could redirect back to the page which returnUrl is pointing to. If there is no returnURl variable, then call the default one (index.php or default.php).
Hope this help. | To get current page url concat `$_SERVER["SERVER_NAME"]` and `$_SERVER["REQUEST_URI"]`.
What you could do is create a session variable when you detect that user needs to sign in. Then redirect it to login page, handle signing and after you verify that his credentials were correct you can retrieve the value from the session and redirect him to the page he was requesting. | Redirect to older page in php? | [
"",
"php",
"url",
"redirect",
""
] |
I'm creating a c# winforms project that can be run as a GUI or can be operated from the command line. Currently, I can process command line input and arguments. I can run the program from command line and I can use the program to process the arguments. But Console.Writeline() does absolutely nothing. Any clue why that could be? | For the most part, see the [answer here](https://stackoverflow.com/questions/807998/). However, I would like to point out the existence of the `FreeConsole()` API call, which allows you to gracefully close the console.
```
[DllImport("kernel32.dll")]
static extern int FreeConsole()
```
One thing I'd like to note: you may see some weirdness of a command prompt appearing in front of your console output, if you're launching from an existing console and attaching to that with `AttachConsole` (as opposed to `AllocConsole`).
This is a timing issue which is hard to work around. If that's a problem, set your application to be a Console application like the others suggested. It will have the effect of no command prompt appearing until the application closes however, which might not be what you want if you're opening a winform.
**In response to your comment**: it's either `AttachConsole` *or* `AllocConsole`. The example I linked tries to attach to an existing console first. If that fails (most likely because it doesn't exist), it creates a new console window instead.
If you find a way to have the best of both worlds in terms of command-line behavior and GUI interactive mode, please let me know. I haven't done any in-depth searching for a solution, but I have a few minor apps that would benefit.
By the way: if you plan on using **pipes** on your command line (redirecting output to a file for example), that won't work like this unfortunately. | You can enable the console in a windows forms app using the following DllImports:
```
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int FreeConsole();
```
You can then enable the console using:
```
AttachConsole(ATTACH_PARENT_PROCESS);
```
And you can disable it using:
```
FreeConsole();
``` | Console.Writeline() not working | [
"",
"c#",
"command-line",
"console",
""
] |
Is anyone aware of a good managed code .NET component which can do HTML Diffs? I'd like to compare two HTML files and show the differences. | Microsoft has a managed-code tool called [XmlDiffPatch](http://msdn.microsoft.com/en-us/library/aa302294.aspx), which should work for HTML files as well. You can run it as a stand-alone executable, or import the diff assemblies into your project. | Check the [htmldiff.net](https://github.com/Rohland/htmldiff.net "htmldiff.net") project out. | HTML Diff Component for .NET | [
"",
"c#",
".net",
"diff",
""
] |
While reading another question, i came to a problem with partial ordering, which i cut down to the following test-case
```
template<typename T>
struct Const { typedef void type; };
template<typename T>
void f(T, typename Const<T>::type*) { cout << "Const"; } // T1
template<typename T>
void f(T, void*) { cout << "void*"; } // T2
int main() {
// GCC chokes on f(0, 0) (not being able to match against T1)
void *p = 0;
f(0, p);
}
```
For both function templates, the function type of the specialization that enters overload resolution is `void(int, void*)`. But partial ordering (according to comeau and GCC) now says that the second template is more specialized. But why?
Let me go through partial ordering and show where i have questions. May `Q` be an unique made-up type used for determining partial ordering according to `14.5.5.2`.
* Transformed parameter-list for `T1` (Q inserted): `(Q, typename Const<Q>::type*)`. The types of the arguments are `AT` = `(Q, void*)`
* Transformed parameter-list for `T2` (Q inserted): `BT` = `(Q, void*)`, which are also the types of the arguments.
* Non-transformed parameter-list for `T1`: `(T, typename Const<T>::type*)`
* Non-transformed parameter-list for `T2`: `(T, void*)`
Since C++03 under-specifies this, i did use the intention that i read about in several defect reports. The above transformed parameter list for `T1` (called `AT` by me) is used as argument list for `14.8.2.1` *"Deducing template arguments from a function call"*.
`14.8.2.1` does not need to transform `AT` or `BT` itself anymore (like, removing reference declarators, etc), and goes straight to `14.8.2.4`, which independently for each `A` / `P` pair does type deduction:
* `AT` against `T2`: **`{`** `(Q, T)`**`,`** `(void*, void*)` **`}`**. `T` is the only template parameter here, and it will find that `T` must be `Q`. Type deduction succeeds trivially for `AT` against `T2`.
* `BT` against `T1`: **`{`** `(Q, T)`**`,`** `(void*, typename Const<T>::type*)` **`}`**. It will find that `T` is `Q`, too here. `typename Const<T>::type*` is an un-deduced context, and so it won't be used to deduce anything.
---
Here is my first question: Will this now use the value of `T` deduced for the first parameter? If the answer is no, then the first template is more specialized. This can't be the case, because both GCC and Comeau say that the second template is more specialized, and i don't believe they are wrong. So we assume "yes", and insert `void*` into `T`. The paragraph (`14.8.2.4`) says *"Deduction is done independently for each pair and the results are then combined"* and also *"In certain contexts, however, the value does not participate in type deduction, but instead uses the values of template arguments that were either deduced elsewhere or explicitly specified."* This sounds like "yes" too.
Deduction therefore succeeds too, for every A / P pair. Now, each template is at least as specialized as the other, because deduction didn't also rely on any implicit conversions and succeeded in both directions. As a result, the call should be ambiguous.
So my second question: Now, why do the implementations say that the second template is more specialized? What point did i overlook?
---
**Edit**: I tested explicit specialization and instantiation, and both, in recent GCC versions (`4.4`) tell me that the reference to the specialization is ambiguous, while an older version of GCC (`4.1`) doesn't rise that ambiguity error. This suggests that recent GCC versions have inconsistent partial ordering for function templates.
```
template<typename T>
struct Const { typedef void type; };
template<typename T>
void f(T, typename Const<T>::type*) { cout << "Const"; } // T1
template<typename T>
void f(T, void*) { cout << "void*"; } // T2
template<> void f(int, void*) { }
// main.cpp:11: error: ambiguous template specialization
// 'f<>' for 'void f(int, void*)'
``` | Here's my go at this. I agree with [Charles Bailey](https://stackoverflow.com/questions/1180325/partial-ordering-with-function-template-having-undeduced-context/1180531#1180531) that the incorrect step is to go from `Const<Q>::Type*` to `void*`
```
template<typename T>
void f(T, typename Const<T>::type*) { cout << "Const"; } // T1
template<typename T>
void f(T, void*) { cout << "void*"; } // T2
```
The steps we want to take are:
14.5.5.2/2
> Given two overloaded function templates, whether one is more specialized than another can be determined by transforming each template in turn and using argument deduction (14.8.2) to compare it to the other.
14.5.5.2/3-b1
> For each type template parameter, synthesize a unique type and substitute that for each occurrence of that parameter in the function parameter list, or for a template conversion function, in the return type.
In my opinion, the types are synthesized as follows:
```
(Q, Const<Q>::Type*) // Q1
(Q, void*) // Q2
```
I don't see any wording that requires that the second synthesized parameter of `T1` be `void*`. I don't know of any precedent for that in other contexts either. The type `Const<Q>::Type*` is perfectly valid type within the C++ type system.
So now we perform the deduction steps:
**Q2 to T1**
We try to deduce the template parameters for T1 so we have:
* Parameter 1: `T` is deduced to be `Q`
* Parameter 2: Nondeduced context
Even though parameter 2 is a non deduced context, deduction has still succeeded because we have a value for T.
**Q1 to T2**
Deducing the template parameters for T2 we have:
* Parameter 1: `T` is deduced to be `Q`
* Parameter 2: `void*` does not match `Const<Q>::Type*` so deduction failure.
IMHO, here's where the standard lets us down. The parameter is not dependent so it's not really clear what should happen, however, my experience (based on a squinted read of 14.8.2.1/3) is that even where the parameter type P is not dependent, then the argument type A should match it.
The synthesized arguments of T1 can be used to specialize T2, but not vice versa. T2 is therefore more specialized than T1 and so is the best function.
---
**UPDATE 1:**
Just to cover the poing about `Const<Q>::type` being void. Consider the following example:
```
template<typename T>
struct Const;
template<typename T>
void f(T, typename Const<T>::type*) // T1
{ typedef typename T::TYPE1 TYPE; }
template<typename T>
void f(T, void*) // T2
{ typedef typename T::TYPE2 TYPE ; }
template<>
struct Const <int>
{
typedef void type;
};
template<>
struct Const <long>
{
typedef long type;
};
void bar ()
{
void * p = 0;
f (0, p);
}
```
In the above, `Const<int>::type` is used when we're performing the usual overload resolution rules, but not when we get to the partial overloading rules. It would not be correct to choose an arbitrary specialization for `Const<Q>::type`. It may not be intuitive, but the compiler is quite happy to have a synthasized type of the form `Const<Q>::type*` and to use it during type deduction.
---
**UPDATE 2**
```
template <typename T, int I>
class Const
{
public:
typedef typename Const<T, I-1>::type type;
};
template <typename T>
class Const <T, 0>
{
public:
typedef void type;
};
template<typename T, int I>
void f(T (&)[I], typename Const<T, I>::type*) // T1
{ typedef typename T::TYPE1 TYPE; }
template<typename T, int I>
void f(T (&)[I], void*) // T2
{ typedef typename T::TYPE2 TYPE ; }
void bar ()
{
int array[10];
void * p = 0;
f (array, p);
}
```
When the `Const` template is instantiated with some value `I`, it recursively instantiates itself until `I` reaches 0. This is when the partial specialization `Const<T,0>` is selected. If we have a compiler which synthesizes some real type for the parameters of the function, then what value will the compiler choose for the array index? Say 10? Well, this would be fine for the above example but it wouldn't match the partial specialization `Const<T, 10 + 1>` which, conceptually at least, would result in an infinite number of recursive instantiations of the primary. Whatever value that it selected we could modify the end condition to be that value + 1, and then we'd have an infinite loop in the partial ordering algorithm.
I do not see how the partial ordering algorithm could correctly instantiate `Const` to find what `type` really is. | Edit: After studying [Clang's](http://clang.llvm.org) implementation (by Doug Gregor) of their partial ordering algorithm, I have come to agree with the rest of the posters that the original example is not 'intended' to be ambiguous - even though the standard is not as clear as it could be about what should happen in such situations. I have edited this post to indicate my revised thoughts (for my own benefit & reference). In particular Clang's algorithm clarified that '`typename Const<T>::type`' is not translated into 'void' during the partial ordering step - and that each A/P pair is deduced independent of each other.
Initially I wondered why the following was considered ambiguous:
```
template<class T> void f(T,T*); // 1
template<class T> void f(T, int*); // 2
f(0, (int*)0); // ambiguous
```
`(The above is ambiguous because one cannot deduce f1(U1,U1*) from f2(T,int*), and going the other way, one cannot deduce f2(U2,int*) from f1(T,T*). Neither is more specialized.)`
but the following would not be ambiguous:
```
template<class T> struct X { typedef int type; };
template<class T> void f(T, typename X<T>::type*); // 3
template<class T> void f(T, int*); // 2
```
(The reason one could expect it to be ambiguous is if the following were to happen:
- `f3(U1,X<U1>::type*) -> f3(U1, int*) ==> f2(T,int*) (deduction ok, T=U1)`
- `f2(U2,int*) ==> f3(T, X<T>::type*) (deduction ok, T=U2 makes X<U2>::type* -> int*)`
If this were true, neither one would be more specialized than the other.)
After studying Clang's partial ordering algorithm it is clear that they treat '3' above as if it was:
```
template<class T, class S> void f(T, S*); // 4
```
so deduction of some unique 'U' against 'typename X::type' will succeed -
* `f3(U1,X<U1>::type*) is treated as f3(U1, U2*) ==> f2(T,int*) (deduction not ok)`
* `f2(U2,int*) ==> f3(T,S* [[X<T>::type*]]) (deduction ok, T=U2, S=int)`
And so '2' is clearly more specialized than '3'. | Partial ordering with function template having undeduced context | [
"",
"c++",
"templates",
"template-argument-deduction",
"function-templates",
"partial-ordering",
""
] |
Consider the following contrived example:
```
void HandleThat() { ... }
void HandleThis()
{
if (That) return HandleThat();
...
}
```
This code works just fine, and I'm fairly sure it's spec-valid, but I (perhaps on my own) consider this unusual style, since the call appears to return the result of the function, despite the fact that both functions are prototyped to be void.
Typically, I would expect to see:
```
if (That) {HandleThat(); return;}
```
which, I feel, leaves no ambiguity as to what's going on.
SO community, can I get your opinion on whether the returning-void coding style is confusing or problematic? It has the feel of an idiom; should I use this or avoid it?
Generally I'd strive for clarity and use the second style. On the other hand, there's a neatness to the first form that draws me to it somewhat. | I agree with you, the first style is confusing because there's the implication that some sort of value is getting returned. In fact I had to read it over a couple times *because* of that.
When returning from a function prototyped void, it should just be return; | This is probably just a little too clever. If that line ends up more than a couple of lines away from the top of the function, it'll be confusing. It also means the programmer looking at the code will need to correlate the
```
return HandleThat();
```
with the void return type and figure out the cleverness before they really understand the code. When you're doing more than one thing in an if/else branch, you should really use braces and put the steps on different lines. Takes up more space but is easier to understand:
```
if (That) {
HandleThat();
return;
}
``` | Stylistic question concerning returning void | [
"",
"c++",
"coding-style",
"idioms",
""
] |
A confusing title I know. Let me explain.
I have to marshal an array of structs, which then get converted to an array of classes (legacy compatibility). For instance
```
public class InnerClass {}
public class OuterClass { private InnerClass[] innerClasses; }
public struct InnerStruct {
// Data
}
private static buildInnerClass( InnerStruct i );
public struct OuterStruct {
private int _numInnerStructs;
private IntPtr _innerStructs;
// Other members
public InnerClass[] InnerClasses {
get {
InnerClass[] ret = new InnerClass[_numInnerStructs];
var structSize = Marshal.SizeOf(typeof(InnerStruct));
var ptr = _innerStructs;
for (int i = 0; i < _numInnerStructs; i++)
{
InnerStruct innerStruct = (InnerStruct)Marshal.PtrToStructure(
ptr, typeof(InnerStruct));
ret[i] = buildInnerClass(innerStruct);
ptr = (IntPtr)((int)ptr + structSize);
}
return ret;
}
}
}
``` | Viewed in a vacuum, there's nothing intrinsically wrong with this practice. However, you should be careful in that...
1. Property getters should--with few (if any) exceptions--not be "expensive" (ie, shouldn't consume many CPU cycles or resources to execute)
2. Property getters should NEVER cause side effects. For example, if your PInvoke code obtains a new handle of some kind then it should be a function, not a getter.
In general, keep in mind that properties should be written in such a way that the consumer shouldn't have much, if any, reason to cache the value versus calling the property again. If a responsible developer could follow that practice with your property, then you're on the right track. | The getter of a property should be as minimal as possible. In your case, it's probably better to use a regular method. Especially because returning an array from a property is also a bad idea. | Is it bad practice to put a lot of code in the get function of a property which wraps PInvoke stuff? | [
"",
"c#",
".net",
"properties",
"pinvoke",
"conventions",
""
] |
The following code ends with broken pipe when piped into tee, but behave correctly when not piped :
```
#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
return
print s
if __name__ == "__main__":
testfun()
sys.exit()
```
Expected output :
```
./bug.py
Ctrl-C pressed
```
What is observed when piped into tee is either a broken pipe or no output at all, ie nothing on tee stdout, and nothing in bug.log :
```
./bug.py | tee bug.log
Traceback (most recent call last):
File "./bug.py", line 14, in <module>
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
```
What can be the reason for this ? | When you hit Ctrl-C, the shell will terminate *both* processes (`python` and `tee`) and tear down the pipe connecting them.
So when you handle the Ctrl-C in your `python` process and flush, it'll find that `tee` has been terminated and the pipe is no more. Hence the error message.
(As an aside, would you expect anything in the log ? I don't see your process outputting anything other than the flush on exit) | Nope, hitting Ctrl-C does NOT terminate both processes. It terminates the tee process only,
the end of the tee process close the pipe between your script and tee, and hence your script dies with the broken pipe message.
To fix that, tee has an option to pass the Ctrl-C to its previous process in the pipe: -i
try: man tee
```
./bug.py
^CCtrl-C pressed
./bug.py | tee log
^CTraceback (most recent call last):
File "./bug.py", line 14, in <module>
testfun()
File "./bug.py", line 9, in testfun
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
./bug.py | tee -i log
^CCtrl-C pressed
``` | python stdout flush and tee | [
"",
"python",
"tee",
""
] |
How can I use python to find the longest word from a set of words?
I can find the first word like this:
```
'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
'a'
rfind is another subset
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
'a aa aaa'
``` | If I understand your question correctly:
```
>>> s = "a aa aaa aa"
>>> max(s.split(), key=len)
'aaa'
```
`split()` splits the string into words (seperated by whitespace); `max()` finds the largest element using the builtin `len()` function, i.e. the string length, as the key to find out what "largest" means. | Here is one from the category "How difficult can you make it", also violating the requirement that there should be no own class involved:
```
class C(object): pass
o = C()
o.i = 0
ss = 'a aa aaa aa'.split()
([setattr(o,'i',x) for x in range(len(ss)) if len(ss[x]) > len(ss[o.i])], ss[o.i])[1]
```
The interesting bit is that you use an object member to maintain state while the list is being computed in the comprehension, eventually discarding the list and only using the side-effect.
But please do use one of the **max()** solutions above :-) . | How to find the longest word with python? | [
"",
"python",
"cpu-word",
"max",
""
] |
I'm working with the jqueryui datepicker on this page - <http://jqueryui.com/demos/datepicker/>
How do I call it on a label instead of an input field? Is this possible? | I haven't looked at the code but I suspect that it assumes that it's attached to a `<input type="text">` element.
So assume that you must have that element.
You can hide the `<input>` and interact with the datepicker via calls to its methods from your label events.
```
$(labelselector).click(function() {
$(inputselector).datepicker('show');
});
``` | re: The positioning problem
The above suggestions didn't work for me to get a clean ui. I have my datepicker control activated when people click a label, and I didn't want the textbox shown at all (the above css attempt was close, but still the textbox got focus amongst other issues).
The solution for me was to make the textbox that the datepicker is attached to a < input type="hidden" .... /> This solved all the issues for me (I put the hidden input control just prior to the label so that the offset from the input control was right for my label).
Notably, setting a normal input controls style to display: none, or visibility: hidden, etc. did not work.
The reason this solution worked is due to the clauses in the source of the datepicker control that only perform certain functions if "type != "hidden". | How to call/bind a jquery datepicker to a label or div instead of an input field | [
"",
"javascript",
"jquery",
"datepicker",
""
] |
How do you display a custom [`UserControl`](http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol.aspx) as a dialog in C#/WPF (.NET 3.5)? | Place it in a [Window](http://msdn.microsoft.com/en-us/library/system.windows.window.aspx) and call [Window.ShowDialog](http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog.aspx).
(Also, add references to: PresentationCore, WindowsBase and PresentationFramework if you have not already done so.)
```
private void Button1_Click(object sender, EventArgs e)
{
Window window = new Window
{
Title = "My User Control Dialog",
Content = new MyUserControl()
};
window.ShowDialog();
}
``` | ```
Window window = new Window
{
Title = "My User Control Dialog",
Content = new OpenDialog(),
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.NoResize
};
window.ShowDialog();
```
Has worked like a magic for me.
Can it be made as a modal dialog?
---
Ans : ShowDialog it self make it as Modal Dialog.. ... | How do you display a custom UserControl as a dialog? | [
"",
"c#",
".net",
"wpf",
""
] |
I have a source file with a select form with some options, like this:
```
<option value="TTO">1031</option><option value="187">187</option><option value="TWO">2SK8</option><option value="411">411</option><option value="AEL">Abec 11</option><option value="ABE">Abec11</option><option value="ACE">Ace</option><option value="ADD">Addikt</option><option value="AFF">Affiliate</option><option value="ALI">Alien Workshop</option><option value="ALG">Alligator</option><option value="ALM">Almost</option>
```
I would like to read this file using php and regex, but I don't really know how. Anybody an idea? It would be nice to have an array with the 3 digits code as a key, and the longer string as a value. (so, for example, $arr['TWO'] == '2SK8') | ```
<?php
$options= '
<option value="TTO">1031</option><option value="187">187</option><option value="TWO">2SK8</option><option value="411">411</option><option value="AEL">Abec 11</option><option value="ABE">Abec11</option><option value="ACE">Ace</option><option value="ADD">Addikt</option><option value="AFF">Affiliate</option><option value="ALI">Alien Workshop</option><option value="ALG">Alligator</option><option value="ALM">Almost</option>
';
preg_match_all( '@(<option value="([^"]+)">([^<]+)<\/option>)@', $options, $arr);
$result = array();
foreach ($arr[0] as $i => $value)
{
$result[$arr[2][$i]] = $arr[3][$i];
}
print_r($result);
?>
```
output:
```
Array
(
[TTO] => 1031
[187] => 187
[TWO] => 2SK8
[411] => 411
[AEL] => Abec 11
[ABE] => Abec11
[ACE] => Ace
[ADD] => Addikt
[AFF] => Affiliate
[ALI] => Alien Workshop
[ALG] => Alligator
[ALM] => Almost
)
``` | What about something like this :
```
$html = <<<HTML
<option value="TTO">1031</option><option value="187">187</option>
<option value="TWO">2SK8</option><option value="411">411</option>
<option value="AEL">Abec 11</option><option value="ABE">Abec11</option>
<option value="ACE">Ace</option><option value="ADD">Addikt</option>
<option value="AFF">Affiliate</option><option value="ALI">Alien Workshop</option>
<option value="ALG">Alligator</option><option value="ALM">Almost</option>
HTML;
$matches = array();
if (preg_match_all('#<option\s+value="([^"]+)">([^<]+)</option>#', $html, $matches)) {
$list = array();
$num_matches = count($matches[0]);
for ($i=0 ; $i<$num_matches ; $i++) {
$list[$matches[1][$i]] = $matches[2][$i];
}
var_dump($list);
}
```
The output (`$list`) would be :
```
array
'TTO' => string '1031' (length=4)
187 => string '187' (length=3)
'TWO' => string '2SK8' (length=4)
411 => string '411' (length=3)
'AEL' => string 'Abec 11' (length=7)
'ABE' => string 'Abec11' (length=6)
'ACE' => string 'Ace' (length=3)
'ADD' => string 'Addikt' (length=6)
'AFF' => string 'Affiliate' (length=9)
'ALI' => string 'Alien Workshop' (length=14)
'ALG' => string 'Alligator' (length=9)
'ALM' => string 'Almost' (length=6)
```
A few explainations :
* I'm using [`preg_match_all`](http://php.net/preg_match_all) to match as many times as possible
* `([^"]+)` means "everything that is not a double-quote (as that one would mark the end of the `value`), at least one time, and as many times as possible (`+`)
* `([^<]+)` means about the same thing, but with `<` instead of `"` as end marker
* `preg_match_all` will get me an array containing in `$matches[1]` the list of all stuff that matched the first set of `()`, and in `$matches[2]` what matched the second set of `()`
+ so I need to iterate over the results to re-construct the list that inetrestes you :-)
Hope this helps -- and that you understood what it does and how, so you can help yourself, the next time **;-)**
As a sidenote : using regex to "parse" HTML is generally not such a good idea... If you have a full HTML page, you might want to take a look at [`DOMDocument::loadHTML`](http://php.net/manual/en/domdocument.loadhtml.php).
If you don't and the format of the options is not well-defined... Well, maybe it might prove useful to add some stuff to the regex, as a precaution... *(Like accepting spaces here and there, accepting other attributes, ...)* | php regex to read select form | [
"",
"php",
"regex",
"html-select",
""
] |
I'm using someone elses class and that person has defined a function with five arguments.
in Sentry.php:
```
function checkLogin($user = '',$pass = '',$group = 10,$goodRedirect = '',$badRedirect = '')
```
If all five fields are filled in this leads to a login procedure.
Now on the page where he explains how to use this there is a snippet which, according to php.net, doesn't make sense.
in a page that loads the sentry:
```
require_once('../system/Sentry.php');
$theSentry = new Sentry();
if(!$theSentry->checkLogin(2)){ header("Location: login.php"); die(); }
```
which by default should behave as such that it checks if the $group argument is <= 10 (default). In this situation it should be two. If the user checked has a group-variable of <=2 this should enable the person to view the page.
However, this doesn't work and for a very obvious reason: the php manual states:
> Note that when using default
> arguments, any defaults should be on
> the right side of any non-default
> arguments; otherwise, things will not
> work as expected.
So the code, according to phpbuilder.com should have no optional (`$variable = default_something`) field to fill in with a call to the function and it definitely shouldn't be defined as the third of five arguments.
How can I use the function like this?:
```
checkLogin(2)
``` | Default arguments are PHP's way of dealing with the lack of overloaded functions. In Java you can write this:
```
public void login(String username)
public void login(String username, String password)
```
In PHP you have to solve it like this:
```
function login($username, $password = '')
```
This way $username is mandatory and $password is optional. While this may be convenient, it isn't always. In your example there are a log of arguments and they are all optional. A clean solution for this would be to make 1 function that does the work and add 'convenience' methods to make the interface cleaner.
So add:
```
function checkLoginGroup($group = 10) {
$this->checkLogin('', '', $group);
}
```
It simply calls the function that already exists, but it allows for a cleaner interface, just call:
```
$theSentry->checkLoginGroup(2);
```
It's even neater to make the provided method private (or protected, depending on your needs) and create public 'convience' methods so you can hide the implementation details.
However, if you can not or don't want to change the original class, you might be able to create a subclass. | Changing the order of the arguments is a possibility... But what for the time you'll need another argument to be "*more optionnal*" or "*less optionnal*" ? Will you change that order again ?
And, with it, every call that's made to the function ?
To pass only the third argument, considering your function's declaration, the only method I see is to give the three first arguments... Passing the default value *(which you'll have to know, of course -- just look at it's declaration, for that)* for the first two :
```
checkLogin('', '', 20);
```
In my opinion, using this instead of that one :
```
checkLogin(null, null, 20);
```
Has the advantage of being explicit : someone looking at the function's declaration will immediatly notice you're using the default values for the first two parameters.
Using `NULL`, the personn reading your code would have to check inside the function's code to see if `NULL` is handled in a special way *(it could, afterall !)* ; it wouldn't be as easy for someone to understand that this is your way of passing default values... As they are not the default values ^^
Other solutions would imply refactoring the function,
* either to pass only one array as parameter *(with its keys not being required by the code)*
* ot using [Variable-length argument lists](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
Either way, you'd lose the ability your IDE has to show you the parameters the function is waiting for ; and that's bad :-(
And you'd also lose the phpdoc... | how to use a function with a non-optional argument defined as the third | [
"",
"php",
"variables",
"function",
"optional-arguments",
""
] |
Here is how it looks generally:
I get values from an outside device and I have to store a timestamp with them. Somehow I want to store the info in an efficient way to make my life easier when it comes to processing all the stuff.
As a simple solution I have created a class which stores one row:
```
public class X
{
public DateTime timestamp;
public double value1;
public double value2;
}
```
And then I create a List out of these objects.
Can you show a better way of dealing with this kind of data?
Thanks! | That seems perfectly reasonable to me, although I'd use properties rather than public fields. If you're fetching values from an external device, you may want to consider making the type immutable - pass all the values into the constructor and store them in readonly fields. I find it easier to reason about my code when the types are immutable :)
What sort of efficiency are you concerned about? How many of these values will you have? Even though there aren't many values here, I'd probably still use a class instead of a struct... I very rarely create my own structs. Again, I just find classes easier to reason about (no need to worry about boxing, for example.) Also, this feels like "a collection of values" rather than one indivisible value which is what structs are usually used for (numbers etc). It just doesn't *feel* like a struct to me.
You will incur an overhead per object, but I wouldn't worry about that unless you have a really good reason to.
EDIT: This seems a trivial point to make, but give everything meaningful names. For example:
```
public class DeviceReading
{
private readonly DateTime timeStamp;
public DateTime TimeStamp { get { return timeStamp; } }
private readonly double temperature;
public double Temperature { get { return temperature; } }
private readonly double airPressure;
public double AirPressure { get { return airPressure; } }
public DeviceReading (DateTime timeStamp,
double temperature,
double airPressure)
{
this.timeStamp = timeStamp;
this.temperature = temperature;
this.airPressure = airPressure;
}
}
```
I suspect you'd do so anyway, but I just thought I'd make sure :)
A couple of other things to consider:
* Assuming you're using a fairly recent version of .NET, you might want to use `DateTimeOffset` rather than `DateTime`. The benefit is that `DateTiemOffset` unambiguously represents an instant in time, whereas `DateTime` can be UTC, local or unspecified.
* Depending on the kind of readings you're taking (and how they're communicated) you may want to use `decimal` instead of `double`. Probably not for temperature and air pressure (or any other "physical" values) but if you're dealing with artificial values like money, `decimal` is your friend. Given that this is reading from a device, you're *probably* dealing with physical quantities, but I thought it worth mentioning.
* For dealing with the collections of readings, you *really* want to look into LINQ. It's lovely :) | This type is small enough that, assuming it is immutable, you may like to consider using a struct. This will reduce the load on the garbage collected heap.
What exactly are you trying to optimise? Memory footprint? Read performance? How will you be reading the data? | How to store tables in C# - What kind of data structure should I use? | [
"",
"c#",
"data-structures",
""
] |
is it possible to do this? (here is my code)
```
for ($i = 0 ; $i <= 10 ; $i++){
for ($j = 10 ; $j >= 0 ; $j--){
echo "Var " . $i . " is " . $k . "<br>";
}
}
```
I want something like this:
var 0 is 10
var 1 is 9
var 2 is 8 ...
But my code is wrong, it gives a huge list. Php guru, help me !! | Try this:
```
for ($i=0, $k=10; $i<=10 ; $i++, $k--) {
echo "Var " . $i . " is " . $k . "<br>";
}
```
The two variables `$i` and `$k` are initialized with `0` and `10` respectively. At the end of each each loop `$i` will be incremented by one (`$i++`) and `$k` decremented by one (`$k--`). So `$i` will have the values 0, 1, …, 10 and `$k` the values 10, 9, …, 0. | You could also add a condition for the second variable
```
for ($i=0, $k=10; $i<=10, $k>=0 ; $i++, $k--) {
echo "Var " . $i . " is " . $k . "<br>";
}
``` | Php for loop with 2 variables? | [
"",
"php",
"for-loop",
"infinite-loop",
""
] |
I am trying to write an aspx page where I am passing some server side value to the Javascript. The server side tag is changing from `<%` to `<%`
```
<asp:TextBox
ID="txtOriginalNo"
runat="server"
onkeyup="javascript:EnterKeyPress(<%=ibtnSubmit.ClientID%>,event);"
TabIndex="1"
MaxLength="13"
></asp:TextBox>
```
This is getting converted during runtime to:
```
<input
name="txtOriginalNo"
type="text"
maxlength="13"
id="txtOriginalNo"
tabindex="1"
onkeyup="javascript:EnterKeyPress(<%=ibtnSubmit.ClientID%>,event);"
/>
```
Can anyone tell me why this is? | You can't use a server tag inside a server control. Set the property from code behind:
```
txtOriginalNo.Attributes["onkeyup"] = "EnterKeyPress(" + ibtnSubmit.ClientID + ",event);"
```
Note: Don't use the `javascript:` protocol in event attributes. It's used when you put Javascript code in an URL, if you use it in an event attribute it becomes a label instead. | You can't use `<%= %>` there, inside an attribute of a server-side control. You need to assign the `asp:TextBox`'s `onkeyup` property differently, something like:
```
<% myTextBox.OnKeyUp = "javascript:EnterKeyPress(ibtnSubmit.ClientID)"; %>
``` | Why < is getting converted as < during runtime | [
"",
"asp.net",
"javascript",
""
] |
I have written a nice program in Java that connects to a gmail account and download atachments sent to it. Once an attachment has been downloaded, it is marked as read and is not downloaded ever again. This program will have to run in multiple instances with each program downloading unique attachments so that a single attachment is never downloaded twice. The problem is that at the moment if the attachment is of a decent size, one program is still downloading it, when another instance connects and also starts to download the attachment before it has been marked as read.
I have tried checking and setting various flags and checking whether the folder is open, nothing seems to work. Any solutions?
Update: Thank you for the quick answers, sadly IMAP is not an option due to other reasons. | As the others have mentioned, POP3 isn't really intended for this kind of scenario.
If you absolutely have to use POP3, I'd suggest downloading all the e-mail to an intermediate server which sorts the messages and makes them available for each of the other clients.
It sounds like you're just trying to distribute the processing of the e-mails. If that's the case, you can just have each client connect to your intermediate server to retrieve the next available message.
I'm not sure what your constraints are, but you may even want to consider receiving the attachments some other way besides e-mail. If people are uploading files, you could set up a web form that automatically sends each file to the next available instance of your application for processing. | Consider using IMAP instead - it is designed for client-server interaction. | Getting multiple Java pop3 clients to work with GMail | [
"",
"java",
"multithreading",
"gmail",
"jakarta-mail",
"pop3",
""
] |
How do I attach a body onload event with JS in a cross browser way? As simple as this?
```
document.body.onload = function(){
alert("LOADED!");
}
``` | This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...
[window.onload - Dean Edwards](http://dean.edwards.name/weblog/2005/09/busted/) - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.
```
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
``` | Why not use `window`'s own `onload` event ?
```
window.onload = function () {
alert("LOADED!");
}
```
If I'm not mistaken, that is compatible across all browsers. | Attach a body onload event with JS | [
"",
"javascript",
"html",
"events",
"onload",
""
] |
I have Memcache installed and working for PHP apps run through Apache (v2.2) but when I try to run a .php file in the command-line i get this error:
```
Fatal error: Class 'Memcache' not found in /usr/local/Matters/app/matters-common/connection.php on line 94
```
Line 94 is:
```
$memcache = new Memcache;
```
**Other info:**
CentOS 5.2
PHP 5.2.5 (cli) (built: Feb 20 2008 21:13:12)
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
Apache v2.2.8 | Presumably you have separate php.ini files set up for apache and the command line (cli).
If so, you need to add the following to your cli php.ini file:
```
extension=memcache.so
```
On Ubuntu it's in /etc/php5/cli/php.ini
If it's working then memcache should appear in the list of modules if you run `php -m` on the command line.
Alternatively, you can create a file `/etc/php5/cond.d/memcache.ini` with the same contents. | It is possible that you have a separate php.ini file for CLI mode. This file might not include memcache extension. | 'Memcache' not found in command line PHP script | [
"",
"php",
"apache",
"command-line",
"memcached",
""
] |
```
SELECT * FROM Questions
INNER JOIN QuestionKeyword INNER JOIN Keywords
ON Questions.ID=QuestionKeyword.QuestionID
AND QuestionKeyword.KeywordID=Keywords.ID
WHERE Keywords.Keyword LIKE '%es%'
```
It says:
Incorrect syntax near the keyword 'WHERE'. | You cannot combine the conditions from multiple JOINs but you have to list them separately with each join:
```
SELECT * FROM Questions
INNER JOIN QuestionKeyword ON Questions.ID=QuestionKeyword.QuestionID
INNER JOIN Keywords ON QuestionKeyword.KeywordID=Keywords.ID
WHERE Keywords.Keyword LIKE '%es%'
``` | You have two `JOIN`s but only one `ON`. You probably want
```
SELECT
*
FROM
Questions
INNER JOIN QuestionKeyword ON Questions.ID = QuestionKeyword.QuestionID
INNER JOIN Keywords ON QuestionKeyword.KeywordID = Keywords.ID
WHERE
Keywords.Keyword LIKE '%es%'
``` | What's wrong with this SQL statement? | [
"",
"sql",
""
] |
Taking a peek into the `information_schema` database and peeking at the *metadata* for one of my pet projects, I'm having a hard time understanding what (if any) differences there are between the `create schema` command and the `create database` command for MySQL.
Are there any differences? If not, is this a rather typical pattern of behavior for relational databases (I've heard that for other databases, such as Oracle, a schema exists in a database, rather than being on the same level as a database).
Thanks! | The [documentation of MySQL says](http://dev.mysql.com/doc/refman/5.0/en/create-database.html) :
> CREATE DATABASE creates a database
> with the given name. To use this
> statement, you need the CREATE
> privilege for the database. CREATE
> SCHEMA is a synonym for CREATE
> DATABASE as of MySQL 5.0.2.
So, it would seem normal that those two instruction do the same. | [Mysql documentation](http://dev.mysql.com/doc/refman/5.0/en/create-database.html) says : **CREATE SCHEMA is a synonym for CREATE DATABASE** as of MySQL 5.0.2.
---
this all goes back to an ANSI standard for SQL in the mid-80s.
That standard had a "CREATE SCHEMA" command, and it served to introduce
multiple name spaces for table and view names. All tables and views were
created within a "schema". I do not know whether that version defined
some cross-schema access to tables and views, but I assume it did.
AFAIR, no product (at least back then) really implemented it, that whole
concept was more theory than practice.
OTOH, ISTR this version of the standard did not have the concept of a
"user" or a "CREATE USER" command, so there were products that used the
concept of a "user" (who then had his own name space for tables and
views) to implement their equivalent of "schema".
This is an area where systems differ.
As far as administration is concerned, this should not matter too much,
because here you have differences anyway.
As far as you look at application code, you "only" have to care about
cases where one application accesses tables from multiple name spaces.
AFAIK, all systems support a syntax ".",
and for this it should not matter whether the name space is that of a
user, a "schema", or a "database". | MySQL 'create schema' and 'create database' - Is there any difference | [
"",
"sql",
"mysql",
"oracle",
"jdbc",
"database",
""
] |
I have a website. When the user clicks on a particular page (say identify.php) I want to find the type of browser the client is using. The browser might be mozilla, IE, opera, chrome or any other mobiles device such as SonyEricssonK610i, SAMSUNG-SGH-E370, SonyEricssonT700 or NokiaN73-1.
Is this possible to detect the user browser? | You need to look at:
```
$_SERVER['HTTP_USER_AGENT']
```
That will contain the User-Agent string for the browser. Beware that almost all browsers claim to be "Mozilla" for compatibility reasons - you need to look for specific text for each browser within that header, eg. "MSIE" for Internet Explorer.
**Some examples:**
My Firefox calls itself *Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 4.0.20506)*
My IE7 calls itself *Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; User-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; <http://bsalsa.com>) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 4.0.20506)*
Note all the trickery in the IE one, eg. claiming to be multiple versions. | Try the php function get\_browser();
<https://www.php.net/function.get-browser>
Or you can try out one of the many lighter weight scripts in the comments of that page. | Identifying the browser at server side in php | [
"",
"php",
"browser",
"mobile",
""
] |
I am looking for a way to monitor Windows dialog during a MSI deployment. Here is my situation: we have machines deploying daily MSIs and once in a while, one of them fail and shows a *Windows dialog* with an error message.
I am trying to find a way to write a script (maybe in Powershell) which will run every minutes and look for a Windows dialog with an OK button. Is there a simple way to do that?
Thanks! | You can depoly a MSI with options to not display a GUI at all.
Using MSIEXEC with the /quiet option.
Deploy via active directory to machines should not have this problem so I'd be interested in how you are deploying the MSI. | Rather than try to click the dialog, is there a way that you can determine the condition that will cause the error, and handle it?
Although you will find some methods for enumerating windows and posting click messages to them, there are some other things that you migth want to consider:
What if an unrelated dialog box appears that has an Ok button? It could cause problems for your users if an "Are you sure you want to delete the contents of c:\" gets auto-ok'ed.
Also, if your setup is running on Vista/Windows7/server2008 with UAC turned on, then your script will have to run with admin privileges, or any click messages will be rejected. | How to monitor Windows Dialog? | [
"",
"c#",
"windows",
"winapi",
"powershell",
"dialog",
""
] |
I have a table like this:
```
.--------------------------------.
| Name | XX | Date |
.--------------------------------.
| N1 | 5 | 2009-05-01 |
| N1 | 10 | 2008-01-08 |
| N2 | 8 | 2009-02-02 |
.________________________________.
```
My result should be this:
```
.------------.
| Name | XX |
.------------.
| N1 | 5 |
| N2 | 8 |
.____________.
```
I just want the rows, grouped by Name but just the newest ones. I dont want the row with XX=10 in this example because the date 2009-05-01 > 2008-01-08.
I don't know how to sort by Date and group it :( | What do you want the grouping for?
```
select Name, XX
from yourTable t1
where Date = (select MAX(Date)
from yourTable t2
where t1.Name = t2.Name)
```
If you need to sum XX for the last day, then:
```
select Name, SUM(XX)
from yourTable t1
where Date = (select MAX(Date)
from yourTable t2
where t1.Name = t2.Name)
group by Name
``` | ```
SELECT Name, XX FROM myTable GROUP BY Name ORDER BY Date DESC
```
You may need to put quotes around your date field
```
`Date`
``` | mysql query with group by and order by | [
"",
"sql",
"mysql",
"rows",
""
] |
I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()
```
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
```
If this output is what is expected, what is the logic behind it? | Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2). | To pass flags you can use re.compile
```
expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
``` | Can someone explain this Python re.sub() unexpected output? | [
"",
"python",
"regex",
""
] |
There is this [IMacro](https://addons.mozilla.org/en-US/firefox/addon/3863) scripting tool, if you want to automate some web
page visits by using javascript.
I would like to have my javascript to read from a local .txt file
(not a .cvs file and not well formatted.. I would like to search in it probably
with a regular expression..)
and based on that reading, the script will do some job in IMacros.. (e.g call some web site
url etc..)
Do you guys have any idea how this can be done ? I am doing everything
local and that is my local browser reading from my local hard drive.. it should
be somehow possible.. but how ? | Yes you can do it with imacros, but you need to call it from javascript.js file. load your content as one block, then you can use javascript indexOf method to find the string in the text and perform if statement.
Text example (inside your txt file):
"hello world!"
```
var load;
load = "CODE:";
load += "set !extract null" + "\n";
load += "SET !DATASOURCE text.txt" + "\n";
load += "SET !DATASOURCE_COLUMNS 1" + "\n";
load += "SET !DATASOURCE_LINE 1" + "\n";
load += "SET !extract {{!col1}}" + "\n";
iimPlay(load);
var s=iimGetLastExtract(0);
var index=s.indexOf("w");
if (index>0){
do your code;
}
``` | You have to use xml http request as Activex object of file is not supported by any other browser than IE.
This code works perfectly fine while reading local txt or any other file too.
```
f();
function f()
{
var allText =[];
var allTextLines = [];
var Lines = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "file://D:/test.csv", true);
allText = txtFile.responseText;
//allTextLines = allText.split(/\r\n|\n/);//splits ur file line by line.
//alert(allTextLines);
txtFile.onreadystatechange = function()
{
if (txtFile.readyState == 4)
{
// Makes sure it's found the file.
allText = txtFile.responseText;
allTextLines = allText.split(/\r\n|\n/);
alert(allText);
} else { //alert("Didn't work");
}
}
txtFile.send(null)
}
``` | IMacro Scripting - How to read a local .txt file using javascript | [
"",
"javascript",
"imacros",
""
] |
I need to find out the number `<input>` tag within a `<Div>` tag..
How it's possible.. For example the code will be like this..
```
<div><li ><a>Jayan</a><input type="checkbox" id="c21" onClick="fcheck(this);" ></li>
<li ><a href="#">Reshaba</a><input type="checkbox" id="c22" onClick="fcheck(this);" >
<ul>
<li ><a>crescent</a><input type="checkbox" id="c221" onClick="fcheck(this);" ></li>
<li ><a>crescent</a><input type="checkbox" id="c222" onClick="fcheck(this);" ></li>
<li ><a>crescent</a><input type="checkbox" id="c223" onClick="fcheck(this);" ></li>
<li ><a>crescent</a><input type="checkbox" id="c224" onClick="fcheck(this);" ></li>
</ul>
</li></div>
```
Please help
Thanks,
Praveen J | Why always the jquery solutions ?
There is nothing wrong with using jquery, but including a JS library to count some elements is serious overkill.
Native javascript:
```
var inputCount = document.getElementById('divId').getElementsByTagName('input').length;
``` | Very easy if you can use jQuery:
```
$('#divId input').length;
```
Otherwise @Jon Grant's answer is what you need | Find the number of <input> in an Div tag | [
"",
"javascript",
"html",
"xhtml",
""
] |
I want to read an XML file that has a schema declaration in it.
And that's all I want to do, read it. I don't care if it's valid, but I want it to be well formed.
The problem is that the reader is trying to read the schema file, and failing.
I don't want it to even try.
I've tried disabling validation, but it still insists on trying to read the schema file.
Ideally, I'd like to do this with a stock Java 5 JDK.
Here's what I have so far, very simple:
```
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
```
and here's the exception I am getting back:
```
java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
```
Yes, this HAPPENS to be an XHTML schema, but this isn't an "XHTML" issue, it's an XML issue. Just pointing that out so folks don't get distracted. And, in this case, the W3C is basically saying "don't ask for this thing, it's a silly idea", and I agree. But, again, it's a detail of the issue, not the root of it. I don't want to ask for it AT ALL. | The reference is not for **Schema**, but for a **DTD**.
DTD files can contain more than just structural rules. They can also contain entity references. XML parsers are obliged to load and parse DTD references, because they could contain entity references that might affect how the document is parsed and the content of the file(you could have an entity reference for characters or even whole phrases of text).
If you want to want to avoid loading and parsing the referenced DTD, [you can provide your own EntityResolver](https://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references) and test for the referenced DTD and decide whether load a local copy of the DTD file or just return null.
Code sample from the referenced answer on custom EntityResolvers:
```
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (systemId.contains("foo.dtd")) {
return new InputSource(new StringReader(""));
} else {
return null;
}
}
});
``` | The simplest answer is this one-liner, called after creating the DocumentBuilderFactory:
```
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
```
Shamelessly cribbed from [Make DocumentBuilder.parse ignore DTD references](https://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references). | How to read well formed XML in Java, but skip the schema? | [
"",
"java",
"xml",
""
] |
2 short questions. I would appreciate an answer or a pointer to an answered question on SO (I searched before asking :)).
1. I'd like to consume one of the [TRYNT](http://www.trynt.com/)'s web services that returns a JSON object (like [this one](http://www.trynt.com/symbol-lookup-api/v2/?s=IBM&fo=json&f=0) for example). Am I right in deducing that if they don't specify JSONP, there is no way I can consume those services from the client side, without a server-side proxy - due to cross-site scripting limitations?
2. Ok, so I tried implementing a PHP proxy to consume the service and return the JSON to HTML, but found out my (free) web hosting service blocks the CURL libarary. Being a newbie PHP developer (ASP.Net is my usual expertise, but I decided it's time to branch out :) ) - what other options do I have to get the JSON results from PHP?
Any assistance is appreciated. | Try this:
```
$url = 'http://www.trynt.com/symbol-lookup-api/v2/?s=IBM&fo=json&f=0';
$json = file_get_contents($url);
$data = json_decode($json);
```
Depends on your server configuration of course. Worth a shot! | 1. Please read [a related question](https://stackoverflow.com/questions/1197802/cross-site-ajax-using-jquery).
2. If CURL is blocked, probably other methods for getting remote content is also blocked. If `allow_url_fopen` is set to true on php.ini, you can use a function like [fopen](http://php.net/fopen). Also, you can try [opening a socket](http://php.net/fsockopen) to the server. | Consuming JSON with JavaScript and PHP | [
"",
"php",
"web-services",
"json",
"jsonp",
""
] |
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
So that given input `" \t example string\t "` becomes `"example string"`. | For whitespace on both sides, use [`str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip):
```
s = " \t a string example\t "
s = s.strip()
```
For whitespace on the right side, use [`str.rstrip`](https://docs.python.org/3/library/stdtypes.html#str.rstrip):
```
s = s.rstrip()
```
For whitespace on the left side, use [`str.lstrip`](https://docs.python.org/3/library/stdtypes.html#str.lstrip):
```
s = s.lstrip()
```
You can provide an argument to strip arbitrary characters to any of these functions, like this:
```
s = s.strip(' \t\n\r')
```
This will strip any space, `\t`, `\n`, or `\r` characters from both sides of the string.
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try [`re.sub`](https://docs.python.org/3/library/re.html#re.sub):
```
import re
print(re.sub('[\s+]', '', s))
```
That should print out:
```
astringexample
``` | In Python [**trim**](https://en.wikipedia.org/wiki/Trimming_(computer_programming)) methods are named `strip`:
```
str.strip() # trim
str.lstrip() # left trim
str.rstrip() # right trim
``` | How do I trim whitespace? | [
"",
"python",
"string",
"whitespace",
"trim",
"strip",
""
] |
I have this PHP code I am trying to integrate with the html layout below it however I can not figure it out, the php
code gets all status post and displays them in order but it then displays all comments that are associated with the status post so a status post could have
0 comments or it could have multiple comments.
If you read the notes I left in the PHP code and the notes I left in the html you will see the problem I am facing
I need to put the comments inside the table cell of the status post somehow
In the image below there is 1 status post and 3 comments for that post, what I am trying to do is get the comments to show up in there own table that will be nested in the right side right under the status post. So on the status post @ the top you see a table border at the bottom of that post, that border should be below the last comment for that post, hope that makes a little more sense now
[](https://i.stack.imgur.com/TS6zN.jpg)
```
<?PHP
$last_id = 0;
echo '<table width="400">';
while ($row = mysql_fetch_array($res)) {
//start output of new status post and comments
if ($row['0'] != $last_id) {
echo 'status post stuff'
}
//start output of new status post and comments
//output comment here
$last_id = $row['0'];
if($row['commentid'] != ''){
echo 'status COMMENT for above status post'
}
//END output comment here
}
echo '</table>';
?>
<table width="400">
<!-- begin status post -->
<tr>
<td width="99" valign="top" style="border-bottom: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;"> <div class="imageSub" style="width: 90px;"> <img class="female" src="http://cache2.mycrib.net/images/image_group66/0/43/t_6871399b0962b5fb4e29ce477541e165950078.jpg" alt="Something" width="90"/> </div></td>
<td width="489" style="border-bottom: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;">so and so said blah blah blah @ wee hours of the moring! <BR>
<!-- begin comment -->
<table width="90%" style="border: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;">
<tr>
<td width="14%" rowspan="2" valign="top"><img class="male" src="http://cache2.mycrib.net/images/image_group34/0/39/T_653807517aff2b1f5662d865b40d87d527c8eb.jpg" alt="Something" width="45"/></td>
<td width="86%">Date Posted</td>
</tr>
<tr>
<td>Comment text</td>
</tr>
</table>
<!-- end comment -->
</td>
</tr>
<!-- end status post -->
</table>
``` | You can close your php tag to drop into html again then reopen it inside your loop.
e.g.:
```
<table width="400">
<?PHP
$last_id = 0;
echo '<table width="400">';
while ($row = mysql_fetch_array($res)) {
//start output of new status post and comments
if ($row['0'] != $last_id) {
//echo 'status post stuff'
?>
<tr>
<td width="99" valign="top" style="border-bottom: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;"> <div class="imageSub" style="width: 90px;"> <img class="female" src="http://cache2.mycrib.net/images/image_group66/0/43/t_6871399b0962b5fb4e29ce477541e165950078.jpg" alt="Something" width="90"/> </div></td>
<td width="489" style="border-bottom: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;">so and so said blah blah blah @ wee hours of the moring! <BR>
<?php
}
//start output of new status post and comments
//output comment here
$last_id = $row['0'];
if($row['commentid'] != ''){
echo 'status COMMENT for above status post'
}
//END output comment here
?>
<!-- begin comment -->
<table width="90%" style="border: 1px solid rgb(204, 204, 204); margin: 0px; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;">
<tr>
<td width="14%" rowspan="2" valign="top"><img class="male" src="http://cache2.mycrib.net/images/image_group34/0/39/T_653807517aff2b1f5662d865b40d87d527c8eb.jpg" alt="Something" width="45"/></td>
<td width="86%">Date Posted</td>
</tr>
<tr>
<td>Comment text</td>
</tr>
</table>
<!-- end comment -->
<?php
}
echo '</table>';
?>
``` | I would try something like this, it allows you to separate the design from the logic which is fetching stuff from the database.
1.Build an array from your database which is something like below - this should be straightforward:
```
<?php
$posts = array(
array(
'title' => 'Hello',
'post' => 'This is the post',
'comments' => array(
array(
'date_posted' => '28/07/2009',
'text' => 'this is the first comment'
),
array(
'date_posted' => '28/07/2009',
'text' => 'this is the second comment'
)
)
),
array(
'title' => 'Another post',
'post' => 'Hello',
'comments' => array()
)
);
?>
```
2.Loop through array and output html (I have simplified but you should be able to adapt).
```
<?php foreach ($posts as $post): ?>
<!-- begin status post -->
<h1><?php echo $post['title']; ?></h1>
<p><?php echo $post['post']; ?></p>
<?php if ($post['comments']): ?>
<h2>Comments:</h2>
<ul>
<?php foreach ($post['comments'] as $comment): ?>
<!-- begin comment -->
<li>
<?php echo $comment['text']; ?>
etc.
</li>
<!-- end comment -->
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- end status post -->
<?php endforeach; ?>
``` | How can I integrate this html within this php loop? | [
"",
"php",
""
] |
I am learning SQL and am trying to learn JOINs this week.
I have gotten to the level where I can do three table joins, similar to a lot of examples I've seen. I'm still trying to figure out the tiny details of how things work. All the examples I've seen of three table joins use INNER JOINS only. What about LEFT and RIGHT JOINs? Do you ever use these in three table joins? What would it mean?
```
SELECT ~some columns~ FROM ~table name~
LEFT JOIN ~table 2~ ON ~criteria~
INNER JOIN ~table 3~ ON ~criteria~
```
or
```
SELECT ~some columns~ FROM ~table name~
INNER JOIN ~table 2~ ON ~criteria~
LEFT JOIN ~table 3~ ON ~criteria~
```
or
```
SELECT ~some columns~ FROM ~table name~
LEFT JOIN ~table 2~ ON ~criteria~
LEFT JOIN ~table 3~ ON ~criteria~
```
or
???
Just trying to explore the space as much as possible | Yes, I do use all three of those JOINs, although I tend to stick to using just `LEFT (OUTER) JOIN`s instead of inter-mixing LEFT and RIGHT JOINs. I also use `FULL OUTER JOIN`s and `CROSS JOIN`s.
In summary, an `INNER JOIN` restricts the resultset only to those records satisfied by the JOIN condition. Consider the following tables
**EDIT:** I've renamed the Table names and prefix them with `@` so that Table Variables can be used for anyone reading this answer and wanting to experiment.
If you'd also like to experiment with this in the browser, **[I've set this all up on SQL Fiddle](http://www.sqlfiddle.com/#!3/167be/1/0)** too;
```
@Table1
id | name
---------
1 | One
2 | Two
3 | Three
4 | Four
@Table2
id | name
---------
1 | Partridge
2 | Turtle Doves
3 | French Hens
5 | Gold Rings
```
SQL code
```
DECLARE @Table1 TABLE (id INT PRIMARY KEY CLUSTERED, [name] VARCHAR(25))
INSERT INTO @Table1 VALUES(1, 'One');
INSERT INTO @Table1 VALUES(2, 'Two');
INSERT INTO @Table1 VALUES(3, 'Three');
INSERT INTO @Table1 VALUES(4, 'Four');
DECLARE @Table2 TABLE (id INT PRIMARY KEY CLUSTERED, [name] VARCHAR(25))
INSERT INTO @Table2 VALUES(1, 'Partridge');
INSERT INTO @Table2 VALUES(2, 'Turtle Doves');
INSERT INTO @Table2 VALUES(3, 'French Hens');
INSERT INTO @Table2 VALUES(5, 'Gold Rings');
```
An `INNER JOIN` SQL Statement, joined on the `id` field
```
SELECT
t1.id,
t1.name,
t2.name
FROM
@Table1 t1
INNER JOIN
@Table2 t2
ON
t1.id = t2.id
```
Results in
```
id | name | name
----------------
1 | One | Partridge
2 | Two | Turtle Doves
3 | Three| French Hens
```
A `LEFT JOIN` will return a resultset with all records from the table on the left hand side of the join (if you were to write out the statement as a one liner, the table that appears first) and fields from the table on the right side of the join that match the join expression and are included in the `SELECT` clause. *Missing* details will be populated with NULL
```
SELECT
t1.id,
t1.name,
t2.name
FROM
@Table1 t1
LEFT JOIN
@Table2 t2
ON
t1.id = t2.id
```
Results in
```
id | name | name
----------------
1 | One | Partridge
2 | Two | Turtle Doves
3 | Three| French Hens
4 | Four | NULL
```
A `RIGHT JOIN` is the same logic as a `LEFT JOIN` but will return all records from the right-hand side of the join and fields from the left side that match the join expression and are included in the `SELECT` clause.
```
SELECT
t1.id,
t1.name,
t2.name
FROM
@Table1 t1
RIGHT JOIN
@Table2 t2
ON
t1.id = t2.id
```
Results in
```
id | name | name
----------------
1 | One | Partridge
2 | Two | Turtle Doves
3 | Three| French Hens
NULL| NULL| Gold Rings
```
Of course, there is also the `FULL OUTER JOIN`, which includes records from both joined tables and populates any *missing* details with NULL.
```
SELECT
t1.id,
t1.name,
t2.name
FROM
@Table1 t1
FULL OUTER JOIN
@Table2 t2
ON
t1.id = t2.id
```
Results in
```
id | name | name
----------------
1 | One | Partridge
2 | Two | Turtle Doves
3 | Three| French Hens
4 | Four | NULL
NULL| NULL| Gold Rings
```
And a `CROSS JOIN` (also known as a `CARTESIAN PRODUCT`), which is simply the product of cross applying fields in the `SELECT` statement from one table with the fields in the `SELECT` statement from the other table. Notice that there is no join expression in a `CROSS JOIN`
```
SELECT
t1.id,
t1.name,
t2.name
FROM
@Table1 t1
CROSS JOIN
@Table2 t2
```
Results in
```
id | name | name
------------------
1 | One | Partridge
2 | Two | Partridge
3 | Three | Partridge
4 | Four | Partridge
1 | One | Turtle Doves
2 | Two | Turtle Doves
3 | Three | Turtle Doves
4 | Four | Turtle Doves
1 | One | French Hens
2 | Two | French Hens
3 | Three | French Hens
4 | Four | French Hens
1 | One | Gold Rings
2 | Two | Gold Rings
3 | Three | Gold Rings
4 | Four | Gold Rings
```
**EDIT:**
Imagine there is now a Table3
```
@Table3
id | name
---------
2 | Prime 1
3 | Prime 2
5 | Prime 3
```
The SQL code
```
DECLARE @Table3 TABLE (id INT PRIMARY KEY CLUSTERED, [name] VARCHAR(25))
INSERT INTO @Table3 VALUES(2, 'Prime 1');
INSERT INTO @Table3 VALUES(3, 'Prime 2');
INSERT INTO @Table3 VALUES(5, 'Prime 3');
```
Now all three tables joined with `INNER JOINS`
```
SELECT
t1.id,
t1.name,
t2.name,
t3.name
FROM
@Table1 t1
INNER JOIN
@Table2 t2
ON
t1.id = t2.id
INNER JOIN
@Table3 t3
ON
t1.id = t3.id
```
Results in
```
id | name | name | name
-------------------------------
2 | Two | Turtle Doves | Prime 1
3 | Three| French Hens | Prime 2
```
It might help to understand this result by thinking that records with id 2 and 3 are the only ones common to all 3 tables *and* are also the field we are joining each table on.
Now all three with `LEFT JOINS`
```
SELECT
t1.id,
t1.name,
t2.name,
t3.name
FROM
@Table1 t1
LEFT JOIN
@Table2 t2
ON
t1.id = t2.id
LEFT JOIN
@Table3 t3
ON
t1.id = t3.id
```
Results in
```
id | name | name | name
-------------------------------
1 | One | Partridge | NULL
2 | Two | Turtle Doves | Prime 1
3 | Three| French Hens | Prime 2
4 | Four | NULL | NULL
```
[Joel's answer](https://stackoverflow.com/questions/1262148/three-table-join-with-joins-other-than-inner-join/1262196#1262196) is a good explanation for explaining this resultset (Table1 is the base/origin table).
Now with a `INNER JOIN` and a `LEFT JOIN`
```
SELECT
t1.id,
t1.name,
t2.name,
t3.name
FROM
@Table1 t1
INNER JOIN
@Table2 t2
ON
t1.id = t2.id
LEFT JOIN
@Table3 t3
ON
t1.id = t3.id
```
Results in
```
id | name | name | name
-------------------------------
1 | One | Partridge | NULL
2 | Two | Turtle Doves | Prime 1
3 | Three| French Hens | Prime 2
```
Although we do not know the order in which the query optimiser will perform the operations, we will look at this query from top to bottom to understand the resultset. The `INNER JOIN` on ids between Table1 and Table2 will restrict the resultset to only those records satisfied by the join condition i.e. the three rows that we saw in the very first example. This *temporary* resultset will then be `LEFT JOIN`ed to Table3 on ids between Table1 and Tables; There are records in Table3 with id 2 and 3, but not id 1, so t3.name field will have details in for 2 and 3 but not 1. | Joins are just ways of combining tables. Joining three tables is no different than joining 2... or 200. You can mix and match INNER, [LEFT/RIGHT/FULL] OUTER, and even CROSS joins as much as you want. The only difference is which results are kept: INNER joins only keep rows where both sides match the expression. OUTER joins pick an "origin" table depending on the LEFT/RIGHT/FULL specification, always keep all rows from the origin table, and supply NULL values for rows from the other side that don't match the expression. CROSS joins return all possible combinations of both sides.
The trick is that because you're working with declarative code rather than more-familiar iterative, the temptation is to try to think of it as if everything happens at once. When you do that, you try to wrap your head around the entire query and it can get confusing.
Instead, you want to think of it as if the joins happen in order, from the first table listed to the last. This actually is not how it works, because the query optimizer can re-order things to make them run faster. But it makes building the query easier for the developer.
So with three tables, you start with your base table, then join in the values you need from the next table, and the next, and so on, just like adding lines of code to a function to produce the required output.
As for using the different join types, I've used all the different types I listed here: INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER, and CROSS. But most of those you only need to use occasionally. INNER JOIN and LEFT JOIN will cover probably 95% or more of what you want to do.
Now let's talk about performance. Often times the order you list tables is dictated to you: you start from `TableA` and you need to list `TableB` first in order to have access to columns required to join in `TableC`. But sometimes both `TableB` and `TableC` only depend on `TableA`, and you could list them in either order. When that happens the query optimizer will usually pick the best order for you, but sometimes it doesn't know how. Even if it did, it helps to have a good system for listing tables so you can always look at a query and know that it's "right".
With that in mind, you should think of a query in terms of the `working set` currently in memory as the query builds. When you start with `TableA`, the database looks at all the columns from `TableA` in the select list or anywhere else (like WHERE or ORDER BY clauses, or potential indexes) in the query, factors in relevant conditions from the WHERE clause, and loads the smallest portion of that table into memory that it can get away with. It does this for each table in turn, always loading as little as possible. And that's the key: you want to keep this working set as small as possible for as long as possible.
So, going back to our three-table join, we want to list the tables in the order that will keep the working set smaller for longer. This means listing the smaller table above the larger one. Another good rule of thumb is that INNER joins tend to *shrink* result sets, while OUTER joins, tend to *grow* result sets, and so you want to list your INNER joins first. However, this is not a *requirement* for a query to work, nor is it always true; sometimes the reverse can happen as well.
Finally, I want to point out again that this isn't how it really works. The query optimizer and execution plans are a very complex topic, and there are lots of tricks the database can take that break this model from time to time. It's just one model that you as a developer can use to help understand what the server is doing and help you write better queries. | Three table join with joins other than INNER JOIN | [
"",
"sql",
"sql-server",
"database",
"sql-server-2005",
"t-sql",
""
] |
I have two sql server tables with the same structure. In a stored procedure I have a Select from the first table. Occasionally I want to select from the second table as well based on a passed in parameter.
I would like a way to do this without resorting to using dynamic sql or temporary tables. | Pass in param = 1 to union, anything else to only return the first result set:
```
select field1, field2, ... from table1 where cond
union
select field1, field2, ... from table2 where cond AND param = 1
``` | If they are both the exact same structure, then why not have a single table with a parameter that differentiates the two tables? At that point, it becomes a simple matter of a case statement on the parameter on which results set you receive back.
A second alternative is dual result sets. You can select multiple result sets out of a stored procedure. Then in code, you would either use DataReader.NextResult or DataSet.Tables(1) to get at the second set of data. It will then be your code's responsibility to place them into the same collection or merge the two tables.
A THIRD possibility is to utilize an IF Statement. Say, pass in an integer with the expected possible values of 1,2, 3 and then have something along this in your actual stored procedure code
```
if @Param = 1 Then
Select From Table1
if @Param = 2 THEN
Select From Table2
if @Param = 3 Then
Select From Table1 Union Select From Table 2
```
A fourth possibility would be to have two distinct procedures one which runs a union and one which doesn't and then make it your code's responsibility to determine which one to call based on that parameter, something like:
```
myCommandObject.CommandText = IIf(myParamVariable = true, "StoredProc1", StoredProc2")
``` | Optionally use a UNION from another table in T-SQL without using temporary tables or dynamic sql? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Usually throughout development of a project I will deploy frequently, just to make sure I wont have any problems in production.
Also, throughout development, I find myself changing the database's schema.
How can I easily update the database in production?
I have been dropping the old database and reattaching the new one. Is there a faster way to update the deployment database?
Thanks
### EDIT
What are some free tools for this? | The Generate Scripts wizard did exactly what I needed. | Maintain a list of all the change scripts that you apply to your dev database and apply them to the Production database when deploying.
Alternatively, use a third party tool that can compare the two schemas and provide a changescript which you can then run. | How can I update my SQL Server database schema? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"schema",
""
] |
Any difference between the two, int terms of speed/performance?
```
$sql = "SELECT * "
. "FROM `myTable` "
. "WHERE `id` = 4";
$sql = "SELECT *
FROM `myTable`
WHERE `id` = 4";
``` | Maybe a very very **very small** difference, the first one probably being a bit slower *(because of concatenations)*...
... But the time taken to execute your single simple SQL query will be thousands *(maybe hundreds, with a simple query -- just a wild guess, but you'll see the point)* of times more important than that very small difference !
So, you really shouldn't bother about that kind of "optimizations", and consider/choose what is the most easy to both write/read/understand and maintain.
---
**EDIT :** just for fun, here are the opcodes that are generated for the first portion of code :
```
$ php -dextension=vld.so -dvld.active=1 temp-2.php
Branch analysis from position: 0
Return found
filename: /home/squale/developpement/tests/temp/temp-2.php
function name: (null)
number of ops: 6
compiled vars: !0 = $sql
line # op fetch ext return operands
-------------------------------------------------------------------------------
5 0 EXT_STMT
1 CONCAT ~0 'SELECT+%2A+', 'FROM+%60myTable%60+'
2 CONCAT ~1 ~0, 'WHERE+%60id%60+%3D+4'
3 ASSIGN !0, ~1
8 4 RETURN 1
5* ZEND_HANDLE_EXCEPTION
```
And, for the second one :
```
$ php -dextension=vld.so -dvld.active=1 temp-2.php
Branch analysis from position: 0
Return found
filename: /home/squale/developpement/tests/temp/temp-2.php
function name: (null)
number of ops: 4
compiled vars: !0 = $sql
line # op fetch ext return operands
-------------------------------------------------------------------------------
7 0 EXT_STMT
1 ASSIGN !0, 'SELECT+%2A%0A++++++++FROM+%60myTable%60%0A++++++++WHERE+%60id%60+%3D+4'
9 2 RETURN 1
3* ZEND_HANDLE_EXCEPTION
```
So, yes, there is a difference... But, still, what I said before is still true : you shouldn't care about that kind of optimization : you'll do so many "not-optimized" stuff in the other parts of your application *(or even if the configuration of your server)* that a small difference like this one means absolutly nothing
*Well, except if you are google and have thousands of servers, I guess ^^* | To test this kind of stuff, you use a big while loop and run the code over-and-over to compare. Do this twice (or more) to compare operations. Run it a few dozen times and track the results.
```
ob_start();
$t = microtime(true);
while($i < 1000) {
// CODE YOU WANT TO TEST
++$i;
}
$tmp = microtime(true) - $t;
ob_end_clean();
echo $tmp
``` | PHP multiline, concatenated strings | [
"",
"php",
"string",
""
] |
is there an easy possibility to highlight a portion of text in a normal WinForms TextBox (I cannot use RichTextBox in this case). All the solutions I came up with so far are very complex and handle drawing the text on their own, including fancy Interop calls...
Thanks in advance!
**EDIT:**
I don't talk about selecting the text but highlighting parts of it with a background color or a colored underline. Thanks again | I finally ended up implementing the behavior on my own.
<http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/> was really helpful. | If you mean to change the color or font style of part of the text in a regular `TextBox` control, there is no support for that. What you *can* do is to select a portion of the text to make it stand out, but that is obviously a very temporary solution (note that the `HideSelection` property must be set to `false` for this to show when the `TextBox` does not have focus):
```
// select the 8 characters, starting after the fifth character
myTextBox.Select(5, 8);
``` | Highlight character range in .NET TextBox | [
"",
"c#",
".net",
"winforms",
""
] |
I need to access simultaniously multiple instances of a web services with the following Url. The web services is hosted in IIS and has SSL enabled.
<https://services.mysite.com/data/data.asmx>
Usually, when we do this process manually, we go one by one and update the Windows host file (c:\Windows\System32\drivers\etc\hosts) like this :
192.1.1.100 services.mysite.com
I would like to automate the process and do it with some multithreading. So I cannot change the Host file. Is there a way to simulate a host file when we do a HTTP request in C#?
Thanks! | If you know the IP address of the server's SSL endpoint (which isn't necessarily the same as the server's default IP address), then you could just aim you web-service at that? Obviously the SSL check will fail, but you can disable that through code...
```
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true; // you might want to check some of the certificate detials...
};
``` | I think you get the same effect by setting the proxy server of that specific request to the IP address of the actual Web server you want to send the request to. | How to simulate a Host file for the time of one request | [
"",
"c#",
"http",
"ssl",
""
] |
What does the `Inherited` bool property on attributes refers to?
Does it mean that if I define my class with an attribute `AbcAtribute` (that has `Inherited = true`), and if I inherit another class from that class, that the derived class will also have that same attribute applied to it?
To clarify this question with a code example, imagine the following:
```
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class Random: Attribute
{ /* attribute logic here */ }
[Random]
class Mother
{ }
class Child : Mother
{ }
```
Does `Child` also have the `Random` attribute applied to it? | When Inherited = true (which is the default) it means that the attribute you are creating can be inherited by sub-classes of the class decorated by the attribute.
So - if you create MyUberAttribute with [AttributeUsage (Inherited = true)]
```
[AttributeUsage (Inherited = True)]
MyUberAttribute : Attribute
{
string _SpecialName;
public string SpecialName
{
get { return _SpecialName; }
set { _SpecialName = value; }
}
}
```
Then use the Attribute by decorating a super-class...
```
[MyUberAttribute(SpecialName = "Bob")]
class MySuperClass
{
public void DoInterestingStuf () { ... }
}
```
If we create an sub-class of MySuperClass it will have this attribute...
```
class MySubClass : MySuperClass
{
...
}
```
Then instantiate an instance of MySubClass...
```
MySubClass MySubClassInstance = new MySubClass();
```
Then test to see if it has the attribute...
MySubClassInstance <--- now has the MyUberAttribute with "Bob" as the SpecialName value. | Yes that is precisely what it means. [Attribute](http://msdn.microsoft.com/en-us/library/z0w1kczw(VS.80).aspx)
```
[AttributeUsage(Inherited=true)]
public class FooAttribute : System.Attribute
{
private string name;
public FooAttribute(string name)
{
this.name = name;
}
public override string ToString() { return this.name; }
}
[Foo("hello")]
public class BaseClass {}
public class SubClass : BaseClass {}
// outputs "hello"
Console.WriteLine(typeof(SubClass).GetCustomAttributes(true).First());
``` | How does inheritance work for Attributes? | [
"",
"c#",
".net",
"vb.net",
"attributes",
""
] |
I'm working with a webservice which requires a valid username/password. From PyQt, I'm accessing the webservice using QNetworkAccessManager which emits the
```
authenticationRequired (QNetworkReply*, QAuthenticator*)
```
signal when (obviously), authentication is required. When I fill in the user and psswd for
QAuthenticator, everything works fine. However, I can't see how to break the loop when the user is *not* valid.
From the docs for authenticationRequired:
"If it rejects the credentials, this signal will be emitted again."
For invalid credentials this signal is emitted again, and again, and
again... Looking at the error code in the reply showed 0. How is this loop supposed to be broken or handled so that it terminates with an error? | Yeh, it's odd. What I've done previously is check if I've already authenticated with those details and if I have then call `QNetworkReply.abort()` | What about trying:
```
QNetworkReply::abort()
```
or
```
QNetworkReply::close()
```
? | Qt HTTP authentication with QNetworkAccessManager | [
"",
"python",
"qt",
"networking",
"qt4",
"pyqt",
""
] |
In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected ([PEP 212](http://www.python.org/dev/peps/pep-0212/) and [PEP 281](http://www.python.org/dev/peps/pep-0281/)).
This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.
Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.
```
# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
```
When run, it outputs:
```
[ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
``` | **Use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate) like so:**
```
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
```
**Note**: You can optionally put parenthesis around `counter, option`, like `(counter, option)`, if you want, but they're extraneous and not normally included. | I'll sometimes do this:
```
def draw_menu(options, selected_index):
for i in range(len(options)):
if i == selected_index:
print " [*] %s" % options[i]
else:
print " [ ] %s" % options[i]
```
Though I tend to avoid this if it means I'll be saying `options[i]` more than a couple of times. | Python loop counter in a for loop | [
"",
"loops",
"for-loop",
"python",
""
] |
<http://www.s3fm.com/> is really useful for uploading/viewing files for personal viewing.
I was wondering if there was something good for social networks (using Amazon s3 or something similar),
where it will only show the subset of files uploaded by a specific user (for example, limit access to the user's specific bucket).
Can s3fm be adapted to this solution? or is there something else out there? | Chris, thanks for bringing this up.
Next version of S3fm will allow just that: sharing files and "folders" with your friends and colleagues using your own S3 account. A bucket owner will be able to use his or her credentials to create new (non-AWS) "accounts" and assign different permissions for each user. Then s/he will be able to select files to share or "folders" for uploads for each of those users.
A secure authentication method has been developed on top of regular Amazon S3 API so no 3rd party service will be required for that purpose. In fact, your newly created account credentials are not even accessible to anyone but you and you users . On the flip side, if you loose them - they are gone, we wont be able to restore them. :)
This version was expected this coming Fri (Aug 9, 2009), but apparently will be delayed another week or so.
Happy to help, feel free to follow up with questions or ideas, | I believe you would need to build your own system to do this. What you use doesn't really matter, you could use S3, Azure, etc as your base storage "cloud." | Amazon S3 for Social Networks? | [
"",
"javascript",
"amazon-s3",
""
] |
I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML.
Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.
Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff. | ASCII is the American Standard Code for Information Interchange and does **not** include any accented letters. Your best bet is to get Unicode (as you say you can) and encode it as UTF-8 (maybe ISO-8859-1 or some weird codepage if you're dealing with seriously badly coded user-agents/clients, sigh) -- the content type header of that part together with text/plain can express what encoding you've chosen to use (I do recommend trying UTF-8 unless you have positively demonstrated it cannot work -- it's *almost* universally supported these days and MUCH more flexible than any ISO-8859 or "codepage" hack!). | Here is a complete implementation that also handles unicode html entities. You might find it useful.
It returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.
```
def convert_html_entities(s):
matches = re.findall("&#\d+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
name = hit[2:-1]
try:
entnum = int(name)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
hex = hit[3:-1]
try:
entnum = int(hex, 16)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&\w+;", s)
hits = set(matches)
amp = "&"
if amp in hits:
hits.remove(amp)
for hit in hits:
name = hit[1:-1]
if htmlentitydefs.name2codepoint.has_key(name):
s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
s = s.replace(amp, "&")
return s
```
Edit: added matching for hexcodes. I've been using this for a while now, and ran into my first situation with ' which is a single quote/apostrophe. | Convert html entities to ascii in Python | [
"",
"python",
"ascii",
""
] |
let say in tomcat application server we deployed 2 web applications , web application A, web application B. How to pro-grammatically sync session from web application A to web application B . In other words, as long as user login to web application A, he is already login to web application B. As well when he log out. | You may check [Sharing session data between contexts HOW-TO](http://www.fwd.at/tomcat/sharing-session-data-howto.html) to see if it solves your problem. | Use the [single sign on valve](http://tomcat.apache.org/tomcat-6.0-doc/config/host.html#Single%20Sign%20On). | passing session to another web application | [
"",
"java",
"web-applications",
"tomcat",
""
] |
I am searching for a good way to get relative paths of files and (sub)folders within a specific folder.
For my current approach I am using `os.walk()`. It is working but it does not seem "pythonic" to me:
```
myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
```
Any other suggestions?
Thanks | Use [`os.path.relpath()`](https://docs.python.org/3.8/library/os.path.html#os.path.relpath). This is exactly its intended use.
```
import os
root_dir = "myfolder"
file_set = set()
for dir_, _, files in os.walk(root_dir):
for file_name in files:
rel_dir = os.path.relpath(dir_, root_dir)
rel_file = os.path.join(rel_dir, file_name)
file_set.add(rel_file)
```
Note that `os.path.relpath()` was added in Python 2.6 and is supported on Windows and Unix. | ```
myFolder = "myfolder"
fileSet = set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add( os.path.join( root[len(myFolder):], fileName ))
``` | Python - Get relative path of all files and subfolders in a directory | [
"",
"python",
""
] |
Python rather stupidly has a pragma directive in its include files that forces a link against `python26_d.lib` when the `DEBUG` preprocessor variable is defined. This is a problem because the python installer doesn't come with `python26_d.lib`! So I can't build applications in MSVC in debug mode. If I temporarily `#undef DEBUG` for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions.
I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python
Can anyone give me any advice on how to get round this? | From [python list](http://mail.python.org/pipermail/python-list/2009-March/1198717.html)
> As a workaround to the situation, try
> to copy the file python26.dll to
> python26\_d.dll. (I'm not sure this
> will work; you say you are building a
> SWIG library in debug mode, and it's
> possible that SWIG will try to use
> features of the Python debugging
> version. If that's the case, you'll
> have no choice but to use the
> debugging version of Python.)
Edit: From comments:
> You should also edit pyconfig.h and
> comment out the line "#define
> Py\_DEBUG" (line 374) | After you comment out "#define Py\_DEBUG" on line 332 and modify
```
# ifdef _DEBUG
# pragma comment(lib,"python26_d.lib")
# else
```
to
```
# ifdef _DEBUG
# pragma comment(lib,"python26.lib")
# else
```
you do not need to python26\_d.lib anymore. | Compiling python modules with DEBUG defined on MSVC | [
"",
"python",
"debugging",
"visual-c++",
""
] |
Is it possible to determine whether an element has a click handler, or a change handler, or any kind of event handler bound to it using jQuery?
Furthermore, is it possible to determine how many click handlers (or whatever kind of event handlers) it has for a given type of event, and what functions are in the event handlers? | You can get this information from the data cache.
For example, log them to the console (firebug, ie8):
```
console.dir( $('#someElementId').data('events') );
```
or iterate them:
```
jQuery.each($('#someElementId').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log( handler.toString() );
});
});
```
Another way is you can use the following [bookmarklet](http://www.sprymedia.co.uk/article/Visual+Event) but obviously this does not help at runtime. | Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.
I therefore use die() or unbind() like this:
```
$("#someid").die("click").live("click",function(){...
```
or
```
$("#someid").unbind("click").bind("click",function(){...
```
or in recent jQuery versions:
```
$("#someid").off("click").on("click",function(){...
``` | test if event handler is bound to an element in jQuery | [
"",
"javascript",
"jquery",
""
] |
I have the following HTML code:
```
<tr id="1774" class="XXX"><td> <span class="YYY">
Element 1</span></td></tr>
<tr id="1778" class="XYZ"><td> <span class="ZZZ">Element 2
</span></td>
</tr>
```
I want to replace all the class attributes (just for <**tr**> s) but not for <**td**> s.
(***that would be XXX and XYZ***). The replacement would be: ***XXX\_suffix, XYZ\_sufix***
Here is my workaround, but it replaces all the class attributes (in elements too!).
```
var htmlBlock= "<tr id="1774" class="XXX"><td> <span class="YYY">...</span></td></tr>";
htmlBlock+="<tr id="1778" class="XYZ"><td> <span class="ZZZ">...</span></td></tr>";
htmlBlock= htmlBlock.replace(/class="\s*(\w*)/g, "class=\" $1 " + _suffix);
```
But how can I replace *just the tr class attribute* ??
Is there another way in jQuery ?? | I'm weary of what you're trying to do, but this works.
```
var s = '<tr id="1774" class="XXX"><td> <span class="YYY">Element 1</span></td></tr><tr id="1778" class="XYZ"><td> <span class="ZZZ">Element 2</span></td></tr>';
s.replace(/(<tr\s+.*?class=").*?(".*)/gi, "$1NEWCLASS$2");
```
Your string then becomes
```
<tr id="1774" class="NEWCLASS"><td> <span class="YYY">Element 1</span></td></tr><tr id="1778" class="XYZ"><td> <span class="ZZZ">Element 2</span></td></tr>
```
This is all assuming that you want/have to handle it as a string (again, still weary). | Yes there is an easy way:
```
$("tr").removeClass("XYZ").addClass("XXX");
```
If you want to change the existing class you can do something like:
```
var trClass = $("tr#1234").attr("class");
/* do some string operation on tr class string */
$("tr").attr("class", "").addClass(trClass);
```
Also, please note that element ids shouldn't start with a numeral but with a letter.
**EDIT** a bit more on the .attr() method. .attr("name") returns the value of that attribute, whereas .attr("name", "value") sets the attribute to the value. For dealing with classes jQuery has some helper methods: addClass("class"), removeClass("class") and hasClass("class"). these are fairly self explanatory
**EDIT 2** If you create a jquery object from your dynamic html like this:
```
var htmlBlock= "<tr id=\"1774\" class=\"XXX\"><td> <span class=\"YYY\">...</span></td></tr>";
var htmlBlockJ = $(htmlBlock);
```
then you can use the method i suggested | Javascript Regex: how to replace just the class of attribute for any tr? | [
"",
"javascript",
"regex",
""
] |
I have several components for which there exists different versions, depending on the language used by the system (configurable, and can be changed at runtime). For example, I have an interface ("component") for `Tokenizer`, and two concrete implementations for english and chinese, like so:
```
public interface Tokenizer {
List<String> tokenize(String s);
}
public class EnglishTokenizer implements Tokenizer {
List<String> tokenize(String s) { ... };
}
public interface ChineseTokenizer implements Tokenizer {
List<String> tokenize(String s) { ... };
}
```
Now, in many classes of my code, I need to get a language specific implementation of some of those components (`Tokenizer`, `Parser`, and many others), and I was wondering what's the most elegant way to achieve this? I thought of using one of the following approaches:
* Each component (such as `Tokenizer`), would have a factory (singleton) that, given a language `enum`, would return the appropriate language specific implementation, like so (this would require **many** factories):
> ```
> public enum TokenizerFactory {
> SINGLETON;
> private Map<Language, Tokenizer> cache;
> public getTokenizer(Language) {
> return cache.get(Language);
> }
> }
> ```
* Have a (quite large) `Language` class, that would be instantiated with a specific language `enum`, and would have many different methods to get the language specific components. Then, at runtime, I could easily switch between languages (which is one of my goals). Like so:
> ```
> public class Language {
> public Language(LanguageEnum) {/* load language specific components*/};
> public Tokenizer getTokenizer() {/* language specific tokenizer */};
> public Parser getParser() {/* language specific parser */};
> }
> ```
What is the most appropriate way to achieve what I'm trying to do? How can I improve my code? | Use [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection).
[Spring Framework](http://static.springsource.org/spring/docs/2.5.x/reference/index.html) is an extremely useful piece of software and my personal favorite but there are many alternatives such as [Google Guice](http://code.google.com/p/google-guice/).
Using Spring, you would define two (three, fifteen, ...) separate contexts, one per language, and obtain needed component from appropriate context. It's similar to your second approach but without using `Language` class. For example:
```
# English context: english.xml
<bean id="Tokenizer" class="EnglishTokenizer"/>
<bean id="Parser" class="EnglishParser"/>
...
# Your code
ApplicationContext englishContext = ...; // context itself is injected
Parser englishParser = (Parser) englishContext.getBean("Parser");
```
Another alternative is to have a single context but prefix your bean ids with your language, e.g. "English-Tokenizer" and "Chinese-Tokenizer".
If you've never used dependency injection before, this may sound like too much work for a result that can be achieved via factory and / or dynamic class loading :-) But it's not - and it can do so much more (you can configure properties / dependencies of your components; you don't have to worry about caching or maintaining your own singletons, etc...) that once you start using it you'll wonder how you've ever lived without it :-)
**Update** (answers questions in 2nd comment).
Here's a sample "ComponentLocator" pattern. `ComponentLocator` is a singleton that has no dependencies on Spring. Its instance (and implementation) is injected by the context.
```
public abstract class ComponentLocator {
protected static ComponentLocator myInstance;
protected abstract <T> T locateComponent(Class<T> componentClass, String language);
public static <T> T getComponent(Class<T> componentClass, String language) {
return myInstance.locateComponent(componentClass, language);
}
}
```
Implementation of `ComponentLocator` assumes beans in your context are named as their interface names followed by semicolon and language (e.g. "com.mypackage.Parser:English"). ComponentLocatorImpl must be declared as bean in your context (bean name doesn't matter).
```
public class ComponentLocatorImpl extends ComponentLocator
implements ApplicationContextAware {
private ApplicationContext myApplicationContext;
public void setApplicationContext(ApplicationContext context) {
myApplicationContext = context;
myInstance = this;
}
@Override
protected <T> T locateComponent(Class<T> componentClass, String language) {
String beanName = componentClass.getName() + ":" + language;
return componentClass.cast(myApplicationContext.getBean(beanName, componentClass));
}
}
```
In your code elsewhere (in main()?) you're going to load `ApplicationContext`:
```
ApplicationContext ctx = new ClasspathXmlApplicationContext("components.xml");
```
Note that you don't actually need to refer to the context directly anywhere else in the application. Wherever you need to get your components you just do:
```
Parser englishParser = ComponentLocator.getComponent(Parser.class, "English");
Parser chineseParser = ComponentLocator.getComponent(Parser.class, "Chinese");
```
Note that the above is just one possible approach and it assumes that you're pretty much only putting your language-dependent classes in the context. In your case that's probably the best (due to requirement of having all languages available simultaneously) otherwise you'd be replicating all your classes (once per language), so your A/B/C question is probably not applicable here.
But if you do have A/B/C dependency what you can do is (I'm assuming A, B, C are interfaces and Aimpl, Bimpl, Cimpl are their implementations):
```
<bean id="A" class="Aimpl">
<property name="B" ref="B"/>
</bean>
<bean id="B" class="Bimpl">
<property name="C" ref="C"/>
</bean>
<bean id="C" class="Cimpl">
<property name="tokenizer" ref="Tokenizer:English"/>
</bean>
```
Your implementations would need to have setB(), setC() and setTokenizer() methods. This is easier then constructor injection, though latter is also possible. | Consider the dimensions of change. Use cases such as "Add a new language" and "Add a new component". How readily can you do this, how readily do you avoid mistakes.
I'm not clear how your map is populated in the first case, some kind of registration scheme? Am I right in thinking that responsibility for completeness is spread across many classes. Also I'm always suspicous of Singletons.
In the second case if you add a new conmponent then you must add one new method in the language class, and make sure it works. Adding new Languages seems to be localised to the constructor (and presumably some further implmentation methods).
Overall I prefer the second approach. | Multiple language components/classes [OOP/Patterns/IoC/DI] | [
"",
"java",
"design-patterns",
"oop",
"architecture",
"dependency-injection",
""
] |
I have a list containing 60 [DateTime](http://msdn.microsoft.com/en-us/library/system.datetime(VS.71).aspx) objects (sorted in ascending order) and need to validate that each date is 1 month greater than the previous one in the list.
For example, the following list of dates would be valid because they increment by one month with none missing:
> Jan-2009
> Feb-2009
> Mar-2009
> Apr-2009
However, the following list of dates would be invalid because Feb-2009 is missing:
> Jan-2009
> Mar-2009
> Apr-2009
The day doesn't matter, just the **month** and **year** are considered.
Is there an efficient/pretty way of doing this? | You could try the following:
```
int start = list.First().Year * 12 + list.First().Month;
bool sequential = list
.Select((date, index) => date.Year * 12 + date.Month - index)
.All(val => val == start);
```
This 'converts' the list of dates into a number that represents the Year and Month, which should be incrementing by 1 for each item in the list. We then subtract the current index from each of those items, so for a valid list, all items would have the same value. We then compare all values to `start`, which is the first computed value. | For all of the dates, if you take (year \* 12 + month) you'll get a sequential list of integers. That might be easier to check for gaps. | Validate DateTime's are sequential by month | [
"",
"c#",
"linq",
"performance",
"date",
"compare",
""
] |
I have an array of image files with relative paths, like this: `gallery/painting/some_image_name.jpg`. I am passing this array into a `foreach` loop which prints the path into the source of an `<img>`.
What is a safe reliable way to pull the name from a line such as that?
**`gallery/painting/some_image_name.jpg`** > to > **some image name** | basename($path, ".jpg") gives some\_image\_name, then you could replace \_ with space.
```
str_replace('_', ' ', basename($path, ".jpg"));
``` | ```
function ShowFileName($filepath)
{
preg_match('/[^?]*/', $filepath, $matches);
$string = $matches[0];
#split the string by the literal dot in the filename
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
#get the last dot position
$lastdot = $pattern[count($pattern)-1][1];
#now extract the filename using the basename function
$filename = basename(substr($string, 0, $lastdot-1));
#return the filename part
return $filename;
}
```
Reference: <https://www.php.net/basename()> | Get file name from path, and convert underscores to spaces | [
"",
"php",
"regex",
""
] |
Our solution has several (10+) C# projects. Each has a reference to the CAB extension library, with the reference pointing to the DLLs in the library's release folders. Each project has between four and seven such references.
We'd like to make some changes to the library; but to debug the changes, we'll need to build a debug version of the library and refer to that. I'd like to add the library's projects to our solution and change each of the DLL references to a project reference.
Is it possible to perform a 'find and replace' on the existing references, or will I have to do it by hand? | There isn't such a feature in the VS IDE.
However, as a .csproj file is just an XML document it is possible to do such a global search and replace in a scripted fashion e.g. by changing one file to observe the before and after states then running `sed` over the remainder.
For a one-off, going to the extent of writing a script to load the XML and making the substitutions by DOM manipulation is probably overkill. | Take a look at Jared's answer to this [SO thread](https://stackoverflow.com/questions/1080625/updating-visual-studio-project-references-programatically). That approach will likely work for you. | How can I perform 'find and replace' on references? | [
"",
"c#",
"visual-studio-2008",
"reference",
""
] |
This question might sound a bit stupid but here it goes.
I have two functions that can be called at any moment. The first function takes a snapshot, and the second one analyses the data taken from that snapshot. Of course if the user tries to analyse the snapshot before taking it, my application should throw an exception. I know the `ArgumentOutOfRangeException` that is generally thrown when......there is an invalid argument, but that is not really the case. Is there any in-built exception for this kind of cases, or will I have to use `ArgumentOutOfRangeException`?
Thanks | Sounds like an InvalidOperationException.
<http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx>
That said, if you can design your API so that you can't get in this situation, that would be better. Something like (pseudo):
```
public Data TakeSnapshot()
{
// ...
return new Data(...);
}
public void Analyze(Data data)
{
// ...
}
```
Like this, there's no way to call them out of order. | [`InvalidOperationException`](http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx)? | What kind of exception to throw? | [
"",
"c#",
".net",
"vb.net",
"exception",
""
] |
Here is the situation:
I have a database of 'tickets', and we track changes to the tickets each time they are saved. I am specifically looking at status changes, which track with the following format:
STATUS:{FROM}:{TO}
with {FROM} and {TO} changing to the respective statuses. What I need to do is generate numbers by weeks of the amount of tickets that were 'open' (meaning in draft status) at the end of any given week, say for the past 12 weeks. However, you are not limited to 'closing' a ticket and then reopening it, or making multiple changes in a single week.
So, what I need to do is modify the SQL below to ONLY consider the most recent "action" for any given entry. This way we avoid the problem of having entries that were 'closed' appear in the open count because they had been opened earlier.
```
SELECT track.historyID
FROM RS_HistoryTracker track
WHERE (track.action = 'STATUS:INITIAL:DRAFT'
OR track.action = 'STATUS:DELETED:DRAFT'
OR track.action = 'STATUS:DRAFT:DRAFT')
AND track.trackDateTime <= @endOfWeek
```
However, this statement is contained within another select statement, and is used to generate a complete list of history items:
```
SELECT COUNT(DISTINCT his.historyID) AS theCount
FROM RS_History his
WHERE his.historyID IN
(SELECT track.historyID
FROM RS_HistoryTracker track
WHERE (track.action = 'STATUS:INITIAL:DRAFT'
OR track.action = 'STATUS:DELETED:DRAFT'
OR track.action = 'STATUS:DRAFT:DRAFT')
AND track.trackDateTime <= @endOfWeek)
```
So how do I make the inner select consider only the most recent tracked 'action' that occured up to or on the endOfWeek date? HistoryTracker contains a datetime stamp column. | Looks like this works:
```
SELECT query.historyID
FROM
(SELECT MAX(track.trackID) AS maxTrackID, track.historyID
FROM RS_HistoryTracker track
WHERE track.trackDateTime <= '2009-08-06 23:59:59'
AND track.action LIKE 'STATUS:%'
GROUP BY historyID) AS query, RS_HistoryTracker track
WHERE track.historyID = query.historyID
AND track.trackID = query.maxTrackID
AND track.action LIKE 'STATUS:%:DRAFT'
``` | As a starter you can find the last history item for each ticket by doing something like this
```
select * from
(
--find max history id for each ticket
select
T1.ticketId,
max(T1.historyId) As LastHistoryId
from #Ticket T1
--add WHERE clause to filter out dates
group by
T1.ticketId
) MaxTicket
inner join
#Ticket T2 --find the ticket so you can get the status
on MaxTicket.ticketId = T2.ticketId
and MaxTicket.LastHistoryId=T2.Historyid
```
You may want to change how you find the latest ticket to be based on the date rather than the history id. | SQL Server - Selecting Most Recent Record to generate a list of changes | [
"",
"sql",
"sql-server",
""
] |
I am designing a simple chat application (just for the kick of it). I have been wondering of a simple design for that chat application. To give you overview.. here are the rules:
1. Anonymous user enter chat just with a nickname. (User id) is presumably assigned by system in background.
2. They can join in (subscribe to) a chat conversation. And he'll see the chat-text from other users appearing on the designated area.
3. They can reply to a particular conversation and everyone else should see that.
THATS IT! (See I told you it was a simple chat application). So, my intention is not really the application; but the design pattern and objects used in it.
Now here is how I have designed it. (I am coding in java.. in case that really matters)
1. User Object - Two attributes id and nickname
2. Message Object - A simple Message interface and implementation (for now) as a SimpleMessage, with a String as the attribute to contain the message.
3. Chat Window Object - Basically composition of User and Messages. As it has One User Object and List of Messages.
4. Chat Session - Again composition. Basically it'll have a List of Chat Windows. Each chat window registers to a chat session. Chat session is responsible to notify all chat windows when a new message appears. (Observer pattern anyone?)
Alright.. so now I have implemented observer pattern by making ChatWindow implement "ChatListener" patter which has method called "notify(Message)". So ChatSession notifies every registered ChatWindow.
Now here are few things I want to clarify/want your opinion on.
1. I need to have de-register method also for all chat windows, in case a chat window is closed and doesn't want to get any more notifications. That potentially means, that either I should have a "Static" central registration manager which has only one instance and then any chat window should be able to de-register itself by providing a "chat session" id. For that reason, each chat session should have an id. (Included hereon). OR I could maintain an instance of ChatSession in Chat Window too, to always have an instance ready. (I hate singletons as I think they go against oops).
Another way would be to not have de-registration control of chat window, with chat window, instead the notification of window closure should come directly to ChatSession and it should do, what it should do!
2. Does this design makes sense at all? If you'd say it's a piece of CRAP and give me a yet better approach; you'll definitely get a BIG THANK YOU from me. Apart from observer pattern what all patterns could be used here to simplify it more or make it better. Also.. any weak points of this design, if it's appropriate but can be improved.
3. Also when a user types a new message in his own chat window; it needs to be propogated to all chat windows, which is what chat session does, but at the same time; does that mean that.. chat session needs to get a message with "chat window id" and message? And then it propogates it to all windows, including the one which is the owner of the message? What is a better way to handle this. I mean, a way where window lets the chat session know of the message and then chat session to all other windows. (I am thinking it'll need some if's... don't like them either)
Anyway... do let me know your comments. Also please rem. working application is not the intent, I am looking for a good discussion, good Design pattern practices and usage.
Complete code below, if it gives you a high... Feel free to tear it apart and bring up issues related to almost any semantics.
```
package com.oo.chat;
public class User {
private Long userId;
private String nickname;
public User(Long userId, String nickname) {
this.userId = userId;
this.nickname = nickname;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Long getUserId() {
return userId;
}
public String getNickname() {
return nickname;
}
public boolean equals(Object objectToCompare) {
if (!(objectToCompare instanceof User)) {
return false;
}
User incoming = (User) objectToCompare;
if (incoming.getNickname() != null && incoming.getUserId() != null) {
if (incoming.getNickname().equalsIgnoreCase(this.nickname)
&& incoming.getUserId().equals(this.userId))
return true;
}
return false;
}
}
package com.oo.chat;
public interface Message {
public String getValue();
public void setValue(String value);
}
package com.oo.chat;
public class SimpleMessage implements Message {
private String value;
public SimpleMessage() {
}
public SimpleMessage(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package com.oo.chat;
public interface ChatListener {
public void notify(Message newMessage);
}
package com.oo.chat;
import java.util.ArrayList;
import java.util.List;
public class ChatWindow implements ChatListener {
private User user;
private List<Message> messageList;
private Long id;
public User getUser() {
return user;
}
public List<Message> getMessageList() {
return messageList;
}
public void setUser(User user) {
this.user = user;
}
public void setMessageList(List<Message> messageList) {
this.messageList = messageList;
}
public void addMessageToList(Message newMessage) {
if (this.messageList == null) {
this.messageList = new ArrayList<Message>();
}
this.messageList.add(newMessage);
}
public void notify(Message newMessage) {
addMessageToList(newMessage);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
package com.oo.chat;
import java.util.ArrayList;
import java.util.List;
public class ChatSession {
private List<ChatListener> registeredChatListeners;
public void register(ChatWindow chatWindow) {
if (registeredChatListeners == null)
registeredChatListeners = new ArrayList<ChatListener>();
registeredChatListeners.add(chatWindow);
}
public List<ChatListener> getRegisteredChatListeners() {
return registeredChatListeners;
}
public void setRegisteredChatWindows(
List<ChatListener> registeredChatListeners) {
this.registeredChatListeners = registeredChatListeners;
}
public void incomingMessage(Long chatListenerId, Message message) {
publish(message);
}
protected void publish(Message messageToPublish) {
if (registeredChatListeners != null) {
for (ChatListener eachListener : registeredChatListeners) {
eachListener.notify(messageToPublish);
}
}
}
}
```
Thanks to all contributers in advance.
Cheers | Just looking at the `User` object, why does equality depend on id *and* nickname ? That seems a little counter intuitive to me. I would expect if you have an id, then that is the identification of the object, and hence what you'd use in an equality condition.
I see also that you have a setter for the user id. So do you really want to change user id ? I see that you can change the nickname, which makes sense. But I would expect the id to remain constant.
Note also that since you're overriding equals(), you should also [override hashCode()](http://javahowto.blogspot.com/2007/01/override-equals-and-hashcode-methods.html).
Now, if hashCode() and equals() rely on immutable fields (e.g. the id), then the results of hashCode() won't change, and if you put a User in a hashed collection (e.g. HashMap) then you're not going to lose it later (which is very confusing)!
Finally (!) I would protect the constructor and setters against null nicknames (make them throw IllegalArgumentExceptions) and then code like equals() doesn't have to worry about a null nickname (unless 'null' has a meaning for the nickname). I would do the same for id, since you have this as a Long (object). But couldn't this be a primitive long ? | The basic design looks sound to me. Obviously to complete this, you would nee to add a lot more features. The current design keeps all messages in memory indefinitely, but at some point you are going to need code for purging old messages.
The few significant design issues that I do see are:
1. The message interface doesn't link back the the sender of the message - Most chats show who said what, and this will be difficult without a User field in the message.
2. The message interface doesn't have a time property. This will make purging old messages more difficult. | Suitable Design Pattern for a Simple Chat Application | [
"",
"java",
"design-patterns",
""
] |
I create my prepared statement as:
```
pg_prepare('stm_name', 'SELECT ...');
```
Today, I had a problem (calling twice a function for mistake) when declaring a prepared statement with the same name twice:
```
Warning: pg_prepare() [function.pg-prepare]: Query failed: ERROR: prepared statement "insert_av" already exists in xxx on line 221
```
So, as the question title, there is a way **to check if a prepare statement with the same label already exists, and in case, overwrite it?**
I know this error is from my mistake and will be solved by simply declaring the prepared statements at the begin of my code, but I'm wondering if there is a solution to have more control over them.
**EDIT:**
After the Milen answer, is quite simply to check if the prepared statement is already in use, simply querying the db for the table pg\_prepared\_statements:
```
try{
$qrParamExist = pg_query_params("SELECT name FROM pg_prepared_statements WHERE name = $1", array($prepared_statement_name));
if($qrParamExist){
if(pg_num_rows($qrParamExist) != 0){
echo 'parametized statement already created';
}else{
echo 'parametized statement not present';
}
}else{
throw new Exception('Unable to query the database.');
}
}catch(Exception $e){
echo $e->getMessage();
}
```
But, I don't think this is a good solution, because i have to query the database every time.
Ok, usually the prepared statements are declared in the begin of the script and then just reused, but, I have a class nicely wired and I don't like to declare 10 prepared statements when I'll use just 3 of them.
So, I think I'll use a simple PHP array to keep track the statements I create, and then with `isset()` function check if it exists or needs to be created:
```
try{
$prepare = pg_prepare('my_stmt_name', "SELECT ...");
if($prepare){
$this->rayPrepared['my_stmt_name'] = true;
}else{
throw new Exception('Prepared statement failed.');
}
}catch(Exception $e){
echo $e->getMessage();
}
``` | One way (I hope someone will point out a simpler one):
```
<?
$prepared_statement_name = 'activity1';
$mydbname = '...';
$conn = pg_connect("host=... port=... dbname=... user=... password=...");
$result = pg_query_params($conn, 'SELECT name FROM pg_prepared_statements WHERE name = $1', array($prepared_statement_name));
if (pg_num_rows($result) == 0) {
$result = pg_prepare($conn, $prepared_statement_name, 'SELECT * FROM pg_stat_activity WHERE datname = $1');
}
$result = pg_execute($conn, $prepared_statement_name, array($mydbname));
while($row = pg_fetch_row($result)) {
var_dump($row);
}
``` | Haven't tried this in php but if this is feasible in your application (if you need the statement only in one place and don't have to "fetch" it again by name) you could try to prepare an unnamed statement.
<http://www.postgresql.org/docs/8.4/interactive/libpq-exec.html> says:
> PQprepare
> ...
> stmtName may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session.
php\_pg uses PQprepare, so this might work for you. | PHP/PostgreSQL: check if a prepared statement already exists | [
"",
"php",
"postgresql",
"prepared-statement",
""
] |
In Hibernate 3, is there a way to do the equivalent of the following MySQL limit in HQL?
```
select * from a_table order by a_table_column desc limit 0, 20;
```
I don't want to use setMaxResults if possible. This definitely was possible in the older version of Hibernate/HQL, but it seems to have disappeared. | [This was posted](https://forum.hibernate.org/viewtopic.php?f=9&t=939314) on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:
> Limit was *never* a supported clause
> in HQL. You are meant to use
> setMaxResults().
So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I *think* this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.
I think `Query.setMaxResults()` really is your only option. | ```
// SQL: SELECT * FROM table LIMIT start, maxRows;
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
``` | How do you do a limit query in JPQL or HQL? | [
"",
"java",
"hibernate",
"hql",
"hibernate3",
""
] |
I have lines in an ASCII text file that I need to parse.
The columns are separated by a variable number of spaces, for instance:
```
column1 column2 column3
```
How would i split this line to return an array of only the values?
thanks | ```
String testvar = "Some Data separated by whitespace";
String[] vals = testvar.split("\\s+");
```
`\s` means a whitespace character, the `+` means 1 or more. `.split()` splits a string into parts divided by the specified delimiter (in this case 1 or more whitespace characters). | ```
sed 's/ */\n/g' < input
```
Two spaces there btw. | How can I split out individual column values from each line in a text file? | [
"",
"java",
"parsing",
"text-parsing",
""
] |
Let's say I have two entities: Event and Activity
An Event is something that happens at (seemingly) random times, like Sunrise, Sunset, Storm, Fog, etc.
I have a table for this:
```
create table Event (
eventKey int,
eventDesc varchar(100),
started datetime
)
EventKey | EventDesc | Started
1 "Sunset" 2009-07-03 6:51pm
2 "Sunrise" 2009-07-04 5:33am
3 "Fog" 2009-07-04 5:52pm
4 "Sunset" 2009-07-04 6:49pm
5 "Full Moon" 2009-07-04 10:12pm
6 "Sunrise" 2009-07-05 5:34am
```
Then I have a table of activities that people participated in, and which events they relate to (i.e. an action could be long-running and cross multiple events: "Camp-out over the weekend"):
```
create table EventTask (
activityKey int,
activityDesc varchar(100),
startEventKey int,
endEventKey int
)
ActivityKey | ActivityDesc | StartEventKey | EndEventKey
123 "Camp-out" 1 5
234 "Drive home" 6 6
```
I want to output a timeline of actions that are marked by the events that happened:
```
ActivityKey | ActivityDesc | EventKey | EventDesc
123 "Camp-out" 1 "Sunset"
123 "Camp-out" 2 "Sunrise"
123 "Camp-out" 3 "Fog"
123 "Camp-out" 4 "Sunset"
123 "Camp-out" 5 "Full Moon"
234 "Drive Home" 6 "Sunrise"
```
Is it possible to write a query that will do this in linear time, [similar to this question](https://stackoverflow.com/questions/1060524)? Please also recommend indexes or any other optimizations you can think of. The current solution is written in C#, but I would love a fast SQL solution.
What is the optimal query to do this? | ```
/*
create table Event (
eventKey int,
eventDesc varchar(100),
started timestamp
);
insert into event values( 1, 'Sunset' , '2009-07-03 6:51pm');
insert into event values(2, 'Sunrise', '2009-07-04 5:33am');
insert into event values(3, 'Fog' , '2009-07-04 5:52pm');
insert into event values(4, 'Sunset' , '2009-07-04 6:49pm');
insert into event values(5, 'Full Moon', '2009-07-04 10:12pm');
insert into event values(6, 'Sunrise' , '2009-07-05 5:34am');
select * from event;
create table EventTask (
activityKey int,
activityDesc varchar(100),
startEventKey int,
endEventKey int
)
insert into eventtask values(123 , 'Camp-out', 1 , 5);
insert into eventtask values(234, 'Drive home', 6, 6);
select * from eventtask;
*/
select a.activitykey, a.activitydesc, b.eventkey, b.eventdesc
from
eventtask a
join event b on b.eventkey between a.starteventkey and a.endeventkey
order by
a.activitykey, b.eventkey;
activitykey activitydesc eventkey eventdesc
-------------- --------------- ----------- ------------
123 Camp-out 1 Sunset
123 Camp-out 2 Sunrise
123 Camp-out 3 Fog
123 Camp-out 4 Sunset
123 Camp-out 5 Full Moon
234 Drive home 6 Sunrise
6 record(s) selected [Fetch MetaData: 3/ms] [Fetch Data: 1/ms]
[Executed: 7/7/09 4:24:34 PM EDT ] [Execution: 15/ms]
```
If your tables are large, you would definitely want indexes on event.eventkey, eventtask.starteventkey and eventtask.endeventkey.
Note that indexes improve query speed but slow insert and update.
Here's the version which does NOT require the event.eventkey column to have significance (more correct):
```
select a.activitykey, a.activitydesc, d.eventkey, d.eventdesc
from
eventtask a
join event b on b.eventkey = a.starteventkey
join event c on c.eventkey = a.endeventkey
join event d on d.started between b.started and c.started
order by
a.activitykey, d.started;
activitykey activitydesc eventkey eventdesc
-------------- --------------- ----------- ------------
123 Camp-out 1 Sunset
123 Camp-out 2 Sunrise
123 Camp-out 3 Fog
123 Camp-out 4 Sunset
123 Camp-out 5 Full Moon
234 Drive home 6 Sunrise
6 record(s) selected [Fetch MetaData: 2/ms] [Fetch Data: 0/ms]
[Executed: 7/8/09 10:01:25 AM EDT ] [Execution: 4/ms]
``` | I would redefine the activity table so has a startTime and an EndTime, rather than base it on the random events. Then if I really want to see what 'events' were taking place during that time, I would join on the time range. This makes more sense from an OO/flexibility perspective, though you will see a larger performance cost.
```
declare @Event table(
id int,
name varchar(100),
[time] datetime
);
insert into @Event values(1, 'Sunset', '2009-07-03 6:51pm');
insert into @Event values(2, 'Sunrise', '2009-07-04 5:33am');
insert into @Event values(3, 'Fog', '2009-07-04 5:52pm');
insert into @Event values(4, 'Sunset', '2009-07-04 6:49pm');
insert into @Event values(5, 'Full Moon', '2009-07-04 10:12pm');
insert into @Event values(6, 'Sunrise', '2009-07-05 5:34am');
select * from @Event;
declare @Activity table (
id int,
name varchar(100),
startTime datetime,
endTime datetime
)
insert into @Activity values(123, 'Camp-out', '2009-07-03 6:00pm', '2009-07-05 5:00am');
insert into @Activity values(234, 'Drive home', '2009-07-05 5:00am', '2009-07-05 6:00am');
select *
from @Activity A
join @Event E on E.[time] > A.startTime and E.[time] < A.endTime
order by A.startTime
``` | Finding a timeline using a range of values - entity modeling | [
"",
"sql",
"performance",
"optimization",
""
] |
I want to access the webcam so I can do some precessing on the images, like tracking a light, but I can't find a way to access the webcam. I googled it but I got confused.
Can you point me to a library that can do that (windows)? and maybe also provide an example?
I would need to periodically get a pixel map of the image, about 20 time per second or so if it would be possible. | Checkout [OpenCV](https://opencv.org/releases/). It is a cross-platform computer vision SDK and has modules to capture images from the webcam. Maybe too feature rich for you, but it's worth a look. | You need [DirectShow](http://msdn.microsoft.com/en-us/library/dd375454.aspx). This is a Windows framework for video playback and capture.
It's included in [Windows SDK](http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF) and there are many samples for video input capture included.
But, as Vijay mentioned, you can also try using [OpenCV](http://sourceforge.net/projects/opencvlibrary) since it not only abstracts away the platform-specific video capture API, it also includes many image processing algorithms you could use to track the light in your project. | webcam access in c++ | [
"",
"c++",
"windows",
"webcam",
""
] |
I'm currently building an app that generates quotes. The total time to generate all quotes is about 10 secs, and at present provides an unacceptable user experience.
What I want to do is multi-thread each quote so the user can see results as they come in. The problem is that the app I've inherited does a lot of bus logic on the db.
What I'm wondering is if it's ok to multithread each quote item, or would this cause too much load on the db server (e.g. 5 quotes = 5 threads, or threadqueueworkeritems)? | The only thing I would worry about is what "generating a quote" entails on the DB. This may involve writing to the database and if you've got a lot of transactional activity in there, the different quotes may compete with each other and could end up with quotes coming in series due to blocking or worse, deadlocking.
This is worst-case scenario stuff though, going from the scant details given in the question. | On most RDBMS, 5 concurrent connections shouldn't be an issue, so I think you can easily have five threads, each one using its own connection | Multithread database access (.NET) | [
"",
".net",
"sql",
"database",
"multithreading",
""
] |
I am trying to take the code in an .ASMX web service and change it into a class library project. The web service project has a web.config file with:
```
<applicationSettings>
<myService.Properties.Settings>
<setting name="DownloadChunkSize" serializeAs="String">
<value>100000</value>
</setting>
```
..and the code in the FileService.asmx.cs file uses this to retrieve the value:
```
int chunkSize = (int)Properties.Settings.Default.DownloadChunkSize;
```
When I try to re-architect this code to eliminate the .asmx web service, I get a compile time error in my class library project because there is no longer a web.config available. Let me try to explain a bit more about what I've done so far (and why):
The motivation for this is to simplify my projects. That is, I have a Vstudio solution with an .asmx project that works. It has a few methods and encapsulates the communication with another .asmx web service supplied by a vendor.
The new design I am attempting is as follows:
Project 1 is a class library project called ProxyASMX with a web reference to the vendor web service. I've provided no code here; it simply has a small app.config pointing at the vendor web service.
Project 2 is a class library project with a reference to the ProxyASMX.dll. The code in this FileService.cs file is the same as my original web service but the [webmethod] attributes have been removed. This is the project I'm having trouble compiling.
Project 3 is a web application project with 2 HTTPHandlers - Upload.ashx and Download.ashx. This project will have a reference to the Project 2 class library. I tried replacing the small default web.config content with the more comprehensive web.config content from the original solution but when that did not work I thought I better consult the experts about this venture.
I hope the above sketch is clear. I THINK this should be very do-able but now I am not so sure. | You can add Application Settings to a class library. So you add the Application Settings on the project that "consumes them". Then you simply copy these config sections "up the project stack".
So if I understand you correct, you need to add the DownloadChunkSize setting to Project 2 and copy this section to your web.config in Project 3. This will be something like:
```
<applicationSettings>
<Project2.Properties.Settings>
<setting name="DownloadChunkSize" serializeAs="String">
<value>100000</value>
</setting>
```
You can access this setting inside Project 3 using:
```
Project2.Properties.Settings.Default.DownloadChunckSize
```
And in Project 2:
```
Properties.Settings.Default.DownloadChunckSize
``` | I think you need to create an [ExeConfigurationFileMap](http://msdn2.microsoft.com/en-us/library/system.configuration.execonfigurationfilemap.aspx) and use it to retrieve values from your App.config from Project 1.
```
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"ConfigTest.exe.config"; // relative path names possible
// Open another config file
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
// read/write from it as usual
ConfigurationSection mySection = config.GetSection("mySection");
config.SectionGroups.Clear(); // make changes to it
config.Save(ConfigurationSaveMode.Full); // Save changes
```
There's a nice helper from the Enterprise Library for this kind of stuff - Tom Hollander has done a good [writeup](http://blogs.msdn.com/tomholl/archive/2006/04/02/entlib2externalconfig.aspx) of it | How to resolve reference to applicationSettings when web.config not available | [
"",
"c#",
"visual-studio",
"web-config",
"asmx",
"class-design",
""
] |
How to include multiple paths when a PHP script is called?
For example, I need to point [include\_path](https://www.php.net/manual/en/function.set-include-path.php) to multiple directories; inside each directories containing sub directories etc. But I want to include all the php files inside the sub directories as well, so that when my master PHP script can call any methods and objects defined inside the directories.
Any idea?
**If possible, I would like to call a function to do it, instead of specifying the root directories and loop through everything inside the directories.** | It sounds like you want to specify each and every directory in your include\_path to allow you to just do
```
require_once("x.php"); // this is in ./foo/bar
require_once("y.php"); // this is in /docs/utils/
require_once("z.php"); // this is in /some/other/include/path
```
In which case, don't. That idea is full of lose, and bad for documentation, debugging, and sanity.
*If you must,* you'd have to write a function to recursively crawl your include directory by hand as part of a bootstrap process, or do it by hand.
Either way, this sounds like a bad idea and isn't a feature for a reason. | You might be better off using [`spl_autoload_register()`](http://php.net/spl_autoload_register), to register a callback which PHP will call when it can't find a class you are trying to access. You can then write a function to include the correct file based on the name. Libraries like PEAR tend to do this by splitting the Class name by underscore, and each part corresponds to a directory in its path.
I don't think there is any way that you can get PHP (when including a file) to recursively search the include path until it finds the file (unless you write this logic yourself - I suppose you could write wrappers around require(), include() etc., and call those instead, but I wouldn't).
You could also recursively scan through the directories and add each one to the include path when your script starts, but I think this would make including subsequent files much slower. | Include Multiple Directories in PHP script | [
"",
"php",
""
] |
Is it possible to pass a function pointer as a template argument without using a typedef?
```
template<class PF>
class STC {
PF old;
PF& ptr;
public:
STC(PF pf, PF& p)
: old(*p), ptr(p)
{
p = pf;
}
~STC() {
ptr = old;
}
};
void foo() {}
void foo2() {}
int main() {
void (*fp)() = foo;
typedef void (*vfpv)();
STC<vfpv> s(foo2, fp); // possible to write this line without using the typedef?
}
``` | Yes:
`STC<`**`void (*)()`**`> s(foo2, fp); // like this`
It's the same as taking the `typedef` declaration and removing the `typedef` keyword and the name. | It is totally possible,
I'd also recommend looking up boost::function & boost::bind as an alternative solution. | Function pointer as template argument? | [
"",
"c++",
""
] |
How would you go about Cutting strings short so it doesnt go to the next line in a div tag For example my `message` string contained the following:
> We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply. If your question is about this website, ask it on meta instead.
And i want to preferably display it as
> We prefer questions that can be answered, not just discussed. Provide ... Read More
Im thinking cutting the string short using PHP but then you have the following problem
> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ... Read More
You can see that the above string can still be expanded a bit more. Any way to do this or Not, Thanks in Advance | The following mostly works; the main issue is that the "...Read more" notice can cover up part of a letter. It also uses a bunch of presentational elements and requires JS. It makes me feel unclean.
The outermost element (of class .string) is used to set the overall size. .text holds the text to display. Between .string and .text in the descendent hierarchy is an element with a large width. This puts all the text in .text on one line. JS is used to show or hide the "...Read more" notice.
```
<style type="text/css">
.string {
height: 1em;
width: 25%;
position: relative; /* create containing block for children */
border: 1px solid black;
overflow: hidden;
background: white; /* or whatever, as long as it's not "transparent". */
}
.string .line {
width: 5000px; /* long enough for you? */
}
.string .notice {
position: absolute;
top: 0;
right: 0;
z-index: 1;
display: none;
background: inherit; /* so that the notice will completely cover up whatever's beneath */
}
</style>
<div class="string">
<div class="line"><span class="text">We prefer questions that can be answered,
not just discussed. Provide details. Write clearly and simply. If your
question is about this website, ask it on meta instead.</span></div>
</div>
<hr />
<div class="string">
<div class="line"><span class="text">Lorem ipsum dolor sit amet.</span></div>
</div>
<script>
function isOverflowed(elt) {
return elt.offsetWidth > elt.parentNode.parentNode.clientWidth;
}
function getNotice(textElt) {
try {
return (textElt.parentNode.parentNode.getElementsByClassName('notice'))[0];
} catch (e) {
return {style: {}};
}
}
function show(elt) {
elt.style.display = 'block';
}
function hide(elt) {
elt.style.display = 'none';
}
function showReadMoreNotices() {
var text=document.getElementsByClassName('text');
for (var i=0; i<text.length; ++i) {
if (isOverflowed(text[i])) {
show(getNotice(text[i]));
} else {
hide(getNotice(text[i]));
}
}
}
var strings = document.getElementsByClassName('string');
var notice = document.createElement('div');
notice.appendChild(document.createTextNode('\u2026Read more'));
notice.className = 'notice';
for (var i=0; i<strings.length; ++i) {
strings[i].appendChild(notice.cloneNode(true));
}
showReadMoreNotices();
/* use your favorite event registration method here. Not that the traditional
* model is my favorite, it's just simple.
*/
window.onresize = showReadMoreNotices;
</script>
``` | How you can shorten a string is already answered, but your main question:
How would you go about Cutting strings short **so it doesnt go to the next line in a div tag**
this will not work in most cases.
for example:
iiiiiiiiii
wwwwwwwwww
You see the problem ?
this only works if your chars have the same width like:
```
iiiiiiiiii
wwwwwwwwww
``` | Cut strings short PHP | [
"",
"php",
"string",
""
] |
I need to find the most popular occurrence of an item grouped by date and display the total of all items along with the name of this item. Is something like this possible in a single query?
note: If they are all of equal occurrence (see last 3 rows in Insert) than I can just show at random or the first or last occurrence (whichever is easiest).
If this can't be done in the sql then will have to run through the result and sort the data via PHP which seems like it'll be quite messy.
Edit: Sorry, I had the wrong total for '2009'08-04'. It should be 4.
An example of what I need:
```
+------------+---------------------+-------+
| date | item | total |
+------------+---------------------+-------+
| 2009-08-02 | Apple | 5 |
| 2009-08-03 | Pear | 2 |
| 2009-08-04 | Peach | 4 |
| 2009-08-05 | Apple | 1 |
| 2009-08-06 | Apple | 3 |
+------------+---------------------+-------+
```
Here's an example table:
```
CREATE TABLE IF NOT EXISTS `test_popularity` (
`date` datetime NOT NULL,
`item` varchar(256) NOT NULL,
`item_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `test_popularity` (`date`, `item`, `item_id`) VALUES
('2009-08-02 00:00:00', 'Apple', 1),
('2009-08-02 00:00:00', 'Pear', 3),
('2009-08-02 00:00:00', 'Apple', 1),
('2009-08-02 00:00:00', 'Apple', 1),
('2009-08-02 00:00:00', 'Pear', 0),
('2009-08-03 00:00:00', 'Pear', 3),
('2009-08-03 00:00:00', 'Peach', 2),
('2009-08-04 00:00:00', 'Apple', 1),
('2009-08-04 00:00:00', 'Peach', 2),
('2009-08-04 00:00:00', 'Peach', 2),
('2009-08-04 00:00:00', 'Pear', 3),
('2009-08-05 00:00:00', 'Apple', 1),
('2009-08-06 00:00:00', 'Apple', 1),
('2009-08-06 00:00:00', 'Peach', 2),
('2009-08-06 00:00:00', 'Pear', 3);
``` | My initial suggestion was **incorrect**:
```
SELECT
date, item, SUM(cnt)
FROM (
SELECT
date, item, count(item_id) AS cnt
FROM test_popularity
GROUP BY date, item_id
ORDER BY cnt DESC
) t
GROUP BY date;
```
This erroneously assumes that the outside aggregation (by date) will select the first row of the inner derived table which was ordered by cnt. This behavior is, in fact, undefined and not guaranteed to be consistent.
Here is the proper solution:
```
SELECT
t1.date, t1.item,
(SELECT COUNT(*) FROM test_popularity WHERE date = t1.date) as total
# see note!
FROM test_popularity t1
JOIN (
SELECT date, item, item_id, COUNT(item_id) as count
FROM test_popularity
GROUP BY date, item_id
) AS t2
ON t1.date = t2.date AND t1.item_id = t2.item_id
GROUP BY t1.date;
```
**Note:**
I added the `(SELECT COUNT(*)) AS total` because the question asked for this in one query. However, this will not scale as it is a correlated subquery. This means that for every t1.date the SELECT COUNT(\*) subquery will run. Please benchmark and see if it performs suitably for your needs. If not, then I suggest getting the daily totals in a separate query. You would merge these results in your application. | thanks to hohodave for his initial response:
```
SELECT date, item, cnt, (
SELECT COUNT( * )
FROM test_popularity
WHERE date = t.date
) AS totalCnt
FROM (
SELECT date, item, count( item_id ) AS cnt
FROM test_popularity
GROUP BY date, item_id
ORDER BY cnt DESC
)t
GROUP BY date;
``` | mySQL query - show most popular item | [
"",
"php",
"mysql",
""
] |
First question on Stackoverflow (.Net 2.0):
So I am trying to return an XML of a List with the following:
```
public XmlDocument GetEntityXml()
{
StringWriter stringWriter = new StringWriter();
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
List<T> parameters = GetAll();
serializer.Serialize(xmlWriter, parameters);
string xmlResult = stringWriter.ToString();
xmlDoc.LoadXml(xmlResult);
return xmlDoc;
}
```
Now this will be used for multiple Entities I have already defined.
Say I would like to get an XML of `List<Cat>`
The XML would be something like:
```
<ArrayOfCat>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</ArrayOfCat>
```
Is there a way for me to get the same Root all the time when getting these Entities?
Example:
```
<Entity>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</Entity>
```
Also note that I do not intend to Deserialize the XML back to `List<Cat>` | There is a much easy way:
```
public XmlDocument GetEntityXml<T>()
{
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("TheRootElementName"));
ser.Serialize(writer, parameters);
}
return xmlDoc;
}
``` | If I understand correctly, you want the root of the document to always be the same, whatever the type of element in the collection ? In that case you can use XmlAttributeOverrides :
```
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attr = new XmlAttributes();
attr.XmlRoot = new XmlRootAttribute("TheRootElementName");
overrides.Add(typeof(List<T>), attr);
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), overrides);
List<T> parameters = GetAll();
serializer.Serialize(xmlWriter, parameters);
``` | XML Serialization of List<T> - XML Root | [
"",
"c#",
"xml",
"xml-serialization",
"root",
"generic-list",
""
] |
For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
```
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
```
In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.
The naive solution for creating the first comparison function would be something like this:
```
def comparepeople(person1, person2):
if cmp(person1.lastname, person2.lastname) == 0:
if cmp(person1.firstname, person2.firstname) == 0:
return cmp(person1.dob, person2.dob);
return cmp(person1.firstname, person2.firstname);
return cmp(person1.lastname, person2.lastname);
```
It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.
So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members? | If you really want a comparison function, you can use
```
def comparepeople(p1, p2):
o1 = p1.lastname, p1.firstname, p1.dob
o2 = p2.lastname, p2.firstname, p2.dob
return cmp(o1,o2)
```
This relies on tuple comparison. If you want to sort a list, you shouldn't write a comparison function, though, but a key function:
```
l.sort(key=lambda p:(p.lastname, p.firstname, p.dob))
```
This has the advantage that it is a) shorter and b) faster, because each key gets computed only once (rather than tons of tuples being created in the comparison function during sorting). | Here's one way (maybe not the fastest):
```
def compare_people_flexibly(p1, p2, attrs):
"""Compare `p1` and `p2` based on the attributes in `attrs`."""
v1 = [getattr(p1, a) for a in attrs]
v2 = [getattr(p2, a) for a in attrs]
return cmp(v1, v2)
def compare_people_firstname(p1, p2):
return compare_people_flexibly(p1, p2, ['firstname', 'lastname', 'dob'])
def compare_people_lastname(p1, p2):
return compare_people_flexibly(p1, p2, ['lastname', 'firstname', 'dob'])
```
This works because getattr can be used to get attributes named by a string, and because Python compares lists as you'd expect, based on the comparison of the first non-equal items.
Another way:
```
def compare_people_flexibly(p1, p2, attrs):
"""Compare `p1` and `p2` based on the attributes in `attrs`."""
for a in attrs:
c = cmp(getattr(p1, a), getattr(p2, a))
if c:
return c
return 0
```
This has the advantage that it doesn't build two complete lists of attributes, so may be faster if the attribute lists are long, or if many comparisons complete on the first attribute.
Lastly, as Martin mentions, you may need a key function rather than a comparison function:
```
def flexible_person_key(attrs):
def key(p):
return [getattr(p, a) for a in attrs]
return key
l.sort(key=flexible_person_key('firstname', 'lastname', 'dob'))
``` | Pythonic Comparison Functions | [
"",
"comparison",
"metaprogramming",
"python",
""
] |
I have an interface class similar to:
```
class IInterface
{
public:
virtual ~IInterface() {}
virtual methodA() = 0;
virtual methodB() = 0;
};
```
I then implement the interface:
```
class AImplementation : public IInterface
{
// etc... implementation here
}
```
When I use the interface in an application is it better to create an instance of the concrete class AImplementation. Eg.
```
int main()
{
AImplementation* ai = new AIImplementation();
}
```
Or is it better to put a factory "create" member function in the Interface like the following:
```
class IInterface
{
public:
virtual ~IInterface() {}
static std::tr1::shared_ptr<IInterface> create(); // implementation in .cpp
virtual methodA() = 0;
virtual methodB() = 0;
};
```
Then I would be able to use the interface in main like so:
```
int main()
{
std::tr1::shared_ptr<IInterface> test(IInterface::create());
}
```
The 1st option seems to be common practice (not to say its right). However, the 2nd option was sourced from "Effective C++". | One of the most common reasons for using an interface is so that you can "program against an abstraction" rather then a concrete implementation.
The biggest benefit of this is that it allows changing of parts of your code while minimising the change on the remaining code.
Therefore although we don't know the full background of what you're building, I would go for the Interface / factory approach.
Having said this, in smaller applications or prototypes I often start with concrete classes until I get a feel for where/if an interface would be desirable. Interfaces can introduce a level of indirection that may just not be necessary for the scale of app you're building.
As a result in smaller apps, I find I don't actually need my own custom interfaces. Like so many things, you need to weigh up the costs and benefits specific to your situation. | There is yet another alternative which you haven't mentioned:
```
int main(int argc, char* argv[])
{
//...
boost::shared_ptr<IInterface> test(new AImplementation);
//...
return 0;
}
```
In other words, one can use a smart pointer without using a static "create" function. I prefer this method, because a "create" function adds nothing but code bloat, while the benefits of smart pointers are obvious. | Best way to use a C++ Interface | [
"",
"c++",
"interface",
""
] |
I have to produce an ad-hoc report on the number of transactions made with different credit card types. For the purposes of the report it is fine to assume that all credit cards that start with a 4 are VISA cards and that those that start with a 5 are MasterCard.
This query works well for the above distinctions:
```
select card_type =
case substring(pan,1,1)
when '4' then 'VISA'
when '5' then 'MasterCard'
else 'unknown'
end,count(*),
sum(amount)
from transactions
group by card_type
```
However in our situation (not sure how this works world wide) all cards that start with a 3 can be considered Diners Club Cards except for those that start with a 37 which are AMEX cards.
Extending the above query like this seems like a complete hack
```
select card_type =
case substring(pan,1,2)
when '30' then 'Diners'
...
when '37' then 'AMEX'
...
when '39' then 'Diners'
when '40' then 'VISA'
...
when '49' then 'VISA'
when '50' then 'MasterCard'
...
when '59' then 'MasterCard'
else 'unknown'
end,count(*),
sum(amount)
from transactions
group by card_type
```
Is there an elegant way of grouping by the first digit in all cases except where the first two digits match the special case?
*I also have no idea how to* Title *this question if anyone wants to help out...*
**EDIT**: I had the values for MasterCard and VISA mixed up, so just to be correct :) | You can do case statements like the following:
```
select case
when substring(pan,1,2) = '37' then 'AMEX'
when substring(pan,1,1) = '3' then 'Diners'
when substring(pan,1,1) = '4' then 'Mastercard'
when substring(pan,1,1) = '5' then 'VISA'
else 'unknown'
end,
count(*),
sum(amount)
from transactions
group by card_type
``` | Not sure about your system, but in Oracle CASE expressions are exactly that, so you can nest them:
```
case substring(pan,1,1)
when '3' then case substring(pan,2,1)
when '7' then 'Amex'
else 'Diners'
end
when '4' then 'VISA'
when '5' then 'MasterCard'
else 'unknown'
end
``` | Transact SQL CASE over a variable length input_expression | [
"",
"sql",
"t-sql",
"case",
""
] |
I have a large application that I can build through the command line. I want to specify a flag that enables me to compile it into either one of two modes, Actual or Simulated.
So the main issue is, how can I use the preprocessor to programmatically add a reference?
For example:
```
#if SIMULATED
include SimulatedFiles;
myFactory = new SimulatedFiles.simFactory();
#else
myFactory = new realFactory();
#endif
```
I don't want any simulated files to compiled into my "actual" application. Since there is no "include" directive in C#, I am stuck on how to accomplish this. | You cannot do this via a C# preprocessor statement because the language doesn't support the notion of references via preprocessor macros.
What you can do is use a msbuild file and alter the set of references added based on msbuild parameters. | nant/msbuild and dependency injection tool with xml configuration? | Using C# preprocessor to add reference | [
"",
"c#",
"reference",
"c-preprocessor",
""
] |
> **Possible Duplicate:**
> [C# - How to get Program Files (x86) on Windows Vista 64 bit](https://stackoverflow.com/questions/194157/c-sharp-how-to-get-program-files-x86-on-windows-vista-64-bit)
I realize the odds of a user changing the Windows default of `C:\Program Files` is fairly slim, but stranger things have happened!
How can I get the correct path to `Program Files` from the system? | .NET provides an enumeration of '[special folders](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx)' for Program Files, My Documents, etc.
The code to convert from the enumeration to the actual path looks like this:
```
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
```
<http://msdn.microsoft.com/en-us/library/14tx8hby.aspx> | Just to add to this.
If you're running in 32 bit mode (even on a 64 bit os), SpecialFolder.ProgramFiles and %PROGRAMFILES% will return ..Program Files (x86).
If you specifically need one and/or the other then you'll need to check as follows:
**32** bit system:
`SpecialFolder.ProgramFiles` = ..Program Files\
**64** bit system in **32** bit process:
`SpecialFolder.ProgramFiles` = ..Program Files (x86)\
`Environment.GetEnvironmentVariable("ProgramW6432")` = ..Program Files\
**64** bit system in **64** bit process:
`SpecialFolder.ProgramFiles` = ..Program Files\
`Environment.GetEnvironmentVariable("PROGRAMFILES(X86)")` = ..Program Files (x86)\
Obviously this depends on your locale etc... | How do I programmatically retrieve the actual path to the "Program Files" folder? | [
"",
"c#",
".net",
"windows",
"windows-xp",
"program-files",
""
] |
I know very little about C# or .net but I am interested in learning about them.
One thing that intrigues me is that I keep hearing that "C# 3 is really great".
Why is that? What is the difference from C# 2. Are the differences just in C# or in .net also?
Thanks in advance. | I have a little article about this: the [Bluffer's Guide to C# 3](http://csharpindepth.com/Articles/General/BluffersGuide3.aspx). Obviously there are more details in [my book](https://rads.stackoverflow.com/amzn/click/com/1933988363) but it should be enough to get you going. In short:
* Automatically implemented properties:
```
public int Value { get; set; }
```
* Object and collection initializers:
```
Form form = new Form { Size = new Size(100, 100),
Controls = { new Label { Text = "Hi" } }
};
List<string> strings = new List<string> { "Hi", "There" };
```
* Implicitly typed local variables:
```
var x = new Dictionary<string, int>(); // x is still statically typed
```
* Implicitly typed arrays:
```
DoSomething(new[] { "hi", "there"}); // Creates a string array
```
* Anonymous types:
```
var jon = new { Name = "Jon", Age = 33 };
```
* Lambda expressions (like anonymous methods but shorter):
```
Func<string, int> lengthFunc = x => x.Length;
```
* Expression trees:
```
// Representation of logic as data
Expression<Func<string, int>> lengthExpression = x => x.Length;
```
* Extension methods: (static methods which act like instance methods on the type of their first parameter)
```
public static string Reverse(this string text)
{
char[] chars = text.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
...
string hello = "olleh".Reverse();
```
* Query expressions:
```
var query = from person in people
where person.Age > 18
select person.Name;
``` | You can read all about what was introduced in C# 3.0 in the [Wikipedia article](http://en.wikipedia.org/wiki/C_Sharp_(programming_language)#Features_of_C.23_3.0). | Differences between C# 2 and 3 | [
"",
"c#",
".net",
"c#-3.0",
"c#-2.0",
""
] |
I'm having troubles with fckeditor in Firefox. When the user goes to a page, the html (encoded) is stored in a hidden input element. I call the predefined fckeditor javascript event to populate my editor with the html from the hidden ContentBody element.
```
function FCKeditor_OnComplete( editorInstance )
{
editorInstance.InsertHtml("");
var sample = document.getElementById("ContentBody").value;
editorInstance.InsertHtml(sample);
}
```
This automatically populates the editor with the desired text in IE, but in Firefox it doesn't. Firebug gives me the error :
> A is null [Break on this error] var
> FCKW3CRange=function(A){this.\_Docume...eateFromRange(this.\_Document,this);}};\r\n
Using Firebug I can determine that the event method FCKeditor\_OnComplete() just isn't fired when using Firefox. It is, however, in IE. Any ideas on how to get this to work in both browsers?
The HTML for ContentBody is:
`<input type="hidden" name="ContentBody" id="ContentBody" value="<%=Model.Article%>" />` | I came to a solution to this last month while working on a new project. First I store the encoded HTML string in a hidden input element:
```
<input type="hidden" name="ContentBody" id="ContentBody" value="<%=Model.Body%>" />
```
This function is the event that is called when the FCKeditor instance in finished loading.
```
function FCKeditor_OnComplete(editorInstance)
{
var oEditor = FCKeditorAPI.GetInstance(editorInstance.Name);
var content = parent.document.getElementById("ContentBody").value;
var EditedContent = content.replace(/\u201C/g, '"');
oEditor.InsertHtml(EditedContent);
content = null;
}
```
It seems Firefox requires the javascript to call parent.document.getElementById() | That is interesting. I never used FCKeditorOnComplete (I had to remove underscore to make WMD happy), but it looks like a good hook. Did you try to put a break point this the FCKEditor function below? Do you arrive there with Firefox? Maybe it is something to do with where your FCKeditorOnComplete is physically situated...
```
function WaitForActive( editorInstance, newStatus )
267...{
268 if ( newStatus == FCK_STATUS_ACTIVE )
269 ...{
270 if ( FCKBrowserInfo.IsGecko )
271 FCKTools.RunFunction( window.onresize ) ;
272
273 _AttachFormSubmitToAPI() ;
274
275 FCK.SetStatus( FCK_STATUS_COMPLETE ) ;
276
277 // Call the special "FCKeditor_OnComplete" function that should be present in
278 // the HTML page where the editor is located.
279 if ( typeof( window.parent.FCKeditor_OnComplete ) == 'function' )
280 window.parent.FCKeditor_OnComplete( FCK ) ;
281 }
282}
``` | Hidden Input Elements in Firefox | [
"",
"javascript",
"internet-explorer",
"firefox",
"fckeditor",
""
] |
I have a method in DAL like:
```
public bool GetSomeValue(int? a, int?b, int c)
{
//check a Stored Proc in DB and return true or false based on values of a, b and c
}
```
In this method, I am passing two nullable types, because these values can be null (and checking them as null in DB Stored Proc). I don't want to use magic numbers, so is it ok passing nullables types like this (from performance as well as architecture flexibility perspective)? | I think this is perfectly valid - I prefer nullable types to magic values also. | Since nullable types are part of the Base Class Library and not related to any specific language I find it perfectly valid. The only thing that I try to stay away from in public API's are constructs that are language-specific. | Using nullable types in public APIs | [
"",
"c#",
"design-patterns",
""
] |
I'd like some kind of string comparison function that preserves natural sort order1. Is there anything like this built into Java? I can't find anything in the [String class](http://java.sun.com/javase/6/docs/api/java/lang/String.html), and the [Comparator class](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) only knows of two implementations.
I can roll my own (it's not a very hard problem), but I'd rather not re-invent the wheel if I don't have to.
*In my specific case, I have software version strings that I want to sort. So I want "1.2.10.5" to be considered greater than "1.2.9.1".*
---
1 By "natural" sort order, I mean it compares strings the way a human would compare them, as opposed to "ascii-betical" sort ordering that only makes sense to programmers. In other words, "image9.jpg" is less than "image10.jpg", and "album1set2page9photo1.jpg" is less than "album1set2page10photo5.jpg", and "1.2.9.1" is less than "1.2.10.5" | In java the "natural" order meaning is "lexicographical" order, so there is no implementation in the core like the one you're looking for.
There are open source implementations.
Here's one:
[NaturalOrderComparator.java](https://github.com/paour/natorder)
Make sure you read the:
[Cougaar Open Source License](http://www.cougaar.org)
I hope this helps! | I have tested three Java implementations mentioned here by others and found that their work slightly differently but none as I would expect.
Both [AlphaNumericStringComparator](http://simplesql.tigris.org/servlets/ProjectDocumentList?folderID=0) and [AlphanumComparator](http://www.davekoelle.com/alphanum.html) do not ignore whitespaces so that `pic2` is placed before `pic 1`.
On the other hand [NaturalOrderComparator](http://www.java2s.com/Open-Source/Java-Document/Science/Cougaar12_4/org/cougaar/util/NaturalOrderComparator.java.htm) ignores not only whitespaces but also all leading zeros so that `sig[1]` precedes `sig[0]`.
Regarding performance [AlphaNumericStringComparator](http://simplesql.tigris.org/servlets/ProjectDocumentList?folderID=0) is ~x10 slower then the other two. | Natural sort order string comparison in Java - is one built in? | [
"",
"java",
"algorithm",
"comparator",
"natural-sort",
""
] |
I've just landed a PHP5 gig. I won't be handling the parts of the application that involve super sensitive data, but I still know embarrassingly little about security and encryption methods. I only know the very basics (don't store passwords in plaintext, don't allow users to run code using post data, etc). What do I need to know to keep my applications secure, and where can I learn it? | Learn the difference between hashes and encryption. Encryptions are generally two-way interpretations of a string. I can encrypt my password, and then decrypt it to plaintext again. The idea behind hashes are that they become a one-way 'encryption.'
On my sites I store passwords as hashes. Anytime a user signs on, I re-hash their provided password, test it against the hash stored in the database and approve if they match. I cannot send them their password if they forget it, since (generally) there is no way for me to know.Two different strings can translate into the same hash, which makes it (generally) impossible to find out what the original string was.
This is one issue that is good to get a firm understanding of, and discern when to use encryption vs. hashes. | Know not to write your own encryption functionality. An existing, trusted library is best way to go wherever possible. Avoid cool, bleeding edge technologies that lack many successful programmer-hours and user-hours behind them. Know not to trust the functionality you choose until you've thoroughly tested it yourself, first-person. Keep abreast of new developments which may antiquate your chosen functionality overnight. Know that just because you're using the best encryption technology available today that you've protected nothing if you leave the keys on the table (e.g., cleartext is not in a cache or stored in another table in the same database, private keys not left in the open) | What should every web developer know about encryption? | [
"",
"php",
"encryption",
""
] |
I was wondering if setting an object to null will clean up any eventhandlers that are attached to the objects events...
e.g.
```
Button button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;
button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;
```
etc...
Will this cause a memory leak? | If there are no other references to `button` anywhere, then there is no need to remove the event handler here to avoid a memory leak. Event handlers are one-way references, so removing them is only needed when the object with events is long-lived, and you want to avoid the *handlers* (i.e. objects with handler methods) from living longer than they should. In your example, this isn't the case. | Summary: You need to explicitly unsubscribe when the event source/publisher is long-lived and the subscribers are not. If the event source out-lives the subscribers, all registered subscribers are kept "alive" by the event source (not collected by the GC) unless they unsubscribe (and remove the reference to themselves from the event publisher's notification list)
Also this is a duplicate of
[Is it necessary to explicitly remove event handlers in C#](https://stackoverflow.com/questions/506092/is-it-necessary-to-explicitly-remove-event-handlers-in-c) and has a good title n answer. So voting to close. | C# Explicitly Removing Event Handlers | [
"",
"c#",
"events",
"memory-leaks",
"garbage-collection",
""
] |
I want to read everything from a textfile and echo it. But there might be more lines written to the text-file while I'm reading so I don't want the script to exit when it has reached the end of the file, instead I wan't it to wait forever for more lines. Is this possible in php? | I solved it.
The trick was to use fopen and when eof is reached move the cursor to the previous position and continue reading from there.
```
<?php
$handle = fopen('text.txt', 'r');
$lastpos = 0;
while(true){
if (!feof($handle)){
echo fread($handle,8192);
flush();
$lastpos = ftell($handle);
}else{
fseek($handle,$lastpos);
}
}
?>
```
Still consumes pretty much cpu though, don't know how to solve that. | this is just a guess, but try to pass through (passthru) a "tail -f" output.
but you will need to find a way to flush() your buffer.
---
IMHO a much nicer solution would be to build a ajax site.
read the contents of the file in to an array. store the number of lines in the session. print the content of the file.
start an ajax request every x seconds to a script which checks the file, if the line count is greater then the session count append the result to the page.
---
you could use popen() inststed:
```
$f = popen("tail -f /where/ever/your/file/is 2>&1", 'r');
while(!feof($f)) {
$buffer = fgets($f);
echo "$buffer\n";
flush();
sleep(1);
}
pclose($f)
```
the sleep is important, without it you will have 100% CPU time. | Blocking file-read in php? | [
"",
"php",
"input",
"io",
"filehandle",
""
] |
ok, I start with a very simple method:
```
alert(someText);
```
"someText" is a variable, which users will pass a value in by a form.
Will there a chance that the user pass following text, and inject some code in my Javascript?
For example, can the user pass this in this method:
> "anotherText"); alert("the nextText"
If so, how can I prevent it from happening? if not, can anyone mention some security concern about javascript? | No, it doesn't work that way. String values are not substituted where they are used, they are just used as strings. So there is no security problem.
The only time you may have to worry about this is when you use `eval`:
```
eval("alert(\" + someText + "\");");
```
(Yes, I realize this is a contrived example...) | Basically, as long as you're not calling "eval" (or some function that does), and you're not injecting Javascript created from users directly in to pages (via the script tag), you shouldn't have anything to worry about. | Javascript security problem | [
"",
"javascript",
"security",
"code-injection",
""
] |
I'm a newbie to C++. I'm trying to have a char pointer as an out parameter for a function. But the changes made in the function are not reflected in the main function. What am I doing wrong?
```
void SetName( char *pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
pszStr = pTemp;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pszName = NULL;
SetName( pszName );
cout<<"Name - "<<*pszName<<endl;
delete pszName;
return 0;
}
``` | Your pointer is being copied onto the stack, and you're assigning the stack pointer. You need to pass a pointer-to-pointer if you want to change the pointer:
```
void SetName( char **pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
*pszStr = pTemp; // assign the address of the pointer to this char pointer
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pszName = NULL;
SetName( &pszName ); // pass the address of this pointer so it can change
cout<<"Name - "<<*pszName<<endl;
delete pszName;
return 0;
}
```
That will solve your problem.
---
However, there are other problems here. Firstly, you are dereferencing your pointer before you print. This is incorrect, your pointer is a pointer to an array of characters, so you want to print out the entire array:
```
cout<<"Name - "<<pszName<<endl;
```
What you have now will just print the first character. [Also](https://stackoverflow.com/questions/1217173/how-to-have-a-char-pointer-as-an-out-parameter-for-c-function/1217219#1217219), you need to use `delete []` to delete an array:
```
delete [] pszName;
```
---
Bigger problems, though, are in your design.
That code is C, not C++, and even then it's not standard. Firstly, the function you're looking for is `main`:
```
int main( int argc, char * argv[] )
```
Secondly, you should use [references](https://isocpp.org/wiki/faq/references) instead of pointers:
```
void SetName(char *& pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
pszStr = pTemp; // this works because pxzStr *is* the pointer in main
}
int main( int argc, char * argv[] )
{
char* pszName = NULL;
SetName( pszName ); // pass the pointer into the function, using a reference
cout<<"Name - "<<pszName<<endl;
delete pszName;
return 0;
}
```
Aside from that, it's usually better to just return things if you can:
```
char *SetName(void)
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
return pTemp;
}
int main( int argc, char * argv[] )
{
char* pszName = NULL;
pszName = SetName(); // assign the pointer
cout<<"Name - "<<pszName<<endl;
delete pszName;
return 0;
}
```
There is something that makes this all better. C++ has a [string class](http://en.cppreference.com/w/cpp/string/basic_string):
```
std::string SetName(void)
{
return "Mark";
}
int main( int argc, char * argv[] )
{
std::string name;
name = SetName(); // assign the pointer
cout<<"Name - "<< name<<endl;
// no need to manually delete
return 0;
}
```
If course this can all be simplified, if you want:
```
#include <iostream>
#include <string>
std::string get_name(void)
{
return "Mark";
}
int main(void)
{
std::cout << "Name - " << get_name() << std::endl;
}
```
You should work on your formatting to make things more readable. Spaces inbetween your operators helps:
```
cout<<"Name - "<<pszName<<endl;
cout << "Name - " << pszName << endl;
```
Just like spaces in between English words helps, sodoesspacesbetweenyouroperators. :) | You can also use a reference to a pointer int this case. Also, you may want to be aware of 2 other bugs which are in the original code (see my comments in the code snippet).
```
void SetName( char *& pszStr )
{
char* pTemp = new char[10];
strcpy(pTemp,"Mark");
pszStr = pTemp;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* pszName = NULL;
SetName(pszName);
// Don't need '*' in front of pszName.
cout<< "Name - " << pszName << endl;
// Needs '[]' to delete an array.
delete[] pszName;
return 0;
}
``` | How to have a char pointer as an out parameter for C++ function | [
"",
"c++",
""
] |
How should I use this in .NET 2.0 ...?
```
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
// return only selected type
return (from ce in this.OperatorFields where ce.Type == type select ce).ToList();
}
```
I use this in a 3.5 projects, but now I'm adding new functionality to an old project that I cannot (at this time) upgrade to 3.5.
---
I just did this:
```
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
// return only selected type
//return (from ce in this.OperatorFields where ce.Type == type select ce).ToList();
List<OperatorField> r = new List<OperatorField>();
foreach (OperatorField f in this.OperatorFields)
if (f.Type == type)
r.Add(f);
return r;
}
``` | Can you still use C# 3.0 but not .NET 3.5? If so, keep the code as it is and use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx), which is LINQ to Objects implemented for .NET 2.0.
Otherwise, do this:
```
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<OperatorField> FindByType(String type)
{
List<OperatorField> list = new List<OperatorField>();
foreach (OperatorField ce in OperatorFields)
{
if (ce.Type == type)
{
list.Add(ce);
}
}
return list;
}
``` | Something like this perhaps?
```
IList<OperatorField> col = new List<OperatorField>();
foreach (OperatorField f in this.OperatorFields)
{
if (f.Type == type)
col.Add(f);
}
return col;
``` | Converting LINQ to .NET 2.0 | [
"",
"c#",
"linq",
"c#-2.0",
""
] |
Is it possible to save loop results to a string?
```
$sql = "SELECT SUBSTR(a.`title`, 1,1) FROM articles a WHERE a.`tag` = 'human_resources'";
$results = db_query($sql);
while ($fields = db_fetch_array($results)) {
foreach($fields as $key => $value) {
echo $value;
}
}
```
The code above outputs titles of articles with a tag human\_resources. I want to make an alphabar for a catalog, so I'm using this:
```
if(stripos($string, "A") !== false) {
echo ('<a href="http://www.mysite.com/articles/A">A</a>');
}
else echo '<span class="inactive">A</span>';
if(stripos($string, "B") !== false) {
echo ('<a href="http://www.mysite.com/articles/B">B</a>');
}
else echo '<span class="inactive">B</span>';
...etc
```
But I don't know how to get that $string from the loop for the second part of code.
Any suggestions or better approach to this problem are greatly appreciated. | Change this:
```
echo $value;
```
to this:
```
$string .= $value;
``` | I'm not sure exactly what you want... update your examples to show what you have and what you want the result to be.
You can store a list of values using an `array`:
```
$list = array();
for (...) {
/*
Some code here...
*/
// Add the current string to the list.
$list[] = $string;
}
```
If you just want one long string, you can append:
```
$all = "";
for (...) {
/*
Some code here...
*/
// Add the current string to a string with all the strings concatenated.
$all .= $string;
}
``` | Save loop result to a string | [
"",
"php",
"mysql",
"string",
"alphabetized",
""
] |
how to identify remote machine uniquely in proxy server environment, i have used $\_SERVER['REMOTE\_ADDR'] but all machines in proxy network has same IP Address, is there any way | Don't ever depend on information that is coming from the client. In this case, you're running up against simple networking problems (you can never be sure the client's IP address is correct), in other cases the client may spoof information on purpose.
If you need to uniquely identify your clients, hand them a cookie upon their first visit, that's the best you can do. | Your best bet would be :
```
$uid = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']);
```
however, there's no way to know if they changed their user agent or different browser. | how to identify remote machine uniquely in php? | [
"",
"php",
""
] |
I have a PHP codebase that was written to address our MySQL tables in mixed case. For example, `xar_intakeformgenerator_ChangeLog`.
Our code also runs on windows, and before we knew any better, we imported several databases on to a Windows server. This resulted in Windows MySQL changing all the table names to lower case. (`xar_intakeformgenerator_changelog`). We now know how to prevent that from happening to new databases. (`Set lower_case_table_names`) And, the code runs fine on the Windows servers because MySQL just doesn't care about the case of the tables on Windows.
Here's the problem. The Windows server is giving us grief and we need to move all of the databases off to a Linux server. Because all of the table names have converted to lower case, the code will NOT work on Linux. Luckily, Xaraya creates table mappings. So, in theory, I could set up a new code base for these databases and change the mappings of every module to use the lower case tables. Or, we could manually change the table names after we import them onto the Linux machine to get the table case correct.
changing `lower_case_table_names` does not correct the databases that were mangled before the flag was set. These all have the lower case table names.
I'm not wild about either option. Does anybody know an ingenious way to handle this? | OK. I found my answer.
On the Linux server, I needed to run the following to change all the table names in my Linux generated databases to lower case:
1. How to produce a SQL script that renames all tables in a schema to its lower case form:
```
select concat('rename table ', table_name, ' to ' , lower(table_name) , ';')
from information_schema.tables where table_schema = 'your_schema_name';
```
2. Renamed the databases in `phpmyadmin` to lowercase names.
3. Modified the `my.cnf` on the Linux server to use `lower_case_table_names=1`
4. Restarted mysql.
After this, my code would work with the lower case table names. So, I was able to import the Windows ones and have the same code base work on both. | If I remember correctly *(had the same kind of problem a while back -- but I stopped working on that project before we decided which solution to adopt...)*, there is a configuration option which says how tablenames should be used (case-sensitive or not case-sensitive).
Here's what I found : [Identifier Case Sensitivity](http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html)
Quoting that page :
> If you are using MySQL on only one
> platform, you do not normally have to
> change the `lower_case_table_names`
> variable from its default value.
> However, you may encounter
> difficulties if you want to transfer
> tables between platforms that differ
> in file system case sensitivity. For
> example, on Unix, you can have two
> different tables named `my_table` and
> `MY_TABLE`, but on Windows these two
> names are considered identical. To
> avoid data transfer problems arising
> from lettercase of database or table
> names, you have two options:
>
> * Use `lower_case_table_names=1` on all systems. The main disadvantage with
> this is that when you use `SHOW TABLES`
> or `SHOW DATABASES`, you do not see the
> names in their original lettercase.
>
> + Use `lower_case_table_names=0` on Unix and `lower_case_table_names=2` on
> Windows. This preserves the lettercase
> of database and table names.
*(There is more I didn't copy-paste ; so going to read that page might be a good idea ;-) )*
Hope this will help... | MySQL Case Sensitive Tables Conversion | [
"",
"php",
"mysql",
"windows",
"linux",
""
] |
Starting with pthreads, I cannot understand what is the business with pthread\_key\_t and pthread\_once\_t?
Would someone explain in simple terms with examples, if possible?
thanks | No, it can't be explained in layman terms. Laymen cannot successfully program with pthreads in C++. It takes a specialist known as a "computer programmer" :-)
`pthread_once_t` is a little bit of storage which `pthread_once` must access in order to ensure that it does what it says on the tin. Each once control will allow an init routine to be called once, and once only, no matter how many times it is called from how many threads, possibly concurrently. Normally you use a different once control for each object you're planning to initialise on demand in a thread-safe way. You can think of it in effect as an integer which is accessed atomically as a flag whether a thread has been selected to do the init. But since `pthread_once` is blocking, I guess there's allowed to be a bit more to it than that if the implementation can cram in a synchronisation primitive too (the only time I ever implemented `pthread_once`, I couldn't, so the once control took any of 3 states (start, initialising, finished). But then I couldn't change the kernel. Unusual situation).
`pthread_key_t` is like an index for accessing thread-local storage. You can think of each thread as having a map from keys to values. When you add a new entry to TLS, `pthread_key_create` chooses a key for it and writes that key into the location you specify. You then use that key from any thread, whenever you want to set or retrieve the value of that TLS item for the current thread. The reason TLS gives you a key instead of letting you choose one, is so that unrelated libraries can use TLS, without having to co-operate to avoid both using the same value and trashing each others' TLS data. The pthread library might for example keep a global counter, and assign key 0 for the first time `pthread_key_create` is called, 1 for the second, and so on. | `pthread_key_t` is for creating thread [thread-local storage](http://en.wikipedia.org/wiki/Thread-local_storage): each thread gets its own copy of a data variable, instead of all threads sharing a global (or function-static, class-static) variable. The TLS is indexed by a key. See [`pthread_getspecific`](https://computing.llnl.gov/tutorials/pthreads/man/pthread_getspecific.txt) et al for more details.
`pthread_once_t` is a control for executing a function only once with [`pthread_once`](https://computing.llnl.gov/tutorials/pthreads/man/pthread_once.txt). Suppose you have to call an initialization routine, but you must only call that routine once. Furthermore, the point at which you must call it is after you've already started up multiple threads. One way to do this would be to use `pthread_once()`, which guarantees that your routine will only be called once, no matter how many threads try to call it at once, so long as you use the same control variable in each call. It's often easier to use `pthread_once()` than it is to use other alternatives. | pthread_key_t and pthread_once_t? | [
"",
"c++",
"pthreads",
"unix",
""
] |
Is there a simple way to send out email notifications in Maven for each build without outside CI tools, just like Ant? | If CI is not an option I would use a simple script wrapper:
```
mvn install 2>&1 | tee build.log && cat build.log | mail -s 'Maven build output' user@example.com && rm -f build.log
```
---
If you do decide to use a CI tool, I would strongly recommend Hudson. The [installation page](http://wiki.hudson-ci.org/display/HUDSON/Installation+and+Execution) shows how easy it is to run. *Continuous integration server* sounds pompous and enterprisey, but Hudson is dead-simple. | I'd strongly recommend using a CI tool to manage this for you, I personally like to configure which emails are to be sent on the build to avoid spamming. For example only notify when the build starts failing, or starts working again, not on every failure.
If you're sure this is the right approach, you can use the [maven-changes-plugin](http://maven.apache.org/plugins/maven-changes-plugin/index.html) to send an email on each build. You can [customise the mail template with velocity](http://maven.apache.org/plugins/maven-changes-plugin/examples/using-a-custom-announcement-template.html), and bind the execution of the goals to an appropriate phase so it is sent when you want it.
I'd also put the configuration in a profile so it is sent when you want it to be (i.e. when the profile is active).
The configuration looks something like this:
```
<profiles>
<profile>
<id>notify</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-changes-plugin</artifactId>
<executions>
<execution>
<!--send an email in the install phase,
could be changed depending on your needs-->
<phase>install</phase>
<goals>
<goal>announcement-mail</goal>
</goals>
</execution>
</executions>
<configuration>
<smtpHost>mail.yourhost.com</smtpHost>
<smtpPort implementation="java.lang.Integer">25</smtpPort>
<toAddresses>
<toAddress implementation="java.lang.String">
someones@email.com</toAddress>
<toAddress implementation="java.lang.String">
someoneelse@email.com</toAddress>
</toAddresses>
<!--using a custom velocity template in
src/main/resources/mailTemplate/announcement.vm -->
<template>announcement.vm</template>
<templateDirectory>mailTemplate</templateDirectory>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
``` | How to send out email notification for Maven build | [
"",
"java",
"maven-2",
"build",
"notifications",
""
] |
I have a site that lists movies. Naturally people make spelling mistakes when searching for movies, and of course there is the fact that some movies have apostrophes, use letters to spell out numbers in the title, etc.
How do I get my search script to overlook these errors? Probably need something that's a little more intelligent than `WHERE mov_title LIKE '%keyword%'`.
It was suggested that I use a fulltext search engine, but all of those things look really complicated, and I feel that building them into my application will be like hell on earth. If I do have to use one, what's the least invasive one, that will be most painless to implement into existing code? | I think you'll have to implement an external fulltext search engine. MySQL just isn't good at fulltext search. I'd say you should give [Lucene](http://lucene.apache.org/java/docs/) a go ([tutorials](http://www.lucenetutorial.com/)). [Zend Framework has an API](http://framework.zend.com/manual/en/zend.search.lucene.html) that plugs into Lucene, making it easier to learn and utilize. | Presuming that you use MySQL - MySQL has no in-built functionality that is capable of doing this.
This means you will have to implement a full-text search yourself, or use a third party full text search tool.
* If you implement it yourself, you should look into the [metaphone](http://en.wikipedia.org/wiki/Metaphone) or [double metaphone](http://en.wikipedia.org/wiki/Double_Metaphone) algorithms (I'd recommend them over soundex, which is not nearly as good at this type of task), to store phoenetic representations of all your words. However, building your own full text search is no task for the faint-hearted. Don't attempt it if you don't consider yourself a database wizard.
* If you want a third party tool, [Lucene](http://lucene.apache.org/java/docs/) is the way to go. It is ported into tons of different languages/platforms [including PHP](http://framework.zend.com/manual/en/zend.search.lucene.html) - you don't have to use Java. | What's the best way to implement typo correction into a search in php/mysql? | [
"",
"php",
"mysql",
"search",
"full-text-search",
""
] |
What I want to accomplish is a tool that filters my files replacing the occurrences of strings in this format `${some.property}` with a value got from a properties file (just like Maven's or Ant's file filtering feature).
My first approach was to use Ant API (copy-task) or Maven Filtering component but both include many unnecessary dependencies and my program should be lightweight. After, I searched a little in Apache Common haven't found anything yet.
Is there an efficient (and elegant) solution to my problem? | The most efficient solution is using a templating engine. There are few, widely used engines, that comes in a single jar :
* [freemarker](http://freemarker.org/index.html)
* [apache velocity](http://velocity.apache.org/)
* stringtemplate (from antlr) | If this is configuration related, I would recommend [Apache Commons Configuration](http://commons.apache.org/configuration/). It will do varaible replacement on the fly.
It has other nice features, like handling XML, properties, Apple's pList formats. | What is the most efficient way to replace many string tokens in many files in Java? | [
"",
"java",
"algorithm",
"performance",
"replace",
""
] |
I need to (un)zip some files and after some googling I haven't found any utility for doing it. I know I can do it with built-in java.uitl.zip.\* classes but isn't there any utility, that will make it easer, best like this:
SomeClass.unzip("file\_name.zip", "target\_directory");
or
SomeClass.zip("source\_directory", "target\_file\_name.zip", recursively);
I don't want to handle streams. Just file, or better just file names... | How about the [Deflater/Inflater](http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/Deflater.html) classes mentioned in the question "[What’s a good compression library for Java?](https://stackoverflow.com/questions/127001/whats-a-good-compression-library-for-java)".
I know the current interfaces proposed by Java are Stream-based, not "filename"-based, but according to the following article on [Java compression](http://www.j2ee.me/developer/technicalArticles/Programming/compression/), it is easy enough to build an utility class around that:
For instance, a Unzip function based on a filename would look like:
```
import java.io.*;
import java.util.zip.*;
public class UnZip {
final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedOutputStream dest = null;
FileInputStream fis = new
FileInputStream(argv[0]);
ZipInputStream zis = new
ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " +entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
FileOutputStream fos = new
FileOutputStream(entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
``` | Maybe [Compress from Apache Commons](http://commons.apache.org/compress/) could help you. | Is there any java compression utility | [
"",
"java",
"compression",
""
] |
I wanted to know if it was possible to keep the Session variable thought builds in a ASP.NET + C#?
I ask this because every time I make a minor change to my application and need to rebuild it, I need to login again and do a nunch of operation after that... it's taking a lot of my time.
If there is no way around I can set up a testing mode where I'll always be logged in, or automatize the log in procedure... but it would save me time to just keep the Session after a build. | **This answer is community wiki so as not to generate any reputation, as it's effectively a reworking of DOK's answer. If you like it, please upvote DOK's answer.**
@Dok, if you want to edit your answer to incorporate any of this, please do, and I'll gladly delete this answer. :)
DOK, as mentioned in my comments to your answer (and possibly some help for your own solution), you might want to do the following:
```
#if DEBUG //As mentioned by DOK in the comments. If you set debug to false when building for deployment, the code in here will not be compiled.
protected void Page_PreInit(object sender, EventArgs e)
{
bool inDevMode = false;
inDevMode = bool.Parse(ConfigurationManager.AppSettings["InDevMode"]); //Or you could use TryParse
if(inDevMode)
{
// Fake authentication so I don't have to create a damn Login page just for this.
System.Web.Security.FormsIdentity id = new FormsIdentity(new FormsAuthenticationTicket("dok", false, 30));
string[] roles = { "a" };
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
#endif
```
To further ensure that you do not accidentally deploy with this active, then you would have your app settings in seperate config files (as well as your debug section). If you use [Web Deployment](http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en) projects, then you can put your dev config settings in one file, and your live config files in another (this is usually dev.config and live.config!).
eg, in your web.config:
```
<appSettings file="dev.config"/>
```
In your dev.config:
```
<appSettings>
<add key="InDevMode" value="true" />
</appSettings>
```
In your live.config:
```
<appSettings>
<add key="InDevMode" value="false" />
</appSettings>
``` | You could change your test server to use the [State Server or SQL Server session state modes](http://msdn.microsoft.com/en-us/library/ms178586.aspx), which will survive an application restart. | Keep the Session[] variable after a new build | [
"",
"c#",
"asp.net",
"session-variables",
""
] |
This is probably a very stupid question for SQL stalwarts, but I just want one SQL command.
Details,
I am using a data analysis tool called R, this tool uses ODBC to read data from XLS. I am now trying to read data from an XLS file. The ODBC tool in R accepts SQL commands.
Question,
Can someone give me an SQL command that will read data from an XLS file's
- Specified sheet
- Specified column [by name]
- Specified row [Specified just by Row Index]
Thanks ... | Once you have set the connection to the file, you can use following statement:
```
select [columnname] from [sheetname$] where [columnname] = 'somevalue'
```
Not sure about the row index thing. But you can make use of where clause if each row in the file has serial number or any such unique value. | With the query below you can read the data from row 61 of cloumn A, & G is supposed to read all columns till G.
```
SELECT * FROM [Sheet1$a61:G]
``` | sql command for reading a particular sheet, column | [
"",
"sql",
"excel",
"r",
"sqlcommand",
"import-from-excel",
""
] |
I'm trying to add FB xmlns attribute to the document's `<html>` tag (`<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">`) dynamically. For some reason adding it like below does not work:
```
htmltag = document.getElementsByTagName ('html');
htmltag[0].setAttribute("xmlns:fb","http://www.facebook.com/2008/fbml");");
```
How can I do it?
Thanks!
Update: No jquery or other lib is available. | This probably isn't the answer you're wanting :)
Tacking on semantic markup with client-side code is not good practice. It hides the valuable machine-readable info from most machines. The HTML is already fetched, parsed and displayed by the time Javascript executes\*. A dollar short and a day late!
If you can add the attributes on the server, before it is sent to the browser, go for it.
If you *have* to do it client-side; don't be tempted by a framework like jQuery or whatever. That's a huge overhead for a small task.
\*non-scientific tests | Heh actually, after doing the jquery solution I stated above;
I realized it could be done easier with a single javascript line:
```
document.documentElement.setAttribute("xmlns:fb", "http://www.facebook.com/2008/fbml");
```
Keep in mind ... If you view the source with the browser, you will not see the attribute attached, as it programatically adds it after the page loads. Use Firebug in firefox, or something that lets you see the source being manipulated on the fly, and you should be good to go. | Javascript: Adding attribute dynamically to the <html /> tag | [
"",
"javascript",
"html",
"facebook",
""
] |
This code selects cell values in MySQL and manually adds them to PHP variables:
```
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
```
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables? | I think this is what you're looking for
```
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
``` | You could use [extract()](http://uk.php.net/manual/en/function.extract.php) for that. But I'd keep the values in the array.
```
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
``` | How to put MySQL cell values into variables named after column names in PHP | [
"",
"php",
"mysql",
""
] |
Can anyone point me to some info on Disjoint sets as linked list? I cant find any code on this.
Language C++ | Well I think you can find information in this page of [Wikipedia](http://en.wikipedia.org/wiki/Disjoint-set_data_structure). Of course, that information is written in pseudo-code, but is not difficult to translate it. | I just wrote this, if anyone is still interested. I was implementing CLRS Chap 21.1
```
/******************************************************************
* PROGRAM: Implementation of Linked-list representation of disjoi-*
* nted sets in C++ without weighted union optimization. *
* makeset, find takes O(1), Union takes O(n). Testing *
* code is in the main method. *
* AUTHOR: Bo Tian (bt288 at cam.ac.uk) drop me an email if you *
* have any questions. *
* LICENSE: Creative Commons Attribution 3.0 Unported *
* http://creativecommons.org/licenses/by/3.0/ *
*******************************************************************/
#include <iostream>
using namespace std;
long NodeAddress[10] = {0};
int n=0;
template<class T> class ListSet {
private:
struct Item;
struct node {
T val;
node *next;
Item *itemPtr;
};
struct Item {
node *hd, *tl;
};
public:
ListSet() { }
long makeset(T a);
long find (long a);
void Union (long s1, long s2);
};
template<class T> long ListSet<T>::makeset (T a) {
Item *newSet = new Item;
newSet->hd = new node;
newSet->tl = newSet->hd;
node *shd = newSet->hd;
NodeAddress[n++] = (long) shd;
shd->val = a;
shd->itemPtr = newSet;
shd->next = 0;
return (long) newSet;
}
template<class T> long ListSet<T>::find (long a) {
node *ptr = (node*)a;
return (long)(ptr->itemPtr);
}
template<class T> void ListSet<T>::Union (long s1, long s2) {
//change head pointers in Set s2
Item *set2 = (Item*) s2;
node *cur = set2->hd;
Item *set1 = (Item*) s1;
while (cur != 0) {
cur->itemPtr = set1;
cur = cur->next;
}
//join the tail of the set to head of the input set
(set1->tl)->next = set2->hd;
set1->tl = set2->tl;
delete set2;
}
int main () {
ListSet<char> a;
long s1, s2, s3, s4;
s1 = a.makeset('a');
s2 = a.makeset('b');
s3 = a.makeset('c');
s4 = a.makeset('d');
cout<<s1<<' '<<s2<<' '<<s3<<' '<<s4<<endl;
cout<<a.find(NodeAddress[2])<<endl;
a.Union(s1, s3);
cout<<a.find(NodeAddress[2])<<endl;
}
``` | Disjoint set as linked list | [
"",
"c++",
"disjoint-sets",
""
] |
Is there a straight forward way to do it?
I'm stuck here:
```
#include <iostream>
#include <vector>
#include <cstdlib>
using std::size_t;
using std::vector;
int main()
{
vector<vector<int> > Matrix;
//Create the 2x2 matrix.
size_t rows = 2;
size_t cols = 2;
// 1: set the number of rows.
Matrix.resize(rows);
for(size_t i = 0; i < rows; ++i)
{
Matrix[i].resize(cols);
}
// Create Matrix
Matrix[0][0] = 1;
Matrix[0][1] = 2;
Matrix[1][0] = 3;
Matrix[1][1] = 4;
// Create Vector to store sum
vector <int> ColSum;
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
// I'm stuck here
}
}
return 0;
}
```
Given the matrix above:
```
1 2
3 4
```
In the end we hope to print the result of a vector
(that keeps the sum of each column):
```
4 6
```
Note that the matrix can be of any dimension. | ```
for( size_t row = 0; row < Matrix.size(); row++ )
{
ColSum[row] = 0;
for( size_t column = 0; column < Matrix[row].size(); column++ )
{
ColSum[row] += Matrix[row][column];
}
}
``` | ```
// Create Vector to store sum
vector <int> ColSum;
ColSum.Resize(cols);
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
ColSum[j] += Matrix[i][j];
}
}
``` | How to Sum Column of a Matrix and Store it in a Vector in C++ | [
"",
"c++",
"matrix",
"column-sum",
""
] |
I need to make a horizontal "breaking-news" style bar with jQuery. I pick new from the server (the easy part) and I need some way to make them continually scroll from left to right. Any jQuery plugin to help me? thanks | 1. jScroller
[Demo](http://jscroller.markusbordihn.de/example/left/)
[Download](http://jscroller.markusbordihn.de/)
2. Silky smooth marquee:
[Demo](http://remysharp.com/demo/marquee.html)
[Download](http://remysharp.com/2008/09/10/the-silky-smooth-marquee/) | Good gods, there is a plugin at jQuery site to make BBC style scrolling news ticker check it [here](http://plugins.jquery.com/project/BBCnewsTicker).
[Here](http://woork.blogspot.com/2008/07/news-ticker-with-horizontal-scroller.html) is an article about making a horizontal scrolling news ticker
An article on [texotela](http://www.texotela.co.uk/code/jquery/newsticker/) discuss news ticker and ajax. | News Bar with jQuery | [
"",
"javascript",
"jquery",
""
] |
I need a good config file format. I plan on putting to table schema. Like symfony, ruby on rails, etc. What is the best file format for configuration file ? Yaml or XML or JSON encoded file ? Which is the best for this purpose ? | As others have stated, you have loads of options. Just don't invent (i.e. write parsers) such a thing yourself unless you have a really, really good reason to do so (can't think of any). Just evaluate your options:
* Do you need to access this data anywhere outside my application (with another language)
* Do you want users (or yourself) to be able to edit the file using a simple text editor
* Do you need backwards compatibility with older versions of the used language
For example, PHP provides very easy serialize() and unserialize() functions. The format, however, is not as easily readable / editable by humans (XML can also be hard to read, but not as hard as the PHP format. Python's pickle module is even worse.). If you ever need to access data with other languages, this is a bad choice. And think about others - I recently hat to parse PHP serialized data from the Horde project in a python project of mine! JSON is a much better choice because its human-readable (if its "pretty-printed", not in the compacted form!), human-editable and every major language has JSON-support nowadays. However, you will lose backwards compatibility, e.g. with python, JSON requires version 2.6+. | `*.ini` should be pretty good for that
```
[MyApp]
var1 = "foo"
var2 = "bar"
[MyPlugin]
var1 = "qwe"
```
You can easily read it using `parse_ini_file()`
```
$config = parse_ini_file('/path/to/config/file', true);
echo $config['MyApp']['var2'];
``` | What is the best file format for configuration file? | [
"",
"php",
""
] |
If I need pagination support, should I use a ListView or a Repeater ?
I can use a DataPager control with a ListView, but not with a Repeater.
So what would be the best option ? and why ? | I haven't compared performance of the various data visualization controls since the .NET 1.1 days. But if you are planning on using one of these controls on a very large set of data, then it's something to look out for.
Repeaters have the simplest, most stripped-down functionality and won't add anything to your markup that you don't specifically tell it to. And if you feed it a datareader as its datasource then that can be the most performant combination possible (albeit the most devoid of features).
I guess that doesn't answer your question exactly, but raises more questions.
But... is it worth the effort to create custom paging, or use built-in functionality of a listview/datapager combination? At times, I think it is worth it to go custom.
**One thing to worry about is that the DataPager control uses postbacks when navigating between pages.**
IMO, postbacks are a crappy way to handle paging. Here's why:
1.) The user can't navigate between pages with the back & forward buttons in their browser history without getting the annoying message about resubmitting your form data.
2.) Search engines can't index each page of results individually because they all use the same URL.
At least with a custom solution you could resolve all of that by using querystrings for each page.
I talk about some of these same issues in my answer to [this question](https://stackoverflow.com/questions/1113498/how-to-create-seo-friendly-paging-in-digg-com-style-using-asp-net-2-0c/1145683#1145683). | imho ListView is in general better, because you can customize it a lot better. | If I need pagination support, should I use a ListView or a Repeater? | [
"",
"c#",
".net",
"asp.net",
""
] |
I've got an array, indexed by keys, eg:
```
array(
'key1' => 'value1',
'key2' => 'value2',
...
'key57' => 'value57'
)
```
How to "filter" that array, in order to only have, for example:
```
array(
'key2' => 'value2',
'key57' => 'value57'
)
```
and preserve keys.
I know array\_filter() function, but I do NOT want to EXCLUDE all items except 2 and 57, no I just want to KEEP these values.
Is there exist a PHP core function we could name array\_keep() or something ?
Thanks. | If you know exactly which keys you want to keep, you could easily write a function to do that:
```
<?php
function array_keep($array, $keys) {
return array_intersect_key($array, array_fill_keys($keys, null));
}
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key57' => 'value57'
);
$newArray = array_keep($array, array('key2', 'key57'));
print_r($newArray);
```
Output:
```
Array
(
[key2] => value2
[key57] => value57
)
``` | An alternative to Tom's function:
```
$keptValues = array_intersect_key($array, array_flip(array($key1, $key2)));
```
Or, with less magic but more verbose:
```
$keptValues = array_intersect_key($array, array($key1 => null, $key2 => null));
``` | Opposite of array_filter to keep certain values and preserving keys | [
"",
"php",
"arrays",
""
] |
I currently have a table with a column as `varchar`. This column can hold numbers or text. During certain queries I treat it as a `bigint` column (I do a join between it and a column in another table that is `bigint`)
As long as there were only numbers in this field had no trouble but the minute even one row had text and not numbers in this field I got a "Error converting data type `varchar` to `bigint`." error even if in the WHERE part I made sure none of the text fields came up.
To solve this I created a view as follows:
```
SELECT TOP (100) PERCENT ID, CAST(MyCol AS bigint) AS MyCol
FROM MyTable
WHERE (isnumeric(MyCol) = 1)
```
But even though the view shows only the rows with numeric values and casts Mycol to bigint I still get a *Error converting data type varchar to bigint* when running the following query:
```
SELECT * FROM MyView where mycol=1
```
When doing queries against the view it shouldn't know what is going on behind it! it should simply see two bigint fields! ([see attached image](http://www.getprice.com.au/view.gif), even mssql management studio shows the view fields as being bigint) | OK. I finally created a view that works:
```
SELECT TOP (100) PERCENT id, CAST(CASE WHEN IsNumeric(MyCol) = 1 THEN MyCol ELSE NULL END AS bigint) AS MyCol
FROM dbo.MyTable
WHERE (MyCol NOT LIKE '%[^0-9]%')
```
Thanks to **AdaTheDev** and **CodeByMoonlight**. I used your two answers to get to this. (Thanks to the other repliers too of course)
Now when I do joins with other bigint cols or do something like 'SELECT \* FROM MyView where mycol=1' it returns the correct result with no errors. My guess is that the CAST in the query itself causes the query optimizer to not look at the original table as Christian Hayter said may be going on with the other views | Ideally, you want to try to avoid storing the data in this form - would be worth splitting the BIGINT data out in to a separate column for both performance and ease of querying.
However, you can do a JOIN like this example. Note, I'm **not using ISNUMERIC()** to determine if it's a valid BIGINT because that would validate incorrect values which would cause a conversion error (e.g. decimal numbers).
```
DECLARE @MyTable TABLE (MyCol VARCHAR(20))
DECLARE @OtherTable TABLE (Id BIGINT)
INSERT @MyTable VALUES ('1')
INSERT @MyTable VALUES ('Text')
INSERT @MyTable VALUES ('1 and some text')
INSERT @MyTable VALUES ('1.34')
INSERT @MyTable VALUES ('2')
INSERT @OtherTable VALUES (1)
INSERT @OtherTable VALUES (2)
INSERT @OtherTable VALUES (3)
SELECT *
FROM @MyTable m
JOIN @OtherTable o ON CAST(m.MyCol AS BIGINT) = o.Id
WHERE m.MyCol NOT LIKE '%[^0-9]%'
```
**Update:**
The only way I can find to get it to work for having a WHERE clause for a specific integer value without doing another CAST() on the supposedly bigint column in the where clause too, is to use a user defined function:
```
CREATE FUNCTION [dbo].[fnBigIntRecordsOnly]()
RETURNS @Results TABLE (BigIntCol BIGINT)
AS
BEGIN
INSERT @Results
SELECT CAST(MyCol AS BIGINT)
FROM MyTable
WHERE MyCol NOT LIKE '%[^0-9]%'
RETURN
END
SELECT * FROM [dbo].[fnBigIntRecordsOnly]() WHERE BigIntCol = 1
```
I don't really think this is a great idea performance wise, but it's a solution | Error converting data type varchar | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I made a little search-function with javascript to look for a string in a table:
There are "tr"s that simply contain a number as an id and there are "tr"s that contain "childNode+idOfParentNode" as an id (e.g.:
```
<tr id="1"> ... </tr>
<tr id="childNode1"> ... </tr>
```
Now I want to look through the table, see if a giving string or part of it matches the content of the parent-"tr". If that is not the case I want the parent-"tr" and its childNode-"tr"s to be hidden (or collapsed). And I want them being shown if the string or part of it matches. Here is my function:
```
// inputFieldId := Id of the inputField that contains the search-String
// tableId := Id of the table to be searched
function searchTable( inputFieldId, tableId ){
var inputField = document.getElementById( inputFieldId );
var input = inputField.value.toUpperCase();
var countRows = jQuery( '#' + tableId + ' tr' ).length;
jQuery('#loader').css( "visibility", "visible" );
var hideChildren = false;
var childId = -1;
var parentId = -1;
for( var i = 1; i <= countRows; i++ ){
var trsId = jQuery('#' + tableId + ' tr:nth-child('+i+')' ).attr('id');
// I am only looking for <tr> that are not "childnodes"
if( trsId.indexOf( "childNode") == -1 ){
var firstTd = jQuery('#' + tableId + ' tr:nth-child('+i+') td:nth-child(1)' );
var firstTdValue = firstTd.text();
if( firstTdValue.indexOf( input ) == -1 ){
hideChildren = true;
childId = trsId;
parentId = i;
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).children('td').css("visibility", "collapse");
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).css("visibility", "collapse");
}
else{
hideChildren = false;
childId = trsId;
parentId = i;
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).children('td').css("visibility", "visible");
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).css("visibility", "visible");
}
}
else{
childNodeId = "childNode"+childId;
if( hideChildren && trsId == childNodeId && parentId > -1 ){
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).children('td').css("visibility", "collapse");
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).css("visibility", "collapse");
}
else{
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).children('td').css("visibility", "visible");
jQuery('#' + tableId + ' tr:nth-child('+i+')' ).css("visibility", "visible");
}
}
}
jQuery('#loader').css( "visibility", "hidden" );
}
```
Seriously, this works fine, but it takes FOREVER!!! especially if it is a larger table, so I was wondering if someone saw a way to make my function faster and more efficient.
Thnx in advance :)
=========================================================================
EDIT: I made it work ... it now looks like this and works wonderfully :)
```
function searchTable( inputFieldId, tableId ){
jQuery('#loader').show();
var input = jQuery('#'+inputFieldId).val().toUpperCase();
var parentId = -1
jQuery('#' + tableId + ' tr').each( function(i) {
var thiss = jQuery(this);
var showP = false;
var showC = false;
if (thiss.attr('id').indexOf('child') < 0) { // parent
parentId = thiss.attr('id');
showP = !(thiss.find('td:first').text().indexOf( input ) < 0);
thiss.toggle( showP );
}
else{ // childNode
var childId = "childNode"+parentId;
var parent = jQuery('#'+tableId+' tr#'+parentId+':visible').length;
showC = !(thiss.attr('id') == childId && parent < 1);
thiss.toggle( showC );
}
});
jQuery('#loader').css( "visibility", "hidden" );
}
```
Thank you :) | It would be easier if the parents (and children) had classes identifying them as such, but you can get by with the ids if need be. I'm using $ instead of jQuery, but you can change that back if you need to.
```
// inputFieldId := Id of the inputField that contains the search-String
// tableId := Id of the table to be searched
function searchTable( inputFieldId, tableId ){
var input = $('#' + inputFieldId).text().ToUpperCase();
$('#loader').show();
$('#' + tableId + ' tr').each( function(i) {
var $this = $(this);
var show = false;
// if ($this.hasClass('parent')) { // would be nice
if ($this.attr('id').indexOf('child') < 0) { // parent
// note that text() here is the combined texts of all tds
// adjust with :first if you really want to check only the first
show = !($this.find('td').text().indexOf( input ) < 0);
}
$this.toggle( show );
});
$('#loader').hide();
}
``` | 1) Cache the selector that you create multiple times. Then use the variable from then on in.
```
var $rows = jQuery('#' + tableId + ' tr:nth-child('+i+')' );
$rows.children()...
```
2) to get direct children you can use '>' in your selector
```
var $rows = jQuery('#' + tableId + '>tr:nth-child('+i+')' );
``` | Making Javascript-search-function fast | [
"",
"javascript",
"jquery",
"search",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.