Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats?
I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger project that I'm working on).
There is already an awesome open-source project for managing ebook libraries : [Calibre](http://calibre.kovidgoyal.net/). I wanted to try implementing this on my own as a learning/self-teaching exercise. I started looking at their [python source code](http://bazaar.launchpad.net/~kovid/calibre/trunk/files/head%3A/src/calibre/ebooks/mobi/) and realized that I have no idea what is going on. Of course, the big danger in being self-taught at anything is not knowing what you don't know.
In this case, I know that I don't know much about these binary files and how to work with them in python code ([struct](http://www.python.org/doc/2.6/library/struct.html#module-struct)?). But I think I'm probably missing a lot of knowledge about binary files in general and I'd like some help understanding how to work with them. [Here is a detailed overview](http://wiki.mobileread.com/wiki/MOBI) of the mobi/palmdoc headers. Thanks!
Edit: No question, good point! Do you have any tips on how to gain a basic knowledge of working with binary files? Python-specific would be helpful but other approaches could also be useful.
TOM:Edited as question, added intro / better title | You should probably start with the [struct](http://docs.python.org/library/struct.html) module, as you pointed to in your question, and of course, open the file as a binary.
Basically you just start at the beginning of the file and pick it apart piece by piece. It's a hassle, but not a huge problem. If the files are compressed or encrypted, things can get more difficult. It's helpful if you start with a file that you know the contents of so you're not guessing all the time.
Try it a bit, and maybe you'll evolve more specific questions. | If you want to construct and analyse binary files the struct module will give you the basic tools, but it isn't very friendly, especially if you want to look at things that aren't a whole number of bytes.
There are a few modules that can help, such as [BitVector](http://pypi.python.org/pypi/BitVector), [bitarray](http://pypi.python.org/pypi/bitarray/) and [bitstring](http://code.google.com/p/python-bitstring/). (I favour [bitstring](http://code.google.com/p/python-bitstring/), but I wrote it and so may be biased).
For parsing binary formats the [hachoir](http://hachoir.org/) module is very good, but I suspect it's too high-level for your current needs. | Binary file IO in python, where to start? | [
"",
"python",
"binary",
"io",
"epub",
"mobipocket",
""
] |
I have a .dll that was provided, and I need to interface with it using java.
Do I have to rewrite the C to use the JNI types provided in jni.h? as seen in java sun's jni example.
Otherwise, How do i declare the native function my java function to pass and receive pointers?
thanks | You may find [JNA](https://github.com/twall/jna/) useful
"JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation." | In a way, yes.
Most of the time you would just write a small "wrapper" dll with functions that would do the type conversions and delegate to the corresponding functions in the "real" DLL. | Java Native Interface with any arbitrary C code | [
"",
"java",
"c",
"java-native-interface",
""
] |
I'm using the following list comprehension:
```
resources = [obj.get("file") for obj in iterator if obj.get("file") != None]
```
Is there a way to "cache" the value of `obj.get("file")` when it's checked in the if statement so that it doesn't have to call `get` again on obj when it generates the return list? | If you want to stay with list / iterator comprehensions instead of using `filter` you can simply use:
```
resources = [file_obj
for file_obj in (obj.get("file") for obj in iterator)
if file_obj is not None]
``` | ```
resources = filter(None, (obj.get("file") for obj in iterator))
```
See the documentation for [filter](http://docs.python.org/library/functions.html#filter) for how to provide your own evaluation function. Passing `None` for the function (as above) filters out all values which aren't true.
If obj.get() returns an object which has a weird `__nonzero__` method then you'd need to pass `lambda obj: obj != None` to get exactly the same result as your original code. | Caching values in Python list comprehensions | [
"",
"python",
"list-comprehension",
""
] |
For a given set of text files, I need to find every "`\`" character and replace it with "`\\`". This is a Windows system, and my scripting language options are Javascript, VBScript, or Perl.
These files are largish (~10MB a piece), and there are a good number of them (~15,000). I've already come up with the following Javascript:
```
function EscapeSlashes(inFilePath)
{
var readOnly = 1;
var fso = WScript.CreateObject("Scripting.FileSystemObject");
var outFile = fso.CreateTextFile(inFilePath + "escaped.js", true);
var inFile = fso.OpenTextFile(inFilePath, readOnly);
var currChar;
while(!inFile.AtEndOfStream)
{
currChar = inFile.Read(1);
//check for single backslash
if(currChar != "\\")
{
outFile.Write(currChar);
}
else
{
//write out a double backslash
outFile.Write("\\\\");
}
}
outFile.Close();
inFile.Close();
}
```
I'm worried that the above might be a bit slow. Is there any way to improve the algorithm? Since I'm replacing one character with two, I don't think this can be done in-place.
Is there any performance advantage to reading line by line, rather than character by character?
Do Perl or VBScript have any advantages over Javascript in this case? | You can't do it in place, but generally it's a good idea to read data in chunks rather than reading a single value at a time. Read a chunk, and then iterate through it. Read another chunk, etc - until the "chunk" is of length 0, or however the call to Read indicates the end of the stream. (On most platforms the call to Read can indicate that rather than you having to call a separate AtEndOfStream function.)
Also, I wouldn't be surprised if Perl could do this in a single line. Or use `sed` if you can :) | I'd suggest reading and writing bigger chunks (be it lines or a large number of bytes). This should cut down on the IO you need to do and allow you to run faster. However your files may be too large to easily manipulate in memory all together. Play with read/write sizes and see what's fastest for you. | Improving my file i/o algorithm | [
"",
"javascript",
"algorithm",
"optimization",
"file-io",
""
] |
In my asp .net form, I refresh a control using Ajax through the AjaxPro library. However, after doing so...causing any "normal" postback results in a yellow screen (Complete error after the message)
I've set the following Page properties in web.config without any luck
```
<pages enableSessionState="true" enableViewState="false" enableEventValidation="false" enableViewStateMac="false">
```
I've also tried generating a machine key as some solutions suggested online. But that doesn't help either.
Any suggestions?
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*Contents of ASP .NET yellow screen\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
Server Error in '/' Application.
The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.
Source Error:
[No relevant source lines]
Source File: c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\c89baa89\d92b83c5\App_Web_tahnujzf.4.cs Line: 0
Stack Trace:
[FormatException: Invalid character in a Base-64 string.]
System.Convert.FromBase64String(String s) +0
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +72
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
System.Web.UI.HiddenFieldPageStatePersister.Load() +113
[ViewStateException: Invalid viewstate.
Client IP: 127.0.0.1
Port: 49736
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
ViewState: /wEPDwULLTE0OTczNDQ1NjdkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYGBSljdGwwMCR1c3JTaG9wcGluZ0xpc3QkdXNyU2hvcHBpbmdMaXN0X3duZAUaY3RsMDAkdXNyU2hvcHBpbmdMaXN0JF9tZ3IFVGN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAwJGNieEFsbAVcY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kY3RsMDAkXyRycHRMaW5lSXRlbXMkY3RsMDEkaW1nQnRuQ2F0ZWdvcnkFWmN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAxJGNieFNlbGVjdGlvbgVoY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kdXNyUHJvZHVjdFF1aWNrVmlld1BvcHVwJHVzclByb2R1Y3RRdWlja1ZpZXdQb3B1cF93bmQFG2N0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMA8XAgULQ3VycmVudFZpZXcFCFZpZXdDYXJ0BQ1BY3RpdmVWaWV3U2V0Z2Q=,/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgMFIWN0bDAxJF8kc...]
[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
``` | I found the problem. In response to an ajax request with the AjaxPro Library, I render controls like so-
```
Page page = new Page();
/*Not the exact way I init the control. But that's irrevelant*/
Control control = new Control();
page.Controls.Add(control)
string controlHtml;
using(StringWriter sw = new StringWriter())
{
HttpContext.Current.Server.Execute(page, sw, false);
controlHtml = sw.ToString();
}
```
The problem with this approach is that asp .net ***ALWAYS*** adds a hidden input field for viewstate. Some other hidden fields like eventtarget, eventargument, eventvalidation are added depending on the controls your page/controls contains. Then when I append the resulting html to an existing DOM element on the client side, quite obviously there are duplicate hidden input fields with the same name and id resulting in the view state corruption.
Solution?
Strip the generated html of these tags using regex (if you're good at it) or string compare/search etc functions. | Regular Expression for replace the viewstate:
returnvalue = Regex.Replace(html, @"<[/]?(form|[ovwxp]:\w+)[^>]\*?>", "", RegexOptions.IgnoreCase); | State information corrupted after dynamically adding control | [
"",
"c#",
".net",
"asp.net",
""
] |
Does anybody have a script for inserting a list of UK towns cities into a SQL server database? | Try a quich VB using the excellent link which "Machine" provided. I copied and pasted the results
Here is the code
```
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As String = "Abberley | Abbey Wood | Abbots Bromley | Abbots Langley | Abbots Leigh | Abbots Ripton | Abbotsbury | Abbotsley | Aberaeron | Aberargie | Abercastle | Abercraf | Abercych | Aberdare | Aberdaron | Aberdeen | Aberdour | Aberdovey | Aberfeldy | Aberffraw | Aberfoyle | Abergavenny | Abergele | Abergorlech | Abergwili | Aberlady | Aberlour | Abernethy | Aberporth | Abersoch | Abersychan | Abertillery | Aberystwyth | Abingdon | Abinger | Abinger Hammer | Abington | Aboyne | Abram | Abridge | Acaster Malbis | Accrington | Acharacle | Achiltibuie | Achnasheen | Acklam | Ackworth | Acle | Acocks Green | Acomb | Acrefair | Acton | Acton Bridge | Adare | Adderbury | Addingham | Addington | Addlestone | Adlington | Adstock | Aghadowey | Aghalee | Ahoghill | Airdrie | Airth | Akebar | Akeley | Albrighton | Albury | Alcester | Alconbury | Alconbury Weston | Aldbourne | Aldbrough St John | Aldbury | Aldeburgh | Aldenham | Alderbury | Alderley Edge | Aldermaston | Alderminster | Alderney | Aldersey Green | Aldershot | Aldford | Aldgate | Aldridge | Aldringham | Aldworth | Aldwych | Alexandria | Alfold | Alford | Alfreton | Alfriston | All of London | All Stretton | Allendale | Allenheads | Allerford | Allerston | Allerton | Allhallows | Allhallows-on-Sea | Allington | Alloa | Allostock | Alloway | Almeley | Almondbank | Almondsbury | Alne | Alness | Alnmouth | Alnwick | Alresford | Alrewas | Alsager | Alsagers Bank | Alston | Alstonefield | Althorne | Althorp | Altnagelvin | Alton | Alton Towers | Altrincham | Alum Bay | Alva | Alvechurch | Alvecote | Alvediston | Alveley | Alves | Alveston | Alvington | Alwoodley | Alyth | Ambergate | Amberley | Amble | Ambleside | Ambrosden | Amersham | Amesbury | Amlwch | Ammanford | Ampfield | Ampleforth | Ampthill | Amroth | Amulree | Ancaster | Anderton | Andover | Andoversford | Angle | Angmering | Annacloy | Annalong | Annan | Annbank | Anniesland | Annitsford | Anslow | Anstruther | Ansty | Antrim | Apartments all over London | Apperley Bridge | Appin | Applecross | Appledore | Appletreewick | Appley | Apsley | Arborfield | Arbroath | Archway | Arclid | Ardaneaskan | Ardbeg | Ardeley | Ardens Grafton | Ardentinny | Ardeonaig | Ardfern | Ardgay | Ardglass | Ardingly | Ardington | Ardishaig | Ardleigh | Ardmillan | Ardrishaig | Ardrossan | Ardvasar | Arisaig | Arkendale | Arkengarthdale | Arkesden | Arklow | Arlesey | Arlingham | Arlington | Armadale | Armagh | Armathwiate | Armoy | Armscote | Armthorpe | Arncliffe | Arncott | Arnold | Arnside | Aros | Arreton | Arrochar | Arthingworth | Articlave | Artigarvan | Arundel | Ascog Bay | Ascot | Ash | Ash-cum-Ridley | Ashbourne | Ashburnham Place | Ashburton | Ashcott | Ashford | Ashford in the Water | Ashford-in-the-Water | Ashill | Ashington | Ashkirk | Ashleworth | Ashley | Ashmore Green | Ashorne | Ashover | Ashprington | Ashtead | Ashton | Ashton in Makerfield | Ashton Keynes | Ashton under Lyne | Ashton-in-Makerfield | Ashton-under-Lyne | Ashurst | Ashwater | Ashwell | Ashwicke | Askam-in-Furness | Askernish | Askett | Askham | Askrigg | Aspatria | Aspley Guise | Asthall | Astmoor | Aston | Aston Cantlow | Aston Clinton | Aston Rowant | Astwood | Athelstaneford | Atherstone | Atherton | Athlone | Athy | Attleborough | Auchenblae | Auchenbowie | Auchencairn | Auchindoir | Auchinleck | Auchterarder | Auchtermuchty | Audlem | Aughnacloy | Aughrim | Aughton | Auldearn | Auldgirth | Aultbea | Aust | Austerfield | Austrey | Austwick | Avebury | Aveley | Avening | Aviemore | Avonwick | Awre | Axbridge | Axford | Axminster | Axmouth | Aycliffe | Aylesbury | Aylesford | Aylesham | Aylmerton | Aylsham | Aymestrey | Aynho | Ayot St Lawrence | Ayr | Aysgarth | Ayside |"
Dim cities() As String = s.Split("|")
Dim oWrite As System.IO.StreamWriter
oWrite = File.CreateText("C:\uktowns_sql.txt")
For Each city As String In cities
oWrite.WriteLine("INSERT INTO mytable values(" & """" & city.Trim() & """" & ")")
Next
oWrite.Flush()
oWrite.Close()
End Sub
End Class
```
Here is the result. Just change the table name
```
INSERT INTO mytable values("Abberley")
INSERT INTO mytable values("Abbey Wood")
INSERT INTO mytable values("Abbots Bromley")
INSERT INTO mytable values("Abbots Langley")
INSERT INTO mytable values("Abbots Leigh")
INSERT INTO mytable values("Abbots Ripton")
INSERT INTO mytable values("Abbotsbury")
INSERT INTO mytable values("Abbotsley")
INSERT INTO mytable values("Aberaeron")
INSERT INTO mytable values("Aberargie")
INSERT INTO mytable values("Abercastle")
INSERT INTO mytable values("Abercraf")
INSERT INTO mytable values("Abercych")
INSERT INTO mytable values("Aberdare")
INSERT INTO mytable values("Aberdaron")
INSERT INTO mytable values("Aberdeen")
INSERT INTO mytable values("Aberdour")
INSERT INTO mytable values("Aberdovey")
INSERT INTO mytable values("Aberfeldy")
INSERT INTO mytable values("Aberffraw")
INSERT INTO mytable values("Aberfoyle")
INSERT INTO mytable values("Abergavenny")
INSERT INTO mytable values("Abergele")
INSERT INTO mytable values("Abergorlech")
INSERT INTO mytable values("Abergwili")
INSERT INTO mytable values("Aberlady")
INSERT INTO mytable values("Aberlour")
INSERT INTO mytable values("Abernethy")
INSERT INTO mytable values("Aberporth")
INSERT INTO mytable values("Abersoch")
INSERT INTO mytable values("Abersychan")
INSERT INTO mytable values("Abertillery")
INSERT INTO mytable values("Aberystwyth")
INSERT INTO mytable values("Abingdon")
INSERT INTO mytable values("Abinger")
INSERT INTO mytable values("Abinger Hammer")
INSERT INTO mytable values("Abington")
INSERT INTO mytable values("Aboyne")
INSERT INTO mytable values("Abram")
INSERT INTO mytable values("Abridge")
INSERT INTO mytable values("Acaster Malbis")
INSERT INTO mytable values("Accrington")
INSERT INTO mytable values("Acharacle")
INSERT INTO mytable values("Achiltibuie")
INSERT INTO mytable values("Achnasheen")
INSERT INTO mytable values("Acklam")
INSERT INTO mytable values("Ackworth")
INSERT INTO mytable values("Acle")
INSERT INTO mytable values("Acocks Green")
INSERT INTO mytable values("Acomb")
INSERT INTO mytable values("Acrefair")
INSERT INTO mytable values("Acton")
INSERT INTO mytable values("Acton Bridge")
INSERT INTO mytable values("Adare")
INSERT INTO mytable values("Adderbury")
INSERT INTO mytable values("Addingham")
INSERT INTO mytable values("Addington")
INSERT INTO mytable values("Addlestone")
INSERT INTO mytable values("Adlington")
INSERT INTO mytable values("Adstock")
INSERT INTO mytable values("Aghadowey")
INSERT INTO mytable values("Aghalee")
INSERT INTO mytable values("Ahoghill")
INSERT INTO mytable values("Airdrie")
INSERT INTO mytable values("Airth")
INSERT INTO mytable values("Akebar")
INSERT INTO mytable values("Akeley")
INSERT INTO mytable values("Albrighton")
INSERT INTO mytable values("Albury")
INSERT INTO mytable values("Alcester")
INSERT INTO mytable values("Alconbury")
INSERT INTO mytable values("Alconbury Weston")
INSERT INTO mytable values("Aldbourne")
INSERT INTO mytable values("Aldbrough St John")
INSERT INTO mytable values("Aldbury")
INSERT INTO mytable values("Aldeburgh")
INSERT INTO mytable values("Aldenham")
INSERT INTO mytable values("Alderbury")
INSERT INTO mytable values("Alderley Edge")
INSERT INTO mytable values("Aldermaston")
INSERT INTO mytable values("Alderminster")
INSERT INTO mytable values("Alderney")
INSERT INTO mytable values("Aldersey Green")
INSERT INTO mytable values("Aldershot")
INSERT INTO mytable values("Aldford")
INSERT INTO mytable values("Aldgate")
INSERT INTO mytable values("Aldridge")
INSERT INTO mytable values("Aldringham")
INSERT INTO mytable values("Aldworth")
INSERT INTO mytable values("Aldwych")
INSERT INTO mytable values("Alexandria")
INSERT INTO mytable values("Alfold")
INSERT INTO mytable values("Alford")
INSERT INTO mytable values("Alfreton")
INSERT INTO mytable values("Alfriston")
INSERT INTO mytable values("All of London")
INSERT INTO mytable values("All Stretton")
INSERT INTO mytable values("Allendale")
INSERT INTO mytable values("Allenheads")
INSERT INTO mytable values("Allerford")
INSERT INTO mytable values("Allerston")
INSERT INTO mytable values("Allerton")
INSERT INTO mytable values("Allhallows")
INSERT INTO mytable values("Allhallows-on-Sea")
INSERT INTO mytable values("Allington")
INSERT INTO mytable values("Alloa")
INSERT INTO mytable values("Allostock")
INSERT INTO mytable values("Alloway")
INSERT INTO mytable values("Almeley")
INSERT INTO mytable values("Almondbank")
INSERT INTO mytable values("Almondsbury")
INSERT INTO mytable values("Alne")
INSERT INTO mytable values("Alness")
INSERT INTO mytable values("Alnmouth")
INSERT INTO mytable values("Alnwick")
INSERT INTO mytable values("Alresford")
INSERT INTO mytable values("Alrewas")
INSERT INTO mytable values("Alsager")
INSERT INTO mytable values("Alsagers Bank")
INSERT INTO mytable values("Alston")
INSERT INTO mytable values("Alstonefield")
INSERT INTO mytable values("Althorne")
INSERT INTO mytable values("Althorp")
INSERT INTO mytable values("Altnagelvin")
INSERT INTO mytable values("Alton")
INSERT INTO mytable values("Alton Towers")
INSERT INTO mytable values("Altrincham")
INSERT INTO mytable values("Alum Bay")
INSERT INTO mytable values("Alva")
INSERT INTO mytable values("Alvechurch")
INSERT INTO mytable values("Alvecote")
INSERT INTO mytable values("Alvediston")
INSERT INTO mytable values("Alveley")
INSERT INTO mytable values("Alves")
INSERT INTO mytable values("Alveston")
INSERT INTO mytable values("Alvington")
INSERT INTO mytable values("Alwoodley")
INSERT INTO mytable values("Alyth")
INSERT INTO mytable values("Ambergate")
INSERT INTO mytable values("Amberley")
INSERT INTO mytable values("Amble")
INSERT INTO mytable values("Ambleside")
INSERT INTO mytable values("Ambrosden")
INSERT INTO mytable values("Amersham")
INSERT INTO mytable values("Amesbury")
INSERT INTO mytable values("Amlwch")
INSERT INTO mytable values("Ammanford")
INSERT INTO mytable values("Ampfield")
INSERT INTO mytable values("Ampleforth")
INSERT INTO mytable values("Ampthill")
INSERT INTO mytable values("Amroth")
INSERT INTO mytable values("Amulree")
INSERT INTO mytable values("Ancaster")
INSERT INTO mytable values("Anderton")
INSERT INTO mytable values("Andover")
INSERT INTO mytable values("Andoversford")
INSERT INTO mytable values("Angle")
INSERT INTO mytable values("Angmering")
INSERT INTO mytable values("Annacloy")
INSERT INTO mytable values("Annalong")
INSERT INTO mytable values("Annan")
INSERT INTO mytable values("Annbank")
INSERT INTO mytable values("Anniesland")
INSERT INTO mytable values("Annitsford")
INSERT INTO mytable values("Anslow")
INSERT INTO mytable values("Anstruther")
INSERT INTO mytable values("Ansty")
INSERT INTO mytable values("Antrim")
INSERT INTO mytable values("Apartments all over London")
INSERT INTO mytable values("Apperley Bridge")
INSERT INTO mytable values("Appin")
INSERT INTO mytable values("Applecross")
INSERT INTO mytable values("Appledore")
INSERT INTO mytable values("Appletreewick")
INSERT INTO mytable values("Appley")
INSERT INTO mytable values("Apsley")
INSERT INTO mytable values("Arborfield")
INSERT INTO mytable values("Arbroath")
INSERT INTO mytable values("Archway")
INSERT INTO mytable values("Arclid")
INSERT INTO mytable values("Ardaneaskan")
INSERT INTO mytable values("Ardbeg")
INSERT INTO mytable values("Ardeley")
INSERT INTO mytable values("Ardens Grafton")
INSERT INTO mytable values("Ardentinny")
INSERT INTO mytable values("Ardeonaig")
INSERT INTO mytable values("Ardfern")
INSERT INTO mytable values("Ardgay")
INSERT INTO mytable values("Ardglass")
INSERT INTO mytable values("Ardingly")
INSERT INTO mytable values("Ardington")
INSERT INTO mytable values("Ardishaig")
INSERT INTO mytable values("Ardleigh")
INSERT INTO mytable values("Ardmillan")
INSERT INTO mytable values("Ardrishaig")
INSERT INTO mytable values("Ardrossan")
INSERT INTO mytable values("Ardvasar")
INSERT INTO mytable values("Arisaig")
INSERT INTO mytable values("Arkendale")
INSERT INTO mytable values("Arkengarthdale")
INSERT INTO mytable values("Arkesden")
INSERT INTO mytable values("Arklow")
INSERT INTO mytable values("Arlesey")
INSERT INTO mytable values("Arlingham")
INSERT INTO mytable values("Arlington")
INSERT INTO mytable values("Armadale")
INSERT INTO mytable values("Armagh")
INSERT INTO mytable values("Armathwiate")
INSERT INTO mytable values("Armoy")
INSERT INTO mytable values("Armscote")
INSERT INTO mytable values("Armthorpe")
INSERT INTO mytable values("Arncliffe")
INSERT INTO mytable values("Arncott")
INSERT INTO mytable values("Arnold")
INSERT INTO mytable values("Arnside")
INSERT INTO mytable values("Aros")
INSERT INTO mytable values("Arreton")
INSERT INTO mytable values("Arrochar")
INSERT INTO mytable values("Arthingworth")
INSERT INTO mytable values("Articlave")
INSERT INTO mytable values("Artigarvan")
INSERT INTO mytable values("Arundel")
INSERT INTO mytable values("Ascog Bay")
INSERT INTO mytable values("Ascot")
INSERT INTO mytable values("Ash")
INSERT INTO mytable values("Ash-cum-Ridley")
INSERT INTO mytable values("Ashbourne")
INSERT INTO mytable values("Ashburnham Place")
INSERT INTO mytable values("Ashburton")
INSERT INTO mytable values("Ashcott")
INSERT INTO mytable values("Ashford")
INSERT INTO mytable values("Ashford in the Water")
INSERT INTO mytable values("Ashford-in-the-Water")
INSERT INTO mytable values("Ashill")
INSERT INTO mytable values("Ashington")
INSERT INTO mytable values("Ashkirk")
INSERT INTO mytable values("Ashleworth")
INSERT INTO mytable values("Ashley")
INSERT INTO mytable values("Ashmore Green")
INSERT INTO mytable values("Ashorne")
INSERT INTO mytable values("Ashover")
INSERT INTO mytable values("Ashprington")
INSERT INTO mytable values("Ashtead")
INSERT INTO mytable values("Ashton")
INSERT INTO mytable values("Ashton in Makerfield")
INSERT INTO mytable values("Ashton Keynes")
INSERT INTO mytable values("Ashton under Lyne")
INSERT INTO mytable values("Ashton-in-Makerfield")
INSERT INTO mytable values("Ashton-under-Lyne")
INSERT INTO mytable values("Ashurst")
INSERT INTO mytable values("Ashwater")
INSERT INTO mytable values("Ashwell")
INSERT INTO mytable values("Ashwicke")
INSERT INTO mytable values("Askam-in-Furness")
INSERT INTO mytable values("Askernish")
INSERT INTO mytable values("Askett")
INSERT INTO mytable values("Askham")
INSERT INTO mytable values("Askrigg")
INSERT INTO mytable values("Aspatria")
INSERT INTO mytable values("Aspley Guise")
INSERT INTO mytable values("Asthall")
INSERT INTO mytable values("Astmoor")
INSERT INTO mytable values("Aston")
INSERT INTO mytable values("Aston Cantlow")
INSERT INTO mytable values("Aston Clinton")
INSERT INTO mytable values("Aston Rowant")
INSERT INTO mytable values("Astwood")
INSERT INTO mytable values("Athelstaneford")
INSERT INTO mytable values("Atherstone")
INSERT INTO mytable values("Atherton")
INSERT INTO mytable values("Athlone")
INSERT INTO mytable values("Athy")
INSERT INTO mytable values("Attleborough")
INSERT INTO mytable values("Auchenblae")
INSERT INTO mytable values("Auchenbowie")
INSERT INTO mytable values("Auchencairn")
INSERT INTO mytable values("Auchindoir")
INSERT INTO mytable values("Auchinleck")
INSERT INTO mytable values("Auchterarder")
INSERT INTO mytable values("Auchtermuchty")
INSERT INTO mytable values("Audlem")
INSERT INTO mytable values("Aughnacloy")
INSERT INTO mytable values("Aughrim")
INSERT INTO mytable values("Aughton")
INSERT INTO mytable values("Auldearn")
INSERT INTO mytable values("Auldgirth")
INSERT INTO mytable values("Aultbea")
INSERT INTO mytable values("Aust")
INSERT INTO mytable values("Austerfield")
INSERT INTO mytable values("Austrey")
INSERT INTO mytable values("Austwick")
INSERT INTO mytable values("Avebury")
INSERT INTO mytable values("Aveley")
INSERT INTO mytable values("Avening")
INSERT INTO mytable values("Aviemore")
INSERT INTO mytable values("Avonwick")
INSERT INTO mytable values("Awre")
INSERT INTO mytable values("Axbridge")
INSERT INTO mytable values("Axford")
INSERT INTO mytable values("Axminster")
INSERT INTO mytable values("Axmouth")
INSERT INTO mytable values("Aycliffe")
INSERT INTO mytable values("Aylesbury")
INSERT INTO mytable values("Aylesford")
INSERT INTO mytable values("Aylesham")
INSERT INTO mytable values("Aylmerton")
INSERT INTO mytable values("Aylsham")
INSERT INTO mytable values("Aymestrey")
INSERT INTO mytable values("Aynho")
INSERT INTO mytable values("Ayot St Lawrence")
INSERT INTO mytable values("Ayr")
INSERT INTO mytable values("Aysgarth")
INSERT INTO mytable values("Ayside")
INSERT INTO mytable values("")
``` | You could generate some INSERTs in MS Excel from [this list](http://en.wikipedia.org/wiki/List_of_cities_in_the_United_Kingdom) at Wikipedia.
Is that what you are looking for? | UK Cities SQL | [
"",
"sql",
"geolocation",
""
] |
I need to read and write xml files to disk from a stateless session bean running in JBoss. What is the preferred way of doing this?
Right now we are accessing the file system using the java.io classes.
I found a simple file system RAR example and have got that working but it may be more buggy than just using java.io directly. | If you check that *Programming Restrictions* section of the [EJB Spec](http://java.sun.com/products/ejb/docs.html) you'll find the following:
> An enterprise bean must not use the java.io package to attempt to
> access files and directories in the
> file system.
If you can find a better, possibly secure and more importantly, transactional way of doing it, please reconsider. We have a system that stores PDF documents as blobs in a database and then serves them to the users by email or servlet.
The JBoss JCA based FSManagedConnectionFactory isn't too bad. It is JNDI based and likely to work in more instances than just hacking around java.io | If you properly close the file and clean up, you can use anything you want.
I would use an XML parser to read or write XML files, though, it is safer. | FileIO from an stateless session bean | [
"",
"java",
"jboss",
""
] |
As the title says. Where do they go? they're variables, but they're also code... | They should go where they're needed. Can you clarify your question?
A variable that holds a reference to a lambda (or any Delegate) is still a variable. Treat it like a variable.
That doesn't mean you HAVE to use variables. You can just specify the lambda inline in many cases. | I'd put them with the rest of your variables, since they can be reassigned and changed just like any other variable. Like this:
```
class Test
{
string s = "abcdefg";
int one = 1;
Func<int> myFunc;
void MyMethod()
{
int x = 5;
float f = 3.86;
Action<string> a;
}
}
```
I'm not quite sure what else (or where else) you would mean? | Where should Funcs/Actions/etc. go in code? | [
"",
"c#",
"lambda",
""
] |
At the moment we have a number of tables that are using newid() on the primary key. This is causing large amounts of fragmentation. So I would like to change the column to use newsequentialid() instead.
I imagine that the existing data will remain quite fragmented but the new data will be less fragmented. This would imply that I should perhaps wait some time before changing the PK index from non-clustered to clustered.
My question is, does anyone have experience doing this? Is there anything I have overlooked that I should be careful of? | If you switch to sequentialguids *and* reorganize the index once at the same time, you'll eliminate fragmentation. I don't understand why you want to just wait until the fragmented page links rearrange themselves in continuous extents.
That being said, have you done any measurement to show that the fragmentation is actually affecting your system? Just looking at an index and seeing 'is fragmented 75%' does **not** imply that the access time is affected. There are many more factors that come into play (buffer pool page life expectancy, rate of reads vs. writes, locality of sequential operations, concurrency of operations etc etc). While switching from guids to sequential guids is usualy safe, you may introduce problems still. For instance you can see page latch contention for an insert intensive OLTP system because it creates a hot-spot page where the inserts accumulate. | You might think about using [comb guids](http://www.informit.com/articles/article.aspx?p=25862), as opposed to newsequentialid.
```
cast(
cast(NewID() as binary(10)) +
cast(GetDate() as binary(6))
as uniqueidentifier)
```
Comb guids are a combination of purely random guids along with the non-randomness of the current datetime, so that sequential generations of comb guids are near each other and in general in ascending order. Comb guids have various advantages over newsequentialid, including the facts that they are not a black box, that you can use this formula outside of a default constraint, and that you can use this formula outside of SQL Server. | Changing newid() to newsequentialid() on an existing table | [
"",
"sql",
"clustered-index",
"newsequentialid",
"newid",
""
] |
I want to learn C# and the .Net Framework as well.
I have no idea on the Microsoft .Net and C# framework but I once programmed on their Microsoft Visual Basic 6 with experience on making COM Components (OCX and DLL).
I have an experience programming on java and have fair knowledge of Object Oriented Technology. But I am currently confused on the number of books currently written for C#.
I want a book that will not explain me the for loop or iterative looping on one chapter but more on the language itself. I've heard that C# is a close cousin of Java so I think I just want to know the syntax.
Since I dont know C# and .Net framework< i would like a book that could focus on them.
Currently, as I have viewed from the net.
I have this list of books:
* Head First C#
* Illustrated C#
* MS C# 2008 Step By STep
* Illustrated C#
* C# 3.0 in a Nutshell
* Wrox Beginning C# 2008
* C# in Depth
From the review in amazon, they all look good but I dont know which one of them or that is not in the list that I have would suit me.
I definitely want to learn C# so hopefully someone can help me | [Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition](http://www.apress.com/book/view/9781590598849) is my favorite. It takes you from the CLR basics all the way to the advanced 3.5 topics.
You can read the first few chapters now to get a good grip on the basics and then go on with the more advanced chapters when you feel ready for it. | I'm a fan of the [CLR via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632), by Jeffrey Richter, a man very, very wise in C#-fu.
Also, check out our very own [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet)'s [C# in Depth](https://rads.stackoverflow.com/amzn/click/com/1933988363).
Both are great reads. | Books For Learning C# | [
"",
"c#",
".net",
""
] |
How do I check if browser supports `position:fixed` using jQuery. I assume I have to use `$.support` I think, but how?
Thank you for your time. | The most reliable way would be to actually feature-test it. Browser sniffing is fragile and unreliable.
I have an example of such test in CFT <http://kangax.github.com/cft/#IS_POSITION_FIXED_SUPPORTED>. Note that the test should be run after `document.body` is loaded. | I find that mobile safari (specifically iOS 4.2 via the iOS Simulator on OSX) refuses to scroll anywhere unless you wait a few miliseconds. Hence the false positive.
I wrote a quick jquery plugin to work around it:
```
(function($) {
$.support.fixedPosition = function (callback) {
setTimeout(
function () {
var container = document.body;
if (document.createElement && container && container.appendChild && container.removeChild) {
var el = document.createElement('div');
if (!el.getBoundingClientRect) return null;
el.innerHTML = 'x';
el.style.cssText = 'position:fixed;top:100px;';
container.appendChild(el);
var originalHeight = container.style.height,
originalScrollTop = container.scrollTop;
container.style.height = '3000px';
container.scrollTop = 500;
var elementTop = el.getBoundingClientRect().top;
container.style.height = originalHeight;
var isSupported = !!(elementTop === 100);
container.removeChild(el);
container.scrollTop = originalScrollTop;
callback(isSupported);
}
else {
callback(null);
}
},
20
);
}
})(jQuery);
``` | jQuery check if browser support position: fixed | [
"",
"javascript",
"jquery",
""
] |
I have a bunch of data coming in (calls to an automated callcenter) about whether or not a person buys a particular product, 1 for buy, 0 for not buy.
I want to use this data to create an estimated probability that a person will buy a particular product, but the problem is that I may need to do it with relatively little historical data about how many people bought/didn't buy that product.
A friend recommended that with Bayesian probability you can "help" your probability estimate by coming up with a "prior probability distribution", essentially this is information about what you expect to see, prior to taking into account the actual data.
So what I'd like to do is create a method that has something like this signature (Java):
```
double estimateProbability(double[] priorProbabilities, int buyCount, int noBuyCount);
```
priorProbabilities is an array of probabilities I've seen for previous products, which this method would use to create a prior distribution for this probability. buyCount and noBuyCount are the actual data specific to this product, from which I want to estimate the probability of the user buying, given the data and the prior. This is returned from the method as a double.
I don't need a mathematically perfect solution, just something that will do better than a uniform or flat prior (ie. *probability = buyCount / (buyCount+noBuyCount)*). Since I'm far more familiar with source code than mathematical notation, I'd appreciate it if people could use code in their explanation. | Here's the Bayesian computation and one example/test:
```
def estimateProbability(priorProbs, buyCount, noBuyCount):
# first, estimate the prob that the actual buy/nobuy counts would be observed
# given each of the priors (times a constant that's the same in each case and
# not worth the effort of computing;-)`
condProbs = [p**buyCount * (1.0-p)**noBuyCount for p in priorProbs]
# the normalization factor for the above-mentioned neglected constant
# can most easily be computed just once
normalize = 1.0 / sum(condProbs)
# so here's the probability for each of the prior (starting from a uniform
# metaprior)
priorMeta = [normalize * cp for cp in condProbs]
# so the result is the sum of prior probs weighed by prior metaprobs
return sum(pm * pp for pm, pp in zip(priorMeta, priorProbs))
def example(numProspects=4):
# the a priori prob of buying was either 0.3 or 0.7, how does it change
# depending on how 4 prospects bought or didn't?
for bought in range(0, numProspects+1):
result = estimateProbability([0.3, 0.7], bought, numProspects-bought)
print 'b=%d, p=%.2f' % (bought, result)
example()
```
output is:
```
b=0, p=0.31
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.69
```
which agrees with my by-hand computation for this simple case. Note that the probability of buying, by definition, will always be between the lowest and the highest among the set of priori probabilities; if that's not what you want you might want to introduce a little fudge by introducing two "pseudo-products", one that nobody will ever buy (p=0.0), one that anybody will always buy (p=1.0) -- this gives more weight to actual observations, scarce as they may be, and less to statistics about past products. If we do that here, we get:
```
b=0, p=0.06
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.94
```
Intermediate levels of fudging (to account for the unlikely but not impossible chance that this new product may be worse than any one ever previously sold, or better than any of them) can easily be envisioned (give lower weight to the artificial 0.0 and 1.0 probabilities, by adding a vector priorWeights to `estimateProbability`'s arguments).
This kind of thing is a substantial part of what I do all day, now that I work developing applications in Business Intelligence, but I just can't get enough of it...!-) | A really simple way of doing this without any difficult math is to increase buyCount and noBuyCount artificially by adding virtual customers that either bought or didn't buy the product. You can tune how much you believe in each particular prior probability in terms of how many virtual customers you think it is worth.
In pseudocode:
```
def estimateProbability(priorProbs, buyCount, noBuyCount, faithInPrior=None):
if faithInPrior is None: faithInPrior = [10 for x in buyCount]
adjustedBuyCount = [b + p*f for b,p,f in
zip(buyCount, priorProbs, faithInPrior]
adjustedNoBuyCount = [n + (1-p)*f for n,p,f in
zip(noBuyCount, priorProbs, faithInPrior]
return [b/(b+n) for b,n in zip(adjustedBuyCount, adjustedNoBuyCount]
``` | Estimating a probability given other probabilities from a prior | [
"",
"java",
"statistics",
"probability",
""
] |
I noticed that [some people](http://www.javalobby.org/java/forums/t19476.html) write beans with support for the Property Change observer pattern.
```
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class SampleBean implements Serializable {
public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";
private String sampleProperty;
private PropertyChangeSupport propertySupport;
public ChartBean() {
propertySupport = new PropertyChangeSupport(this);
}
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}
```
However, I remember reading that observer pattern is not commonly used in web based MVC patterns, due to the stateless nature of web applications.
**Is it a good practice to follow the above pattern in *web application* Java beans?** | To be honest only bother if you are actually going to need the feature. Most web applications don't need `PropertyChangeSupport`. I can't actually remember seeing it being used in any web app that I've seen. I've only seen it being used a Swing application.
A typical `bean` in a web application is a pretty short lived object, prepared to service the single request and then cast off in to the void to be garbage collected. The main issue is that web applications are my there nature concurrent and multi user this doesn't lend it self to longer lived objects with listeners and events etc. | `PropertyChangeListener` is of a rather poor design anyway - all that magic string comparison. Much better go for a simple models with `ChangeListener` (or similar) and bring together with composite models.
Unless you are doing something interactive and COMETy, then it doesn't make a great deal of sense in a web application. You generally have a pull model where all the current information is bundled up in one go. It may make sense where you have caches.
You can even write desktop applications in the same manner as webapps. Any change (or series of changes) and sync the GUI. This turns out to be quite compact. Also the performance costs are moved from the critical time of major changes (such as opening a window) to be spread over non-critical time where you have cycles to burn. | Should I add support for PropertyChangeSupport and PropertyChangeListener in a Java bean for a web application? | [
"",
"java",
"web-applications",
"observer-pattern",
"javabeans",
""
] |
Has anyone tried NHibernate on Azure? Is there conflicts with the medium trust or SQL integration? | The NHibernate test suite [fully works on SQL Azure](http://ayende.com/Blog/archive/2009/09/05/nhibernate-on-the-cloud-sql-azure.aspx). You should be able to simply change your connection string to your SQL Azure connection string.
There shouldn't be any hangups in running using NHibernate from a Web or Worker role. | I have tried NHibernate 3 inside Azure Web Role which talks to Azure SQL.
I did not have any problems, runs pretty fine.
I am using NFluent for configuration. I can create the database directly from the mapping configuration.
There was only one issue with the HiLo generator. If you are interested in details, I have [post it on my blog](http://www.hoonzis.com/nhibernate-nfluent-and-custom-hilo/).
This issue comes from the fact that Azure SQL is not completely compatible with SQL Server. The limitations of Azure SQL are [described here](http://msdn.microsoft.com/en-us/library/windowsazure/ee336245.aspx).
But that was just a minor issue. | NHibernate on Azure? | [
"",
"c#",
"nhibernate",
"azure",
""
] |
(C#, prime generator)
Heres some code a friend and I were poking around on:
```
public List<int> GetListToTop(int top)
{
top++;
List<int> result = new List<int>();
BitArray primes = new BitArray(top / 2);
int root = (int)Math.Sqrt(top);
for (int i = 3, count = 3; i <= root; i += 2, count++)
{
int n = i - count;
if (!primes[n])
for (int j = n + i; j < top / 2; j += i)
{
primes[j] = true;
}
}
if (top >= 2)
result.Add(2);
for (int i = 0, count = 3; i < primes.Length; i++, count++)
{
if (!primes[i])
{
int n = i + count;
result.Add(n);
}
}
return result;
}
```
On my dorky AMD x64 1800+ (dual core), for all primes below 1 billion in 34546.875ms. Problem seems to be storing more in the bit array. Trying to crank more than ~2billion is more than the bitarray wants to store. Any ideas on how to get around that? | I would "swap" parts of the array out to disk. By that, I mean, divide your bit array into half-billion bit chunks and store them on disk.
The have only a few chunks in memory at any one time. With C# (or any other OO language), it should be easy to encapsulate the huge array inside this chunking class.
You'll pay for it with a slower generation time but I don't see any way around that until we get larger address spaces and 128-bit compilers. | Or as an alternative approach to the one suggested by Pax, make use of the new Memory-Mapped File classes in .NET 4.0 and let the OS decide which chunks need to be in memory at any given time.
Note however that you'll want to try and optimise the algorithm to increase locality so that you do not needlessly end up swapping pages in and out of memory (trickier than this one sentence makes it sound). | C# Prime Generator, Maxxing out Bit Array | [
"",
"c#",
"primes",
"bitarray",
""
] |
```
namespace MyApp.MyNamespace
{
public class MyClass:System.Web.UI.Page
{
private DataUtility Util = new DataUtility();
private CookieData cd = MyClass.Toolbox.GetCurrentCookieData(HttpContext.Current);
//below I get the error: "System.Web.UI.Util is unavailable due to its protection level"
private int CompanyID = Util.GetCompanyIDByUser(cd.Users);
protected override void OnLoad(EventArgs e)
{
//I'd like to use CompanyID here
}
protected void MyEventHandler(object sender, EventArgs e)
{
//as well as here
}
}
```
And here is DataUtility:
```
public class DataUtility
{
public DataUtility() {}
//snip
public int GetCompanyIDByUser(int UserID)
{
//snip
}
}
```
I've looked and DataUility as well as the method inside of it are declared public, so I'm not sure why I am getting this error. | I just added static keyword to DataUtility initializer, and everything worked like a charm. Thanks everyone. :) | You cannot reference an instance field of your class in a field initializer.
Move `cd = Util.GetCompanyIDByUser(cd.Users);` to the class constructor, and it will work.
The reason you're getting a seemingly incorrect error message is that your Util field is conflicting with an internal type in the .Net framework. If you rename `Util` to `util` (lowercase `u`), you'll get a more correct error message (but that won't solve the problem unless you move the method call to the `MyClass` constructor, as above). | Getting Accessibility Error on Public Object | [
"",
"c#",
"asp.net",
""
] |
I've been looking on google but not finding anything that does the trick for me.
as you know SQL has a "where x in (1,2,3)" clause which allows you to check against multiple values.
I'm using linq but I can't seem to find a piece of syntax that does the same as the above statement.
I have a collection of category id's (List) against which I would like to check
I found something that uses the .contains method but it doesn't even build. | You have to use the Contains method on your id list:
```
var query = from t in db.Table
where idList.Contains(t.Id)
select t;
``` | The syntax is below:
```
IEnumerable<int> categoryIds = yourListOfIds;
var categories = _dataContext.Categories.Where(c => categoryIds.Contains(c.CategoryId));
```
The key thing to note is that you do the contains on your list of ids - not on the object you would apply the in to if you were writing sql. | LINQ Where in collection clause | [
"",
"c#",
"linq-to-sql",
""
] |
I'm looking for just a compiler for C++ (such as g++) for Windows, that I could run in my cmd.
I'm using notepad++ as my text editor and I want to set up a macro in there that can compile my programs for me.
I do not wish to install Cygwin though.
Any suggestions? | [MinGW](http://www.mingw.org/). It's GCC/G++ for Windows. It's much lighter than Cygwin. The main difference from Cygwin GCC is that it doesn't try to emulate UNIX APIs, you have to use the Windows APIs (and of course the standard C/C++ libraries). It also doesn't provide a shell and utilities like Cygwin, just the compiler.
There is also a related system called MSYS, which provides a shell, etc. like Cygwin, but this is not required. MinGW itself *will* run in CMD (but I highly suggest using something better like Bash, for your own sanity). | Visual C++ has a command line compiler, `cl`:
* [Compiler Command-Line Syntax (C++)](http://msdn.microsoft.com/en-us/library/610ecb4h(VS.80).aspx) | C++ Compiler for Windows without IDE? | [
"",
"c++",
"windows",
"compiler-construction",
"notepad++",
""
] |
I'm trying to do something like :
```
SELECT * FROM table LIMIT 10,20
```
or
```
SELECT * FROM table LIMIT 10 OFFSET 10
```
but using SQL Server
The only [solution I found](http://blogs.msdn.com/sqlserver/archive/2006/10/25/limit-in-sql-server.aspx) looks like overkill:
```
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases
) a WHERE row > 5 and row <= 10
```
I also [found](http://vorg.ca/626-the-MS-SQL-equivalent-to-MySQLs-limit-command):
```
SELECT TOP 10 * FROM stuff;
```
... but it's not what I want to do since I can't specify the starting limit.
Is there another way for me to do that ?
Also, just curious, is there a reason why doesn't SQL Server support the `LIMIT` function or something similar? I don't want to be mean, but that really sounds like something a DBMS needs ... If it does, then I'm sorry for being so ignorant! I've been working with MySQL and SQL+ for the past 5 years so... | The `LIMIT` clause is not part of standard SQL. It's supported as a vendor extension to SQL by MySQL, PostgreSQL, and SQLite.
Other brands of database may have similar features (e.g. `TOP` in Microsoft SQL Server), but these don't always work identically.
It's hard to use `TOP` in Microsoft SQL Server to mimic the `LIMIT` clause. There are cases where it just doesn't work.
The solution you showed, using `ROW_NUMBER()` is available in Microsoft SQL Server 2005 and later. This is the best solution (for now) that works solely as part of the query.
Another solution is to use `TOP` to fetch the first *count* + *offset* rows, and then use the API to seek past the first *offset* rows.
See also:
* "[Emulate MySQL LIMIT clause in Microsoft SQL Server 2000](https://stackoverflow.com/questions/216673/emulate-mysql-limit-clause-in-microsoft-sql-server-2000)"
* "[Paging of Large Resultsets in ASP.NET](http://www.codeproject.com/KB/aspnet/PagingLarge.aspx)" | For SQL Server 2012 + [you can use](http://msdn.microsoft.com/en-us/library/ms188385%28SQL.110%29.aspx).
```
SELECT *
FROM sys.databases
ORDER BY name
OFFSET 5 ROWS
FETCH NEXT 5 ROWS ONLY
``` | LIMIT 10..20 in SQL Server | [
"",
"sql",
"sql-server",
"pagination",
"limit",
""
] |
I have a grid, and I'm setting the `DataSource` to a `List<IListItem>`. What I want is to have the list bind to the underlying type, and disply those properties, rather than the properties defined in `IListItem`. So:
```
public interface IListItem
{
string Id;
string Name;
}
public class User : IListItem
{
string Id { get; set; };
string Name { get; set; };
string UserSpecificField { get; set; };
}
public class Location : IListItem
{
string Id { get; set; };
string Name { get; set; };
string LocationSpecificField { get; set; };
}
```
How do I bind to a grid so that if my `List<IListItem>` contains users I will see the user-specific field? Edit: Note that any given list I want to bind to the Datagrid will be comprised of a single underlying type. | Data-binding to lists follows the following strategy:
1. does the data-source implement `IListSource`? if so, goto 2 with the result of `GetList()`
2. does the data-source implement `IList`? if not, throw an error; list expected
3. does the data-source implement `ITypedList`? if so use this for metadata (exit)
4. does the data-source have a non-object indexer, `public Foo this[int index]` (for some `Foo`)? if so, use `typeof(Foo)` for metadata
5. is there anything in the list? if so, use the first item (`list[0]`) for metadata
6. no metadata available
`List<IListItem>` falls into "4" above, since it has a typed indexer of type `IListItem` - and so it will get the metadata via `TypeDescriptor.GetProperties(typeof(IListItem))`.
So now, you have three options:
* write a `TypeDescriptionProvider` that returns the properties for `IListItem` - I'm not sure this is feasible since you can't possibly know what the concrete type is given just `IListItem`
* use the correctly typed list (`List<User>` etc) - simply as a simple way of getting an `IList` with a non-object indexer
* write an `ITypedList` wrapper (lots of work)
* use something like `ArrayList` (i.e. no public non-object indexer) - very hacky!
My preference is for using the correct type of `List<>`... here's an `AutoCast` method that does this for you **without having to know the types** (with sample usage);
Note that this only works for homogeneous data (i.e. all the objects are the same), and it requires at least one object in the list to infer the type...
```
// infers the correct list type from the contents
static IList AutoCast(this IList list) {
if (list == null) throw new ArgumentNullException("list");
if (list.Count == 0) throw new InvalidOperationException(
"Cannot AutoCast an empty list");
Type type = list[0].GetType();
IList result = (IList) Activator.CreateInstance(typeof(List<>)
.MakeGenericType(type), list.Count);
foreach (object obj in list) result.Add(obj);
return result;
}
// usage
[STAThread]
static void Main() {
Application.EnableVisualStyles();
List<IListItem> data = new List<IListItem> {
new User { Id = "1", Name = "abc", UserSpecificField = "def"},
new User { Id = "2", Name = "ghi", UserSpecificField = "jkl"},
};
ShowData(data, "Before change - no UserSpecifiedField");
ShowData(data.AutoCast(), "After change - has UserSpecifiedField");
}
static void ShowData(object dataSource, string caption) {
Application.Run(new Form {
Text = caption,
Controls = {
new DataGridView {
Dock = DockStyle.Fill,
DataSource = dataSource,
AllowUserToAddRows = false,
AllowUserToDeleteRows = false
}
}
});
}
``` | As long as you know for sure that the members of the List<IListItem> are all going to be of the same derived type, then here's how to do it, with the "Works on my machine" seal of approval.
First, download [BindingListView](http://blw.sourceforge.net/), which will let you bind generic lists to your DataGridViews.
For this example, I just made a simple form with a DataGridView and randomly either called code to load a list of Users or Locations in Form1\_Load().
```
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Equin.ApplicationFramework;
namespace DGVTest
{
public interface IListItem
{
string Id { get; }
string Name { get; }
}
public class User : IListItem
{
public string UserSpecificField { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
public class Location : IListItem
{
public string LocationSpecificField { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InitColumns(bool useUsers)
{
if (dataGridView1.ColumnCount > 0)
{
return;
}
DataGridViewCellStyle gridViewCellStyle = new DataGridViewCellStyle();
DataGridViewTextBoxColumn IDColumn = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn NameColumn = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn DerivedSpecificColumn = new DataGridViewTextBoxColumn();
IDColumn.DataPropertyName = "ID";
IDColumn.HeaderText = "ID";
IDColumn.Name = "IDColumn";
NameColumn.DataPropertyName = "Name";
NameColumn.HeaderText = "Name";
NameColumn.Name = "NameColumn";
DerivedSpecificColumn.DataPropertyName = useUsers ? "UserSpecificField" : "LocationSpecificField";
DerivedSpecificColumn.HeaderText = "Derived Specific";
DerivedSpecificColumn.Name = "DerivedSpecificColumn";
dataGridView1.Columns.AddRange(
new DataGridViewColumn[]
{
IDColumn,
NameColumn,
DerivedSpecificColumn
});
gridViewCellStyle.SelectionBackColor = Color.LightGray;
gridViewCellStyle.SelectionForeColor = Color.Black;
dataGridView1.RowsDefaultCellStyle = gridViewCellStyle;
}
public static void BindGenericList<T>(DataGridView gridView, List<T> list)
{
gridView.DataSource = new BindingListView<T>(list);
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
Random rand = new Random();
bool useUsers = rand.Next(0, 2) == 0;
InitColumns(useUsers);
if(useUsers)
{
TestUsers();
}
else
{
TestLocations();
}
}
private void TestUsers()
{
List<IListItem> items =
new List<IListItem>
{
new User {Id = "1", Name = "User1", UserSpecificField = "Test User 1"},
new User {Id = "2", Name = "User2", UserSpecificField = "Test User 2"},
new User {Id = "3", Name = "User3", UserSpecificField = "Test User 3"},
new User {Id = "4", Name = "User4", UserSpecificField = "Test User 4"}
};
BindGenericList(dataGridView1, items.ConvertAll(item => (User)item));
}
private void TestLocations()
{
List<IListItem> items =
new List<IListItem>
{
new Location {Id = "1", Name = "Location1", LocationSpecificField = "Test Location 1"},
new Location {Id = "2", Name = "Location2", LocationSpecificField = "Test Location 2"},
new Location {Id = "3", Name = "Location3", LocationSpecificField = "Test Location 3"},
new Location {Id = "4", Name = "Location4", LocationSpecificField = "Test Location 4"}
};
BindGenericList(dataGridView1, items.ConvertAll(item => (Location)item));
}
}
}
```
The important lines of code are these:
```
DerivedSpecificColumn.DataPropertyName = useUsers ? "UserSpecificField" : "LocationSpecificField"; // obviously need to bind to the derived field
public static void BindGenericList<T>(DataGridView gridView, List<T> list)
{
gridView.DataSource = new BindingListView<T>(list);
}
dataGridView1.AutoGenerateColumns = false; // Be specific about which columns to show
```
and the most important are these:
```
BindGenericList(dataGridView1, items.ConvertAll(item => (User)item));
BindGenericList(dataGridView1, items.ConvertAll(item => (Location)item));
```
If all items in the list are known to be of the certain derived type, just call ConvertAll to cast them to that type. | C# grid DataSource polymorphism | [
"",
"c#",
"winforms",
"datagridview",
""
] |
I want to run regasm.exe from cmd. which is available in c:\windows\Microsoft.net\framework\2.057
I do like this c:\ regasm.exe
It gives *regasm is not recognized as internal or external command*.
So I understood that I need to set the path for regasm.exe in environment variable.
For which variable do I need to set the path to run regasm as described above? | In command prompt:
```
SET PATH = "%PATH%;%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
``` | Like Cheeso said:
> You don't need the directory on your path. You could put it on your path, but you don't NEED to do that.
> If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:
***%SystemRoot%***\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyAssembly.dll | How to run regasm.exe from command line other than Visual Studio command prompt? | [
"",
".net",
"c++",
"visual-c++",
"command-line",
"operating-system",
""
] |
I've been having a look at Django and, from what I've seen, it's pretty darn fantastic. I'm a little confused, however, how I go about implementing a "home page" for my website? Would it be a separate app, or just a view within the project, or what? | There's no real rule for this, But one thing I like to do is actually arrange for the index access to redirect to another spot. If you prefer, though, you can just give the index page a plain view.
That said, It's probably a good idea to keep all your code in an actual app, so that you can refactor it more easily, and so that it appears on the python path as a normal module. Putting views in the project rather than an app seems to cause more headaches than it solves. | I just found my original approach (`direct_to_template`) is deprecated in Django 1.5
Instead, use a `TemplateView` to achieve the same result
```
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^$',
TemplateView.as_view(template_name='index.html'),
name='index'),
)
```
(**For Django 1.4**) You can setup a `direct_to_template` url within `./project/project/urls.py`
```
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^$', direct_to_template, { 'template': 'index.html'}),
# add urls to apps here
)
```
For both, place the template (`index.html`) in your `TEMPLATE_DIRS` root. This is one approach to create a homepage without implementing an entire app. There are many ways to make this happen as others have noted. | Django - Website Home Page | [
"",
"python",
"django",
""
] |
I am getting the following error while migrating VC6 code to VS2008. This code works fine in VC6 but gives a compilation error in VC9. I know it is because of a compiler breaking change. What is the problem and how do I fix it?
```
error C2440: 'initializing' : cannot convert
from 'std::_Vector_iterator<_Ty,_Alloc>'
to 'STRUCT_MUX_NOTIFICATION *'
```
Code
```
MUX_NOTIFICATION_VECTOR::iterator MuxNotfnIterator;
for(
MuxNotfnIterator = m_MuxNotfnCache.m_MuxNotificationVector.begin();
MuxNotfnIterator != m_MuxNotfnCache.m_MuxNotificationVector.end();
MuxNotfnIterator ++
)
{
STRUCT_MUX_NOTIFICATION *pstMuxNotfn = MuxNotfnIterator; //Error 2440
}
``` | If it worked before, I am guessing MUX\_NOTIFICATION\_VECTOR is a typedef
```
typedef std::vector<STRUCT_MUX_NOTIFICATION> MUX_NOTIFICATION_VECTOR;
```
The iterator for a container can often be mistaken with a pointer (because it works the same way) and, in the case of some stl implementations, it can actually be a pointer (it probably was the case with STL provided with VC6). But there is no guarantee about that.
What you should do is the following :
```
STRUCT_MUX_NOTIFICATION& reference = *MuxNotfnIterator;
// or
STRUCT_MUX_NOTIFICATION* pointer = &(*MuxNotfnIterator);
``` | I think this should do the trick:
```
STRUCT_MUX_NOTIFICATION *pstMuxNotfn = &(*MuxNotfnIterator);
``` | error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'type *' | [
"",
"c++",
"visual-studio-2008",
"iterator",
"porting",
"visual-c++-6",
""
] |
Here is the code I have thus far:
```
import java.io.*;
class JAVAFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".java"));
}
}
public class tester {
public static void main(String args[])
{
FilenameFilter filter = new JAVAFilter();
File directory = new File("C:\\1.3\\");
String filename[] = directory.list(filter);
}
}
```
At this point, it'll store a list of all the \*.java files from the directory C:\1.3\ in the string array *filename*. However, i'd like to store a list of all the java files also in subdirectories (preferably with their path within C:\1.3\ specified also. How do I go about doing this? Thanks! | As far as I know, you will have to do this manually (recursively), i.e. you will have to call list(filter) for all sub-directories of C:\1.3\, and so on.... | I'm afraid you can't do it with the `list(FilenameFilter)` method. You'll have to list all files and directories, and then do the filtering yourself. Something like this:
```
public List<File> getFiles(File dir, FilenameFilter filter) {
List<File> ret = new ArrayList<File>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
ret.addAll(getFiles(f, filter));
} else if (filter.accept(dir, f.getName())) {
ret.add(f);
}
}
return ret;
}
``` | How do I import a directory (and subdirectory) listing in Java? | [
"",
"java",
"path",
"directory",
""
] |
I confess I’m new to C#. I am struggling with creating a method to delete a registry key using .NET. The method takes one string parameter which contains the complete key to be removed. Here’s a sample of what I’m trying to do that doesn’t work (obviously):
```
namespace NameHere
{
class Program
{
static void Main(string[] args)
{
RegistryKey hklm = Registry.LocalMachine;
hklm = hklm.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\")
string strKey=”Test123”;
string fullPath = hklm + "\\" + strKey;
deleteRegKey(fullPath);
}
static void deleteRegKey(string keyName)
{
Registry.LocalMachine.DeleteSubKey(keyName);
}
}
}
```
I’ve tried a few other iterations and googled for solutions but have, so far, been unable to put the pieces together. Any help would be greatly appreciated. Also, any explanation for why my lame attempt doesn’t work to help clarrify my knowledge gap would be awesome. | This routine should really be a one-liner, like:
Registry.LocalMachine.DeleteSubKey( @"SYSTEM\ControlSet...\etc..." );
You shouldn't need to open a RegistryKey object, because Registry.LocalMachine is kind of already open for you.
If you do need to open a RegistryKey object to do something else, be aware that RegistryKey implements IDisposable, so now that you've created an object, you're responsible for disposing of it no matter what. So, you have to surround your code with **try { ... }** and call Dispose() in the **finally** block. Fortunately, this can be coded in C# more elegantly using **using**:
```
using( RegistryKey key = Registry.LocalMachine.OpenSubKey(...) ) {
...
}
``` | I believe you have too many \'s. Try this:
```
RegistryKey hklm = Registry.LocalMachine;
hklm = hklm.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\")
string strKey=”Test123”;
string fullPath = hklm + strKey;
deleteRegKey(fullPath);
``` | C# Issue creating method to delete a registry key | [
"",
"c#",
"registry",
""
] |
another beginner problem. Why isn't the following code with an asp.net page not working?
```
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
list.Add("Teststring");
this.GridView.DataSource = list;
}
```
GridView is the GridView control on that asp page. However, no grid shows up at all. It's both enabled and visible. Plus when I debug, the GridView.Rows.Count is 0. I always assumed you can just add generic Lists and all classes implementing IList as a DataSource, and the gridview will then display the content automatically? Or is the reason here that it's been done in the page\_load event handler. and if, how can I fill a grid without any user interaction at startup?
Thanks again. | Unlike in winforms, for ASP developement you need to specifically call `GridView.DataBind();`. I would also break out that code into a separate method and wrap the initial call into a check for postback. That will save you some headaches down the road.
```
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
List<string> list = new List<string>();
list.Add("Teststring");
bindMydatagrid(list);
}
}
protected void bindMydatagrid(List<string> list)
{
gv.DataSource = list;
gv.DataBind();
}
``` | You should call DataBind(). | ASP.NET gridview binding doesn't work / control doesn't show up | [
"",
"c#",
"asp.net",
"gridview",
""
] |
I have asked a similar question here before, but I need to know if this little tweak is possible. I want to shorten a string to 100 characters and use `$small = substr($big, 0, 100);` to do so. However, this just takes the first 100 characters and doesn't care whether it breaks up a word or not.
Is there any way to take up to the first 100 characters of a string but make sure you don't break a word?
Example:
```
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$small = some_function($big);
echo $small;
// OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"
```
Is there a way to do this using PHP? | All you need to do is use:
```
$pos=strpos($content, ' ', 200);
substr($content,0,$pos );
``` | Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.
```
//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
```
Note that it automatically adds ellipses, if you don't want that just use `'\\1'` as the second parameter for the `preg_replace` call. | Get first 100 characters from string, respecting full words | [
"",
"php",
"string",
""
] |
The purpose of this is to avoid writing a ton of if() statements.
Here is my current code:
```
public override List<oAccountSearchResults> SearchForAccounts(oAccountSearchCriteria searchOptions)
{
List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);
results.Sort((a1, a2) => a2.AccountNumber.CompareTo(a1.AccountNumber));
return results;
}
```
What I would like to do is provide a parameter which tells me which field to sort on. Then dynamically update my sort criteria without having a bunch of if() statements such as this:
```
public override List<oAccountSearchResults> SearchForAccounts(oAccountSearchCriteria searchOptions, string sortCriteria)
{
List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);
if (sortCriteria == "AccountNumber")
{
results.Sort((a1, a2) => a2.AccountNumber.CompareTo(a1.AccountNumber));
}
else if (sortCriteria == "FirstName")
{
results.Sort((a1, a2) => a2.FirstName.CompareTo(a1.FirstName));
}
return results;
}
```
I would like to do this without having about 30 if() statements for all the sortable criteria that will be available.
Any and all help will be appreciated.
**EDIT WITH SOLUTION:**
Thank you all for your responses.
David, your approached worked but I think that Richard's answer works a bit better.
Here is the ultimate solution that I came up with. I used David's framework for the example and Richards implementation:
```
using System;
using System.Collections.Generic;
namespace SortTest
{
class Program
{
static void Main(string[] args)
{
var results1 = Search(oObject => oObject.Value1);
foreach (oObject o in results1)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.WriteLine(Environment.NewLine);
var results2 = Search(oObject => oObject.Value2);
foreach (oObject o in results2)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.ReadLine();
}
public static List<oObject> Search<T>(Func<oObject, T> keyExtract) where T: IComparable
{
var results = new List<oObject>
{
new oObject {Value1 = "A 1", Value2 = "B 2"},
new oObject {Value1 = "B 1", Value2 = "A 2"}
};
results.Sort((a, b) => keyExtract(a).CompareTo(keyExtract(b)));
return results;
}
}
class oObject
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
}
``` | If the caller could supply an *expression* which extracts the value to use to compare, you can call that delegate in the comparison function:
```
public override List<oAccountSearchResults> SearchForAccounts<T>(
oAccountSearchCriteria searchOptions,
Func<oAccountSearchResults, T> keyExtract) where T : IComparable {
List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);
results.Sort(a,b) => keyExtract(a).CompareTo(keyExtract(b)));
return results;
}
``` | You can try it like this. I have created a sample object for testing purposes:
You can view the original source from here but cleaned up for readability purposes:
<http://msdn.microsoft.com/en-us/library/bb534966.aspx>
First create an extension method on IEnumerable:
```
public static class EnumerableExtension
{
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
{
var myObject = Expression.Parameter(typeof (T), "MyObject");
var myEnumeratedObject = Expression.Parameter(typeof (IEnumerable<T>), "MyEnumeratedObject");
var myProperty = Expression.Property(myObject, property);
var myLambda = Expression.Lambda(myProperty, myObject);
var myMethod = Expression.Call(typeof (Enumerable), ascending ? "OrderBy" : "OrderByDescending",
new[] {typeof (T), myLambda.Body.Type}, myEnumeratedObject, myLambda);
var mySortedLambda =
Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(myMethod, myEnumeratedObject).Compile();
return mySortedLambda(items);
}
}
```
Here is our test object:
```
class oObject
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
```
Then in your program you can do this:
```
static void Main(string[] args)
{
var results = new List<oObject>
{
new oObject {Value1 = "A", Value2 = "B"},
new oObject {Value1 = "B", Value2 = "A"}
};
IEnumerable<oObject> query = results.OrderBy("Value2", false);
foreach (oObject o in query)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.WriteLine(Environment.NewLine);
IEnumerable<oObject> query2 = results.OrderBy("Value1", false);
foreach (oObject o in query2)
{
Console.WriteLine(o.Value1 + ", " + o.Value2);
}
Console.ReadLine();
}
```
Your results will be:
Query 1:
A, B
B, A
Query 2:
B, A
A, B | Dynamic Sort Criteria for Generic List | [
"",
"c#",
"generics",
"sorting",
""
] |
Spring and Hibernate uses reflection for bean creation (in case of spring) and POJO mapping (in case of Hibernate). Does it negatively impacts on performance ? Because reflection is slower compare to direct object creation. | While there is a performance penalty, it is relatively low and can be considered negligible. The key issue here is that the benefit you gain from using an ORM (with reflection) far outweighs the very small performance penalty you pay.
Remember that when looking at performance, design the system the way you want and worry about performance when it becomes a problem. | Yes, it probably does. Hibernate is pretty heavily optimised in various cunning ways, but it will still be slower than low-level data access with exactly the right prepared statement, assuming the cache doesn't help you.
But that's not the question you need to ask anyway.
You need to ask whether it affects performance *significantly* - at which point I suspect you'll find the answer is "no". In terms of Hibernate, the underlying database access is likely to be a *lot* slower than the overhead due to Hibernate. In terms of Spring, the bean creation often happens only at the very start of the program, a single time.
As always, if you have concerns, benchmark and profile a realistic scenario. | Performance overhead for Hibernate and Spring due to reflection | [
"",
"java",
"performance",
"hibernate",
"spring",
""
] |
I have a c# unit test project that is compiled for AnyCPU. Our build server is a 64bit machine, and has a 64bit SQL Express instance installed.
The test project uses code similar to the following to identify the path to the .MDF files:
```
private string GetExpressPath()
{
RegistryKey sqlServerKey = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" );
string sqlExpressKeyName = (string) sqlServerKey.GetValue( "SQLEXPRESS" );
RegistryKey sqlInstanceSetupKey = sqlServerKey.OpenSubKey( sqlExpressKeyName + @"\Setup" );
return sqlInstanceSetupKey.GetValue( "SQLDataRoot" ).ToString();
}
```
This code works fine on our 32bit workstations, and did work ok on the build server until I recently enabled code coverage analysis with NCover. Because NCover uses a 32bit COM component, the test runner (Gallio) runs as a 32bit process.
Checking the registry, there is no "Instance Names" key under
> HKEY\_LOCAL\_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
Is there a way for an application running in 32bit mode to access the registry outside Wow6432Node? | you have to use the KEY\_WOW64\_64KEY param when creating/opening the registry key. But AFAIK that's not possible with the Registry class but only when using the API directly.
[This](https://web.archive.org/web/20201029081011/http://www.geekswithblogs.net/derekf/archive/2007/06/26/113485.aspx) might help to get you started. | Reading the 64 bit registry is possible because of [WOW64](https://en.wikipedia.org/wiki/WoW64) which is a Windows subsystem providing access to 64 bit from within 32 bit applications. (Likewise, in older NT-based Windows versions it was called [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows) and was an emulation layer inside 32 bit Windows to support 16 bit applications).
There is still native support for registry access under 64 bit Windows using **.NET Framework 4.x** and for newer .NET versions (such as .NET Core, .NET 5 and 6) as well. The following code is tested with *Windows 7, 64 bit* and also with *Windows 10, 64 bit*. It should also work with Windows 11.
Instead of using `"Wow6432Node"`, which emulates a node by mapping one registry tree into another making it appear there virtually, you can do the follwing:
Decide, whether you need to access the 64 bit or the 32 bit registry, and use it as described below. You may also use the code I mentioned later (Additional information section), which creates a union query to get registry keys from both nodes in one query - so you can still query them by using their real path.
## 64 bit registry
To access the **64 bit registry**, you can use `RegistryView.Registry64` as follows:
```
// using Microsoft.Win32
string value64 = string.Empty;
RegistryKey localKey =
RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
RegistryView.Registry64);
localKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
if (localKey != null)
{
value64 = localKey.GetValue("RegisteredOrganization").ToString();
localKey.Close();
}
Console.WriteLine(String.Format("RegisteredOrganization [value64]: {0}",value64));
```
## 32 bit registry
If you want to access the **32bit registry**, use `RegistryView.Registry32` as follows:
```
// using Microsoft.Win32
string value32 = string.Empty;
RegistryKey localKey32 =
RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
RegistryView.Registry32);
localKey32 = localKey32.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
if (localKey32 != null)
{
value32 = localKey32.GetValue("RegisteredOrganization").ToString();
localKey32.Close();
}
Console.WriteLine(String.Format("RegisteredOrganization [value32]: {0}",value32));
```
Don't be confused, both versions are using `Microsoft.Win32.RegistryHive.LocalMachine` as first parameter, you make the distinction whether to use **64 bit** or **32 bit** by the **2nd parameter** (`RegistryView.Registry64` versus `RegistryView.Registry32`).
**Note** that
* On a 64bit Windows, `HKEY_LOCAL_MACHINE\Software\Wow6432Node` contains values used by 32 bit applications running on the 64 bit system. Only true 64 bit applications store their values in `HKEY_LOCAL_MACHINE\Software` directly. The subtree `Wow6432Node` is entirely transparent for 32 bit applications, 32 bit applications still see `HKEY_LOCAL_MACHINE\Software` as they expect it (it is a kind of redirection). In older versions of Windows as well as 32 bit Windows 7 (and Vista 32 bit) the subtree `Wow6432Node` obviously does **not** exist.
* Due to a bug in Windows 7 (64 bit), the 32 bit source code version always returns "Microsoft" regardless which organization you have registered while the 64 bit source code version returns the right organization.
Coming back to the example you've provided, do it the following way to access the 64 bit branch:
```
RegistryKey localKey =
RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
RegistryView.Registry64);
RegistryKey sqlServerKey = localKey.OpenSubKey(
@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");
string sqlExpressKeyName = (string) sqlServerKey.GetValue("SQLEXPRESS");
```
---
## Additional information - for practical use:
I'd like to add an interesting approach [Johny Skovdal](https://stackoverflow.com/users/222134/johny-skovdal) has suggested in the comments, which I've picked up to develop some useful functions by using his approach: In some situations you want to get back all keys regardless whether it is 32 bit or 64 bit. The SQL instance names are such an example. You can use a union query in that case as follows (C#6 or higher):
```
// using Microsoft.Win32;
public static IEnumerable<string> GetRegValueNames(RegistryView view, string regPath,
RegistryHive hive = RegistryHive.LocalMachine)
{
return RegistryKey.OpenBaseKey(hive, view)
?.OpenSubKey(regPath)?.GetValueNames();
}
public static IEnumerable<string> GetAllRegValueNames(string RegPath,
RegistryHive hive = RegistryHive.LocalMachine)
{
var reg64 = GetRegValueNames(RegistryView.Registry64, RegPath, hive);
var reg32 = GetRegValueNames(RegistryView.Registry32, RegPath, hive);
var result = (reg64 != null && reg32 != null) ? reg64.Union(reg32) : (reg64 ?? reg32);
return (result ?? new List<string>().AsEnumerable()).OrderBy(x => x);
}
public static object GetRegValue(RegistryView view, string regPath, string ValueName="",
RegistryHive hive = RegistryHive.LocalMachine)
{
return RegistryKey.OpenBaseKey(hive, view)
?.OpenSubKey(regPath)?.GetValue(ValueName);
}
public static object GetRegValue(string RegPath, string ValueName="",
RegistryHive hive = RegistryHive.LocalMachine)
{
return GetRegValue(RegistryView.Registry64, RegPath, ValueName, hive)
?? GetRegValue(RegistryView.Registry32, RegPath, ValueName, hive);
}
public static IEnumerable<string> GetRegKeyNames(RegistryView view, string regPath,
RegistryHive hive = RegistryHive.LocalMachine)
{
return RegistryKey.OpenBaseKey(hive, view)
?.OpenSubKey(regPath)?.GetSubKeyNames();
}
public static IEnumerable<string> GetAllRegKeyNames(string RegPath,
RegistryHive hive = RegistryHive.LocalMachine)
{
var reg64 = GetRegKeyNames(RegistryView.Registry64, RegPath, hive);
var reg32 = GetRegKeyNames(RegistryView.Registry32, RegPath, hive);
var result = (reg64 != null && reg32 != null) ? reg64.Union(reg32) : (reg64 ?? reg32);
return (result ?? new List<string>().AsEnumerable()).OrderBy(x => x);
}
```
Now you can simply use the functions above as follows:
**Example 1:** Get SQL instance names
```
var sqlRegPath=@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL";
foreach (var valueName in GetAllRegValueNames(sqlRegPath))
{
var value=GetRegValue(sqlRegPath, valueName);
Console.WriteLine($"{valueName}={value}");
}
```
will give you a list of the value names and values in sqlRegPath.
**Note:** You can access the **default** value of a key (displayed by the commandline tool `REGEDT32.EXE` as `(Default)`) if you omit the `ValueName` parameter in the corresponding functions above.
To get a list of **SubKeys** within a registry key, use the function `GetRegKeyNames`or `GetAllRegKeyNames`. You can use this list to traverse further keys in the registry.
**Example 2:** Get uninstall information of installed software
```
var currentVersionRegPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion";
var uninstallRegPath = $@"{currentVersionRegPath}\Uninstall";
var regKeys = Registry.GetAllRegKeyNames(RegPath: uninstallRegPath);
```
will get all 32 bit and 64 bit uninstall keys.
**Notice the null handling** required in the functions because SQL server can be installed as 32 bit or as 64 bit (Example 1 above). The functions are overloaded so you can still pass the 32 bit or 64 bit parameter if required - however, if you omit it then it will try to read 64 bit, if that fails (null value), it reads the 32 bit values.
There is one speciality here: Because **`GetAllRegValueNames`** is usually used in a loop context (see Example 1 above), it returns an empty enumerable rather than `null` to simplify `foreach` loops: if it wouldn't be handled that way, the loop would have to be prefixed by an `if` statement checking for `null` which would be cumbersome having to do that - so that is dealt with once in the function.
**Why bothering about null?** Because if you don't care, you'll have a lot more headaches finding out why that null reference exception was thrown in your code - you'd spend a lot of time finding out where and why it happened. And if it happened in production you'll be very busy studying log files or event logs (I hope you have logging implemented) ... better avoid null issues where you can in a defensive way. The operators `?.`, `?[`...`]` and `??` can help you a lot (see the code provided above). There is a nice related article discussing the new [nullable reference types in C#](https://blogs.msdn.microsoft.com/dotnet/2017/11/15/nullable-reference-types-in-csharp/), which I recommend to read and also [this one](https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/) about the [Elvis operator](https://krishnarajb.wordpress.com/2015/09/26/c-6-0-elvis-operator-and-other-improvements/) (a nickname for the `?.` operator, sometimes also called safe navigation operator).
---
**Hint:** You can use the free edition of **[Linqpad](https://www.linqpad.net/)** to test all examples under Windows. It doesn't require an installation. Don't forget to press `F4` and enter `Microsoft.Win32` in the Namespace import tab. In Visual Studio, you require `using Microsoft.Win32;` at the top of your code.
**Tip:** To familiarize yourself with the new **[null handling operators](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators),** try out (and debug) the following code in LinqPad:
**Example 3:** Demonstrating null handling operators
```
static string[] test { get { return null;} } // property used to return null
static void Main()
{
test.Dump(); // output: null
// "elvis" operator:
test?.Dump(); // output:
// "elvis" operator for arrays
test?[0].Dump(); // output:
(test?[0]).Dump(); // output: null
// combined with null coalescing operator (brackets required):
(test?[0]??"<null>").Dump(); // output: "<null>"
}
```
[Try it with .Net fiddle](https://dotnetfiddle.net/BfE955)
If you're interested, **[here](https://stackoverflow.com/questions/3555317/linqpad-extension-methods/12006038#12006038)** are some examples I put together showing what else you can do with the tool. | Reading 64bit Registry from a 32bit application | [
"",
"c#",
".net",
"windows",
"registry",
"wow64",
""
] |
Folks,
I'm looking to build a piece of PHP5 UI that I'm pretty sure is common to a bunch of applications. Basically, it's an expression builder that allows users to specify expressions combined through logical operators (AND/OR), like this:
* FieldX > 3 AND FieldY = 5
* FieldY = "bob" and FieldZ is not null
* FieldX > '5/23/2007' OR (FieldY = 5 AND FieldY is not null)
Ideally, a system like that would allow me as a programmer to specify the list of parameters that the user can pick (columns) and the data type for each. It would also provide a nice, user-friendly interface for defining expressions like that - I'm imagining something like a table, where each row has several pickers:
[Column] [Condition] [Value] [AND/OR]
[Column] [Condition] [Value] [AND/OR]
...
Do you know of an open-source component that does something like that? Or maybe a part of this kind of functionality? | A word of caution. These types of generic expression builders are commonly thought of as excellent solutions to a variety of user problems. The thinking tends to go along these lines:
* The user wants all these different reports
* There's no way we're giving them SQL access (even if they could understand it)
* We don't have time to write all these custom reports
* Therefore, I'll make an easy way for them to write queries without having to know specific syntax, tables and fields.
This is not necessarily a bad idea, but what we have found at my company is that non-techie users have surprising difficulty understanding and building expressions more complex than a group of ANDS or a group of ORS. This is hard for us programmers to grasp, as most of us probably had an intuitive understanding of boolean logic even before we learned to program.
I would recommend that you not try to give them complete flexibility to create whatever expression they want, and instead you put together a UI that lets you the programmer define something more complicated on the back-end but gives the user simple choices on the front-end. This is easier said than done, obviously.
Remember - sometimes the difficulty for end users isn't the fact that they don't know the right syntax to express their idea in. More often it's because they don't even know how to formulate their thoughts in an unambiguous way, even if they were provided an easy way to do so.
NOTE: I'm not saying the end users are always morons - just that their minds may work differently from us crazy developers. | I think this is a very interesting idea. Are you planning on working on this project for personal use or through work?
If you are planning on working on this project personally, maybe you should write it yourself and turn it into an open source project. It looks like there is already some interest in this area and it would be a good learning experience.
Otherwise, I can see how a company could find value in something like this. It would give the programmers another utility that could help them do their job a little bit easier and pay dividends in the long run.
Either way, this project is win. You will learn alot, and create something that other people find useful. | Generic Declarative Expression Builder in PHP | [
"",
"php",
"ajax",
"user-interface",
"expression",
"declarative",
""
] |
I'm beginning to program in Java.
```
public static void main(String[]args)
```
A book said that I should use static in this case, but doesn't clearly say why I should or what it means.
Could you clarify this? | The concept of `static` has to do with whether something is part of a class or an object (instance).
In the case of the `main` method which is declared as `static`, it says that the `main` method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the `ClassName.method`. For example, invoking the run method of `MyClass` would be accomplished by:
```
MyClass.main(new String[]{"parameter1", "parameter2"});
```
On the other hand, a method or field without the `static` modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
```
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
```
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
```
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
```
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
```
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
```
The above class has an instance variable `instanceVariable`, and a class variable `classVariable` which is declared with a `static` modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be `42` and never changed.
Let's actually use the above class and see what happens:
```
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
```
Notice the different ways the class and instance methods are called. The way they refer to the class by the name `AnotherClass`, or the instance by the name `ac1`. Let's go further and see the behavioral differences of the methods:
```
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
```
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by `ac1` and `ac2`.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the `AnotherClass`:
```
public int getClassVariableFromInstance() {
return classVariable;
}
```
Then, run the following:
```
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
```
Although `getClassVariableFromInstance` is an instance method, as can be seen by being invoked by referring to the instances `ac1` and `ac2`, they both return the same value, `42`. This is because in both instance methods, they refer to the class method `classVariable` which is unique to the class, not to the instance -- there is only a single copy of `classVariable` for the class `AnotherClass`.
I hope that some what clarifies what the `static` modifier is used for.
[The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) from Sun has a section called [Understanding Instance and Class Members](http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html), which also goes into the two types of variables and methods. | Please see a nice description on [Wikipedia](http://en.wikipedia.org/wiki/Method_(computer_science))
For example, notice how in the Math class, you can say things like
```
Math.Abs(x);
```
without having to say
```
Math m = new Math();
```
These are static methods since you don't need an instance. Instance methods are those methods that require you to have an instance of a class.
```
Employee e = new Employee();
e.Terminate();
``` | What is "static"? | [
"",
"java",
"static",
""
] |
I have an object Foo which has a global variable, Time currentTime
Foo has two methods which are called from different threads.
```
update()
{
currentTime = currentTime + timeDelay;
}
restart(Time newTime)
{
currentTime = newTime;
}
```
I am seeing behavior on a restart, the time changes correctly and other times where currentTime does not seem to reset (or it does reset but then update sets it back somehow.
The method update is called roughly every second or so while restart only occurs when a user initiates a restart event (presses a button). I think this is threading timing issue, any suggestions or comments on what is happening are welcome. | You certainly have a race condition here. The most straitforward solution is to protect the use of the shared variable `currentTime` by using a lock. I am using the Boost.Threads mutex class here:
```
class Foo
{
boost::mutex _access;
update()
{
boost::mutex::scoped_lock lock(_access);
currentTime = currentTime + timeDelay;
}
restart(Time newTime)
{
boost::mutex::scoped_lock lock(_access);
currentTime = newTime;
}
};
``` | Thread 1 calls update, gets a copy of currentTime and saves it in its thread local memory.
Thread 2 calls restart, sets currentTime to newTime. Thread 2 finishes.
Thread 1 continues, reassigns currentTime to the currentTime in its thread local memory (which is the old value of currentTime prior to your restart call) + the timeDelay. Thread 1 now finishes.
Hence your restart will have failed. There are many other situations which can occur resulting in unexpected behavior. Always synchronize variables shared amongst a different threads, to avoid such problems.
You should use a mutex suggested by others. | C++ Threading Question | [
"",
"c++",
"multithreading",
""
] |
I have the following two tables (simplified for this question):
```
CREATE TABLE team (
teamID CHAR(6) NOT NULL PRIMARY KEY);
CREATE TABLE member (
memberID CHAR(7) NOT NULL PRIMARY KEY,
teamID CHAR(6) NOT NULL REFERENCES team(teamID) );
```
I also have the following query, which is to list the number of members in each team:
```
SELECT teamID, count(memberID) AS [noOfMembers]
FROM member
GROUP by teamID;
```
However, I have four teams (MRT1, MRT2, MRT3 and MRT4). My members in my table only belong to teams 2 and 3, so when I run the query I get the following output:
MRT2: 7,
MRT3: 14
I'm not sure how I can adjust my query to list all 4 teams like so:
MRT1: 0,
MRT2: 7,
MRT3: 14,
MRT4: 0
I have been messing with subqueries to fix this without any luck. Any ideas? Thanks | try selecting from TEAM left JOIN-ing on Member
```
SELECT Team.Teamid, count(memberid)
FROM
TEAM
LEFT OUTER JOIN
Member on Member.teamid = Team.Teamid
GROUP by Team.Teamid
```
Just to give you some background as to what this is doing.
It says
> Give me all teamids from team and then for each one count the matches in the member table even if there are no matches.
if you use
```
SELECT Team.Teamid, count(memberid)
FROM
TEAM
INNER JOIN
Member on Member.teamid = Team.Teamid
GROUP by Team.Teamid
```
this translates to
> Give me all teamids from team and then for each one count the matches in the member table but only if there are matches. | ```
SELECT teamID, count(memberID) AS [noOfMembers]
FROM team
LEFT JOIN member
ON team.teamID = member.teamID
GROUP by teamID;
``` | Displaying zero-valued data in an SQL Query? | [
"",
"sql",
"select",
"count",
""
] |
I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.
One method would be creating an MP3 with a a single, fixed-frequency tone ([This can easily done by audacity](http://www.google.co.il/search?q=audacity+generate+tone&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a)), [opening it with a python library](https://stackoverflow.com/questions/307305/play-a-sound-with-python) and playing it repeatedly.
The second would be playing a sound using the computer built-in speaker. I'm looking for something similar to QBasic *Sound*:
```
SOUND 17000, 100
```
Is there a python library for that? | [PyAudiere](http://pypi.python.org/pypi/pyaudiere/) is a simple cross-platform solution for the problem:
```
>>> import audiere
>>> d = audiere.open_device()
>>> t = d.create_tone(17000) # 17 KHz
>>> t.play() # non-blocking call
>>> import time
>>> time.sleep(5)
>>> t.stop()
```
pyaudiere.org is gone. [The site](https://web.archive.org/web/20120221041148/http://pyaudiere.org/) and binary installers for Python 2 (debian, windows) are available via the wayback machine e.g., [here's source code `pyaudiere-0.2.tar.gz`](https://web.archive.org/web/20120221041148/http://pyaudiere.org/download.php?get=pyaudiere-0.2.tar.gz).
To support both Python 2 and 3 on Linux, Windows, OSX, [`pyaudio` module](https://pypi.python.org/pypi/PyAudio) could be used instead:
```
#!/usr/bin/env python
"""Play a fixed frequency sound."""
from __future__ import division
import math
from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio
try:
from itertools import izip
except ImportError: # Python 3
izip = zip
xrange = range
def sine_tone(frequency, duration, volume=1, sample_rate=22050):
n_samples = int(sample_rate * duration)
restframes = n_samples % sample_rate
p = PyAudio()
stream = p.open(format=p.get_format_from_width(1), # 8bit
channels=1, # mono
rate=sample_rate,
output=True)
s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples))
for buf in izip(*[samples]*sample_rate): # write several samples at a time
stream.write(bytes(bytearray(buf)))
# fill remainder of frameset with silence
stream.write(b'\x80' * restframes)
stream.stop_stream()
stream.close()
p.terminate()
```
Example:
```
sine_tone(
# see http://www.phy.mtu.edu/~suits/notefreqs.html
frequency=440.00, # Hz, waves per second A4
duration=3.21, # seconds to play sound
volume=.01, # 0..1 how loud it is
# see http://en.wikipedia.org/wiki/Bit_rate#Audio
sample_rate=22050 # number of samples per second
)
```
It is a modified (to support Python 3) version of [this AskUbuntu answer](https://askubuntu.com/a/455825/3712). | The module [winsound](http://docs.python.org/library/winsound.html) is included with Python, so there are no external libraries to install, and it should do what you want (and not much else).
```
import winsound
winsound.Beep(17000, 100)
```
It's very simple and easy, though is only available for Windows.
But:
A complete answer to this question should note that although this method will produce a sound, **it will not deter mosquitoes**. It's already been tested: see [here](https://biology.stackexchange.com/questions/2056/are-mosquitoes-repelled-by-high-frequency-sound) and [here](http://www.cbc.ca/news/high-frequency-mosquito-repellents-don-t-work-study-finds-1.658894) | Python library for playing fixed-frequency sound | [
"",
"python",
"audio",
"mp3",
"frequency",
""
] |
Are Session Beans (stateless session beans, stateful session beans) Synchronized? | Only one thread at a time will be accessing your beans. It is up to the application server to manage this. So you should not be using synchronized from within your beans. This is why a non-threadsafe like EntityManager can be an instance value and not have synchronization issues. | **Stateless beans**:
Every thread/request will get different instance of EJB from pool. SLB should not hold any user session data, any state. The same code may be executed in parallel. One instance is accessed by one thread at a time.
**Statefull beans** are synchronized for user session. Every user will get own session scoped instance. Second thread/request will wait until the first thread finishes. Statefull EJB can hold user specific data. One user cannot execute same code in parallel. Different users may execute same code in parallel.
If accessing a resource that does not allow parallel access use **Singleton EJB**. As name implies there is only one instance. By default EJB Singleton can be accessed only by one thread (Container Managed Concurrency and @Lock(WRITE)). | EJB and Synchronization | [
"",
"java",
"jakarta-ee",
"synchronization",
"ejb",
""
] |
I've a user control which contains asp:Literal.
```
<div>
<asp:Literal id="MenuContainer" runat="server" />
</div>
```
There is a method in code-behind page which initializes the control:
```
internal void Setup(MyBusinessObject obj)
{
MenuObject menu = MenuHelper.GetMenu(obj.State);
if(obj == null)
MenuContainer.Visible = false;
//other code
}
```
In the page where the control is used I call **Setup** method of control in **LoadComplete** event handler (I was first calling it in *Load* event). Irrespective of *MyBusinessObject* being null or not null, when I access *Literal* on user-control I get error:
```
Object reference not set to an instance of an object.
```
What is the reason and what is the remedy for this? | It was very simple. I was adding things in web.config's controls section as was suggested by [Rick Sthral](http://www.west-wind.com/weblog) in one of his post ( :( for got about the post, you will have to search on his page).
It was nicely allowing me to add controls without putting **@ Register** tag but the downside was that child controls on my controls were shown as null! so I simply put **@ Register** directive in my pages and it worked. | It depends on exactly *how* you're including the controls in your web.config. It will not work if you try to include all of the controls in a namespace (although the designer will correctly show you the list of your controls):
```
<add tagPrefix="prefix" namespace="example.ui.controls" assembly="example.ui" />
```
But if you add your control(s) individually and point to their physical location(s), it will work as you expect without having to include endless `@Register` directives.
```
<add tagPrefix="prefix" tagName="Message" src="~/Controls/Message.ascx" />
``` | asp:Literal control null in user control | [
"",
"c#",
"asp.net",
"user-controls",
""
] |
I'm just wondering what's more costly, something like:
```
echo "Hello world, my name is $name";
```
or
```
echo 'Hello world, my name is '.$name;
```
I know in this case it wouldn't make much difference, but maybe here it would:
```
for($i = 0; $i < 10000; $i++)
{
echo 'Hello world, my name is '.$name;
}
```
Thanks in advance! | Personally, I would use:
```
echo 'Hello ' , $name;
```
[echo](http://php.net/echo) takes multiple arguments, so there is no need to concatenate for something like this.
Here is a [benchmark](http://www.phpbench.com/) that shows the difference between ' and " (virtually none). However, " allows for escape sequences (\n, etc), and variable expansion.
This type of thing is a micro-optimization and you shouldn't worry about it. See the following threads about optimization:
[How important is optimization?](https://stackoverflow.com/questions/710263/how-important-is-optimization)
<https://stackoverflow.com/questions/127765/php-optimization-tips>
[Optimizing PHP string concatenation](https://stackoverflow.com/questions/416914/optimizing-php-string-concatenation) | See the "string output" section of [The PHP Benchmark](http://phpbench.com/)...
Or just write a few crappy microtime loops and test them for yourself.
```
ob_start();
$s = microtime(true);
for ($i=0; $i<10000; $i++)
echo 'Hello world, my name is '.$i."\n";
$end = microtime(true) - $s;
ob_end_clean();
echo $end;
``` | PHP "" vs '' | [
"",
"php",
""
] |
I am currently refactoring a large Java application. I have split up one of the central (Eclipse) projects into about 30 individual "components", however they are still heavily inter-dependent. In order to get a better idea of what depends on what I am looking for some way to graph the compile time dependencies.
All tools I have found so far are capable of graphing package or class dependencies or the dependencies between Eclipse plugins, however what I have in mind should just take a look at the classpath settings for each Eclipse project and build a coarser grained graph from that.
Later I will then go deeper, however right now this would just mean I would not be able to see the forest for all of the trees. | [Structure101](http://structure101.com/products/structure101/index.php) is capable of visualizing class and method JAR level dependencies in Jboss 5.
See the screenshot below or [view it larger.](http://structure101.com/images/jboss5-jar-dependencies.jpg)
[](https://i.stack.imgur.com/6B7qv.jpg) | Check out [JBoss Tattletale](http://www.jboss.org/tattletale). It might not do all you ask but it's worth checking out. It's still relatively new though.
The tool will provide you with reports that can help you
* Identify dependencies between JAR files
* Find missing classes from the classpath
* Spot if a class is located in multiple JAR files
* Spot if the same JAR file is located in multiple locations
* With a list of what each JAR file requires and provides
* Verify the SerialVersionUID of a class
* Find similar JAR files that have different version numbers
* Find JAR files without a version number
* Locate a class in a JAR file
* Get the OSGi status of your project
* Remove black listed API usage | How can I visualize jar (not plugin) dependencies? | [
"",
"java",
"eclipse",
"graph",
"dependencies",
"visualization",
""
] |
I'm trying to deploy a website using ASP.NET membership and the hosting company is godaddy. Problem is that for some reason an error is being thrown when I log in. I've modified some pages for testing purposes to see if I can pull data from the database and it works fine. So I know it's mapping to the proper source. The error I'm receiving is the following:
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
Any help would be much appreciated. | It sounds like something is using the LocalSqlServer automagic connection string still. I'd add`<remove name="LocalSqlServer />` to your `<connectionStrings>` and see what blows up. | When you setup membership it normally adds another connection string to your web.config. I think it creates a key in the web.config called ApplicationServices that contains the connection string that the membership classes will use (I think this depends on what membership provider you are using). When you checked the connectionstring did you also check that one? | Deploying ASP.NET membership to Godaddy | [
"",
"c#",
"asp.net",
"membership",
""
] |
I have a canvas object and I am sprinkling fantastic controls all over it. I'm using a ScaleTransform object to scale the canvas so I can zoom in/out.
I have wired up the controls so that I can drag them around, and the drag and drop works well by using MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove. Now, I want to work on enabling an event when I click only on the Canvas. When I read the [docs](http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas_events(VS.95).aspx) for the canvas object, I see that the MouseLeftButtonDown event only fires when it's over a UIElement.
> Occurs when the left mouse button is
> pressed (or when the tip of the stylus
> touches the tablet PC) while the mouse
> pointer is over a UIElement.
> (Inherited from UIElement.)
Unfortunately, I want the *opposite* behavior. I want to know when the mouse is clicked on the Canvas while the mouse pounter isn't over any controls. Since I'm new to Silverlight, I could be doing this the wrong way. Is there something I have overlooked? Am I going about this the wrong way? I'm looking for a little help, and perhaps a lot of direction. | I'm no Silverlight guru, but could you add a transparent `UIElement` to the `Canvas`, below all other `UIElement`s, and use it to determine if the user has clicked outside of any of the other drag/drop-able elements. | You want to know when a click happens on the `Canvas` and isn't over other controls?
The most natural thing is to capture the `Canvas`'s `MouseLeftButtonDown`. Inside of that event, take a peak to see where the click happened. Then peak at the `UIElement`s under the click. I recommend you keep everything in absolute coordinates to keep things straight. Something like:
```
void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point p = e.GetPosition(null);
var elements = VisualTreeHelper.FindElementsInHostCoordinates(p, App.Current.RootVisual);
foreach (var element in elements)
{
//Figure out if you're over a particular UI element
}
}
``` | Canvas Click events in Silverlight when not over a UIElement | [
"",
"c#",
"silverlight",
"canvas",
"click",
"uielement",
""
] |
How can i change dateformat?Forexample:
2009-06-10 10:16:41.123
->2009-June
2009-05-10 10:16:41.123
->2009-May | Try this:
```
select cast(datepart(year, mydatecolumn) as char(4)) + '-'
+ datename(month, mydatecolumn)
from mytable
``` | You should not change the date-format in your database.
You should just make sure that , when displaying the date, you correctly format the date, so that you display them in the format that you want.
How to do that, is related to the language you use in your program.
You can also output the date directly in the format you want using the method of ck. | How can i change datetime format in sql? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
Is there a simple way to get a system's uptime using C#? | ```
public TimeSpan UpTime {
get {
using (var uptime = new PerformanceCounter("System", "System Up Time")) {
uptime.NextValue(); //Call this an extra time before reading its value
return TimeSpan.FromSeconds(uptime.NextValue());
}
}
}
``` | I'm a bit late, but another *simple* way is to use the [GetTickCount64](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724411%28v=vs.85%29.aspx) function, which is available starting with Windows Vista and does not overflow as GetTickCount does:
```
public static TimeSpan GetUpTime()
{
return TimeSpan.FromMilliseconds(GetTickCount64());
}
[DllImport("kernel32")]
extern static UInt64 GetTickCount64();
``` | Retrieve system uptime using C# | [
"",
"c#",
".net",
"windows",
"uptime",
""
] |
I Just can't seem to wrap my head around them.
As I understand it's dynamically adding logic to a class. Are classes within the framework prepared for this?
Why should I just extend the class and add the functionality to it in the extension. I would be globally accessible and afaik much easier to maintain.
I've Read there are 4 functor types:
Comparer
Closure
Predicate
Transformer
We should probably Handle each one of them.
p.s. is there something like it in vb?
So I can state I think that lambda expressions are functors. This clears up things for me a bit :) (hehe)
* Lambda expressions are functors?
* Anonymous functions are functors?
But I asked this question because I ran into another type of fucntors namely these ones:
```
delegate void FunctorDelegate(int value);
class Addition {
FunctorDelegate _delegate;
public Addition AddDelegate(FunctorDelegate deleg) {
_delegate += deleg;
return this;
}
public int AddAllElements(IList< int> list) {
int runningTotal = 0;
foreach( int value in list) {
runningTotal += value;
_delegate(value);
}
return runningTotal;
}
}
```
And then calling it with this:
```
int runningTotal = new Addition()
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 1) {
runningOddTotal += value;
}
}))
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 0) {
runningEvenTotal += value;
}
}))
.AddAllElements(list);
```
So no fancy lambda style things.
Now I have this example but it isn't at all clear why this is a "good" solution.
**Are delegates (functors) used as lambda expressions or anonymous methods "in most cases" just there as a shortcut for the programmer? There are as far as I can see only a few cases where they're actually the prefered choice for a problem.** | I think you're confusing terms from different languages. You seem to be using "Functor" in the C++ or Java sense, e.g. [see the wikipedia page](http://en.wikipedia.org/wiki/Function_object). In C++, it's an object of a class that overloads the function-call operator, so it can be used as a function but with state.
This is logically the same thing as a delegate bound to an instance method in C# (or any .NET language).
There are three ways to write such a thing. First, you can write an ordinary method, and then assign the name of the method to a delegate variable.
```
void MyMethod() { Console.WriteLine("Hi!"); }
void Foo()
{
Action a = MyMethod;
a();
}
```
Second, you can use anonymous method syntax, introduced in C# 2.0:
```
void Foo()
{
Action a = delegate { Console.WriteLine("Hi!"); }
a();
}
```
Thirdly, you can use lambda syntax, introduced in C# 3.0:
```
void Foo()
{
Action a = () => Console.WriteLine("Hi!");
a();
}
```
The advantage of the last two is that the body of the method can read and write local variables in the containing method.
The advantage of lambda syntax over anon-methods are that it is more succinct and it does type inference on parameters.
**Update:** The advantage of anon-methods (`delegate` keyword) over lambdas is that you can omit the parameters altogether if you don't need them:
```
// correct way using lambda
button.Click += (sender, eventArgs) => MessageBox.Show("Clicked!");
// compile error - wrong number of arguments
button.Click += () => MessageBox.Show("Clicked!");
// anon method, omitting arguments, works fine
button.Click += delegate { MessageBox.Show("Clicked!"); };
```
I know of only one situation where this is worth knowing, which is when initializing an event so that you don't have to check for `null` before firing it:
```
event EventHandler Birthday = delegate { };
```
Avoids a lot of nonsense elsewhere.
Finally, you mention that there are four kinds of functor. In fact there are an infinity of possibly delegate types, although some authors may have their favourites and there obviously will be some common patterns. An `Action` or `Command` takes no parameters and returns `void`, and a predicate takes an instance of some type and returns `true` or `false`.
In C# 3.0, you can whip up a delegate with up to four parameters of any types you like:
```
Func<string, int, double> f; // takes a string and an in, returns a double
```
**Re: Updated Question**
You ask (I think) if there are many use cases for lambdas. There are more than can possibly be listed!
You most often see them in the middle of larger expressions that operate on sequences (lists computed on-the-fly). Suppose I have a list of people, and I want a list of people exactly forty years old:
```
var exactlyForty = people.Where(person => person.Age == 40);
```
The `Where` method is an extension method on the `IEnumerable<T>` interface, where `T` in this case is some kind of `Person` class.
This is known in .NET as "Linq to Objects", but known elsewhere as pure functional programming on sequences or streams or "lazy" lists (all different names for the same thing). | In .NET terms, I *think* what you are describing is the `Delegate` - and it exists in all of .NET, not just C#.
I'm not sure that a "closure" would a "type" in the same was as a comparer/predicate/transformer, since in C# terms a closure is simply an implementation detail but can **be** any of those three.
In .NET, delegates are used in two main ways:
* as the eventing mechanism
* to provide functional-style programming
The first is important, but it sounds like you are more interested in the second. In reality, they operate much like single-method interfaces... consider:
```
List<int> vals = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenVals = vals.FindAll(i => i % 2 == 0); // predicate
List<string> valsAsStrings = vals.ConvertAll(i => i.ToString()); // transformer
// sort descending
vals.Sort((x, y) => y.CompareTo(x)); // comparer
```
A closure is more where we bring additional scope from **outside** the delegate *into* the delegate:
```
int max = int.Parse(Console.ReadLine()); // perhaps 6
List<int> limited = vals.FindAll(i => i <= max);
```
here the `max` is captured into the delegate as a closure.
Re "Are classes within the framework prepaired for this?" - many are, and LINQ goes a *long* way to allowing this even wider. LINQ provides extension methods over (for example) all of `IEnumerable<T>` - meaning that collections *without* delegate-based access aquire them for free:
```
int[] data = { 1,2,3,4,5,6,7,8,9 };
var oddData = data.Where( i => i % 2 == 1 );
var descending = data.OrderBy(i => -i);
var asStrings = data.Select(i => i.ToString());
```
Here the `Where` and `OrderBy` methods are LINQ extension methods that take delegates. | Functors when should I use them whats their intended use | [
"",
"c#",
".net",
"generics",
"lambda",
"functor",
""
] |
I am looking for a scripting language that meets the following criteria:
* Well Documented
* Implemented in Java
* Understands Datatypes (can handle longs, strings, etc)
* Is fully extensible
Any suggestions? Currently, I'm using Javascript, but the Doubles that it sets numbers to is not big enough for the data work I'm doing.
Thanks! | [Groovy](http://groovy.codehaus.org)
In particular, Groovy *can* be used as a scripting language, but doesn't have to be, and is built on top of Java. It isn't a Java port of a different language, which means it integrates more closely with Java than JRuby/Jython, although that may have changed since I last looked at them.
As for documentation for Groovy, you may want to buy [Groovy in Action](https://rads.stackoverflow.com/amzn/click/com/1932394842) (plug plug ;) | Python and Ruby have Java implementations (look for Jython and JRuby). | What is a scripting language that understands datatypes and can be implemented in Java? | [
"",
"java",
"scripting",
"etl",
""
] |
Suppose I have the following class:
```
public class FixExpr {
Expr<FixExpr> in;
}
```
Now I want to introduce a generic argument, abstracting over the use of Expr:
```
public class Fix<F> {
F<Fix<F>> in;
}
```
But Eclipse doesn't like this:
> The type F is not generic; it cannot be parametrized with arguments <Fix<F>>
Is this possible at all or have I overlooked something that causes this specific instance to break?
Some background information: in Haskell this is a common way to write generic functions; I'm trying to port this to Java. The type argument F in the example above has kind \* -> \* instead of the usual kind \*. In Haskell it looks like this:
```
newtype Fix f = In { out :: f (Fix f) }
``` | I think what you're trying to do is simply not supported by Java generics. The simpler case of
```
public class Foo<T> {
public T<String> bar() { return null; }
}
```
also does not compile using javac.
Since Java does not know at compile-time what `T` is, it can't guarantee that `T<String>` is at all meaningful. For example if you created a `Foo<BufferedImage>`, `bar` would have the signature
```
public BufferedImage<String> bar()
```
which is nonsensical. Since there is no mechanism to force you to only instantiate `Foo`s with generic `T`s, it refuses to compile. | Maybe you can try Scala, which is a functional language running on JVM, that supports higher-kinded generics.
---
**[ EDIT by [Rahul G](https://stackoverflow.com/users/192247/missing-faktor) ]**
Here's how your particular example roughly translates to Scala:
```
trait Expr[+A]
trait FixExpr {
val in: Expr[FixExpr]
}
trait Fix[F[_]] {
val in: F[Fix[F]]
}
``` | Higher-kinded generics in Java | [
"",
"java",
"generics",
"haskell",
"polymorphism",
"higher-kinded-types",
""
] |
I'm using Antenna to build, pack and obfuscate a j2me app.
Building and packing works fine.
The project uses a 3rd party jar that is already obfuscated except by some interfaces.
When trying to obfuscate I got several errors like:
```
[wtkobfuscate] Warning: i: can't find referenced class fooPackage.fooClass
```
Class i and fooPackage.fooClass is from this 3rd party jar that I mentioned.
**UPDATE**:
This 3rd party library uses j2me-xmlrpc.jar. If I don't package all together then I won't be able to obfuscate the 3rd party interfaces and the j2me-xmlrpc.jar. (and I can't run the app this way, not sure why)
If I package only the j2me-xmlrpc.jar and my project classes I get the this error while obfuscating
```
[wtkobfuscate] Warning: there were 2 instances of library classes depending on program classes.
```
**UPDATE 2:**
I know this obfuscation is possible beacause in Netbeans I can do obfuscation using Proguard.
Since Netbeans internals uses ANT to make builds I tried to copy the generated build.xml to my own build.xml.
For obfuscation Netbeans uses the library org-netbeans-modules-mobility-antext.jar that can be used outside Netbeans. I imported this library to my project and used it without problem.
But I get the same error I got using antenna.
Obfuscating in Netbeans generates a lot of warnings but it still generates the obfuscated jar.
What I'm missing? | I was using Proguard 4.3. Downgrading to Proguard 4.2 solved the problem. | If the 3rd party library is obfuscated, don't include that library while you obfuscate your classes. Rather follow these steps
1. Jar your classes alone (dont include 3rd party library)
2. Obfuscate the jar obtained in step 1
3. Unjar the obfuscated jar obtained in step 2 and the 3rd party library in some temp folder
4. Jar all the unjared classes
5. Preverify and package them again | Trouble making obfuscation | [
"",
"java",
"ant",
"java-me",
"obfuscation",
"proguard",
""
] |
I am confused about the connection string format of ADO.Net when connect to a non-default instance of SQL Cluster. I did search but find various samples, could anyone let me know what is the correct format please (if I know the virtual server name and instance name)? I am using trusted connection.
thanks in advance,
George | ServerName\InstanceName ? Use double \ when handling strings in C# | See <http://www.connectionstrings.com/> - great site for making DB connection strings. | connection string of ADO.Net of SQL Server | [
"",
"sql",
"string",
"ado.net",
"connection",
"cluster-computing",
""
] |
Over the past couple of days I have been reading into using *autotools* to build my project instead of the Makefiles I have pieced together over the past couple of months. Unfortunately I have not found an example that gave me enough insight towards how my project structure is currently.
I have three libraries that are included in the application code of my project. I am looking for the best way to use a single configure script to make (and install) the application, and libraries. | Here are a few I found that don't look to bad:
1. <http://www.lrde.epita.fr/~adl/autotools.html>
2. <http://www.developingprogrammers.com/index.php/2006/01/05/autotools-tutorial/>
3. <http://sources.redhat.com/autobook/>
The last one is a free book
**Good Luck** | Sorry for offtopic.
I did similar thing now, but I was able to choose between Autotools and CMake. I am happy to have choosen the second.
Might be worth looking at, including CDash, CTest and CPack.
<http://www.cmake.org/>
Best Regards,
Ovanes | Refactoring build system to use Autotools | [
"",
"c++",
"c",
"autotools",
"autoconf",
"automake",
""
] |
I'm trying to pass a username and password variable to the twitter credentials but it keeps returning that I'm not authenticated. However, when I use the actual username and password, instead of the variables, it successfully authorizes.
```
$username = $_POST["username"];
$password = $_POST["password"];
$url = "http://search.twitter.com/search.atom?q=golf&show_user=true&rpp=100";
$search = file_get_contents($url);
$regex_name = '/\<name\>(.+?) \(/';
preg_match_all($regex_name,$search,$user);
for($i=0;$user[1][$i];$i++)
{
$follow = $user[1][$i];
define('TWITTER_CREDENTIALS', '$username:$password');
$url = "http://twitter.com/friendships/create/".$follow.".xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, TWITTER_CREDENTIALS);
$result= curl_exec ($ch);
curl_close ($ch);
```
I'm thinking it has something to do with the colon in between the username and password, or perhaps trying to use variables within define function.
Any clues? | ```
$username = $_POST["username"];
$password = $_POST["password"];
// INCORRECT. Will literary assign TWITTER_CREDENTIALS as $username:$password
// define('TWITTER_CREDENTIALS', '$username:$password');
// CORRECT, will parse the variables and assign the result to TWITTER_CREDENTIALS
define('TWITTER_CREDENTIALS', "$username:$password");
```
Remember strings with double quotes (") parse variables in the string, strings with single quotes (') do not.
Read more about strings in PHP:
* [PHP strings](http://se.php.net/manual/en/language.types.string.php)
* [Variable parsing in PHP strings](http://se.php.net/manual/en/language.types.string.php#language.types.string.parsing)
* [PHP string functions](http://se.php.net/manual/en/ref.strings.php) | it has something to do with using single quotes instead of double quotes. | Twitter API Error using variables within php DEFINE | [
"",
"php",
"twitter",
""
] |
I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.
loop.py:
```
#! /usr/bin/env python
if __name__ == "__main__":
try:
print 'starting loop'
while True:
pass
except KeyboardInterrupt:
print 'quitting loop'
```
From the shell I can interrupt it:
```
$ python loop.py &
[1] 15420
starting loop
$ kill -SIGINT 15420
quitting loop
[1]+ Done python loop.py
```
kill.sh:
```
#! /bin/bash
python loop.py &
PID=$!
echo "sending SIGINT to process $PID"
kill -SIGINT $PID
```
But from a script I can't:
```
$ ./kill.sh
starting loop
sending SIGINT to process 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3 R 0:08 python loop.py
```
And, if it's been launched from a script I can no longer kill it from the shell:
```
$ kill -SIGINT 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3 R 0:34 python loop.py
```
I'm assuming I'm missing some fine point of bash job control. | You're not registering a signal handler. Try the below. It seems to work fairly reliably. I think the rare exception is when it catches the signal before Python registers the script's handler. Note that KeyboardInterrupt is only supposed to be raised, "when the user hits the interrupt key". I think the fact that it works for a explicit (e.g. via kill) SIGINT at all is an accident of implementation.
```
import signal
def quit_gracefully(*args):
print 'quitting loop'
exit(0);
if __name__ == "__main__":
signal.signal(signal.SIGINT, quit_gracefully)
try:
print 'starting loop'
while True:
pass
except KeyboardInterrupt:
quit_gracefully()
``` | In addition to @matthew-flaschen's answer, you can use `exec` in the bash script to effectively replace the scope to the process being opened:
```
#!/bin/bash
exec python loop.py &
PID=$!
sleep 5 # waiting for the python process to come up
echo "sending SIGINT to process $PID"
kill -SIGINT $PID
``` | How to send a SIGINT to Python from a bash script? | [
"",
"python",
"bash",
""
] |
I know it's possible to make a template function:
```
template<typename T>
void DoSomeThing(T x){}
```
and it's possible to make a template class:
```
template<typename T>
class Object
{
public:
int x;
};
```
but is it possible to make a class not within a template, and then make a function in that class a template? Ie:
```
//I have no idea if this is right, this is just how I think it would look
class Object
{
public:
template<class T>
void DoX(){}
};
```
or something to the extent, where the class is not part of a template, but the function is? | Your guess is the correct one. The only thing you have to remember is that the member function template *definition* (in addition to the declaration) should be in the header file, not the cpp, though it does *not* have to be in the body of the class declaration itself. | See here: [Templates](http://www.cs.otago.ac.nz/postgrads/alexis/tutorial/node39.html), [template methods](http://www.cs.otago.ac.nz/postgrads/alexis/tutorial/node42.html),Member Templates, Member Function Templates
```
class Vector
{
int array[3];
template <class TVECTOR2>
void eqAdd(TVECTOR2 v2);
};
template <class TVECTOR2>
void Vector::eqAdd(TVECTOR2 a2)
{
for (int i(0); i < 3; ++i) array[i] += a2[i];
}
``` | How to create a template function within a class? (C++) | [
"",
"c++",
"templates",
"function",
"class",
""
] |
I am using the singleton pattern in a wpf app, but having doubts about how to make it work with multiple threads.
I have a class called Monitor which maintains a list of "settings" to watch, for different "devices". Outline shown below.
On my main thread I am doing
Monitor.getMonitor.register(watchlist) or Monitor.getMonitor.unregister(...) depending on the user input and I have a DispatchTimer running every 200ms that does a
Monitor.getMonitor.update()
```
public class Monitor
{
private Hashtable Master; //key=device, value=list of settings to watch
private static Monitor instance = new Monitor();
private Monitor() {}
public static Monitor getMonitor()
{
return instance;
}
public void register(watchlist){...}
public void unregister(...){...}
public void update(){...}
}
```
register()/unregister() perform add/remove to the hastable.
update() is only reading stuff out of the hashtable.
Depending on the number of devices and settings, update() is going to be iterating over the hastable and it contents, getting the latest values.
The main thread maybe calling register and unregister quite often and I want the gui to stay responsive. Whats a good way to do this?
Do I lock the hashtable, around add/remove and iterate, OR just surrond the iteration part in update with a try catch (ala gracefully fail) to catch any weird state the hashtable might get into(no locking) or is there some better way to do this (if update fails no prob..its going to be running in 200ms again anyway).
Not very sure about what is going on, cause the code as is hasnt really shown any problems which itself is making me a bit uneasy cause it just seems wrong. Thanks for any suggestions... | See my [article on singleton implementations](http://pobox.com/~skeet/csharp/singleton.html) to make the singleton fetching itself threadsafe.
Yes, you'll need to lock when you modify *or* iterate over the hashtable. You could use a [`ReaderWriterLock`](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx) (or preferrably [`ReaderWriterLockSlim`](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx) in .NET 3.5) to allow multiple readers at a time. If you need to do a lot of work while you're iterating, you could always lock, take a copy, unlock, and then work on the copy - so long as the work doesn't mind the copy being slightly stale.
(If you're using .NET 2.0+, I'd suggest using the generic collections such as `Dictionary<TKey, TValue>` instead of `Hashtable`. I'd also suggest you rename your methods in line with .NET conventions. That code's got a distinct Java accent at the moment ;) | Yes, you should lock each operation:
```
public class Monitor
{
private Hashtable Master; //key=device, value=list of settings to watch
...
private object tableLock = new object();
public void register(watchlist)
{
lock(tableLock) {
// do stuff
}
}
}
```
You shouldn't consider using a try/catch block - exceptions shouldn't be considered as a "normal" situation, and you might end up with a corrupted object state without any exception. | C# working with singleton from two different threads | [
"",
"c#",
"multithreading",
"singleton",
""
] |
I have looked and looked and tried to find an answer for what I've been looking for, but I have yet to see an answer for this:
I am trying to generate a Wordpress loop that takes all the posts from a single category and displays them three at a time inside `<li></li>` tags.
Output should look like this:
```
<li>My post title | Another Title | Third title</li>
<li>The next post title | A different post | Post #6</li>
<li>And so on | And so forth</li>
```
I need this to loop through all the entries in the category until finished, and then exit the loop.
My code is completely non-working at this point, but I've provided what I'm working with below. If anyone has any solution to this, I'd love to give mad props to you, as this has hounded me for three days without any solution so far.
```
<?php // Loop through posts three at a time
$recoffsetinit = '0';
$recoffset = '3';
query_posts('cat=1&showposts=0');
$post = get_posts('category=1&numberposts=3&offset='.$recoffsetinit.');
while (have_posts()) : the_post();
?>
<li>
<?php
$postslist = get_posts('cat=1&order=ASC&orderby=title');
foreach ($postslist as $post) : setup_postdata($post);
static $count = 0; if ($count == "3") { break; } else { ?>
<a href="<?php the_permalink() ?>"></a>
<?php $count++; } ?>
<?php endforeach; ?>
<?php $recoffsetinit = $recoffset + $recoffsetinit; ?>
</li>
<?php endwhile; ?>
``` | No wordpress to test with, and no time, but something like this might be a better way of going about it?
```
<?php
$postList = get_posts('cat=1&order=ASC&orderby=title');
$postsPerLine = 3;
echo "<ul>";
echo buildPosts($postList, $postsPerLine);
echo "</ul>";
function buildPosts($list, $perLine) {
$out = '';
$currentPostNumber = 0;
foreach ($list as $post) {
if ($currentPostNumber == 0) {
$out .= '<li>';
}
$out .= "<a href='" . the_permalink() . "'></a> ";
$currentPostNumber++;
if ($currentPostNumber <= $perLine) {
$currentPostNumber = 0;
$out .= '</li>';
}
}
return $out;
}
?>
``` | I hacked up your solution to make it work. It took a little doing, since my code-fu is not what you'd call "good." Here's the solution:
```
<ul>
<?php
query_posts('category=1&showposts=0');
$posts = get_posts('category_name=my_cat&order=ASC&orderby=title&numberposts=0');
$postsPerLine = 3;
$currentPostNumber = 0;
foreach ($posts as $post) :
if ($currentPostNumber == 0) {
echo '<li>';
}
?>
<a href="<?php the_permalink(); ?>"></a>
<?php
$currentPostNumber++;
if ($currentPostNumber >= $postsPerLine) {
$currentPostNumber = 0;
echo '</li>';
}
endforeach;
?>
</ul>
```
Thanks for the input! | Looping Through Set Number of Posts in Wordpress, Then running same loop again on next set, etc | [
"",
"php",
"wordpress",
"loops",
"nested-loops",
""
] |
In Fusion charts 3.0 they have option to save the graph as PNG. But it is only for licensed users. But they don't have that option for free users. My requirement is to save it as an image somehow. Is it possible in the free version. To achieve that what am I supposed to do. Is there any mechanism ( 3rd party tool ) to convert flash into PNG.
Thanks
`Shafi | See this: [DisplayObject to JPEG or PNG with IImageEncoder](http://blog.tsclausing.com/post/21) | Use your OS's built-in screen capture facility.
* Windows: Alt+PrintScreen - captures to clipboard
* Mac OS X: Command+Ctrl+Shift+3 - captures to clipboard
* Mac OS X 10.4+: Command+Shift+4 - captures to PNG file on your desktop
* don't know about other platforms
After capturing to the clipboard, you can use almost any graphics app to save it as a PNG. | Saving flash chart to png | [
"",
"javascript",
"flash",
"png",
""
] |
> **Possible Duplicate:**
> [In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown ?](https://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try-catch-finally-if-an-unhandled)
Will finally be executed in this scenario (in C#)?
```
try
{
// Do something.
}
catch
{
// Rethrow the exception.
throw;
}
finally
{
// Will this part be executed?
}
``` | Yes, finally is always executed.
A simple example for demonstrating the behaviour:
```
private void Button_Click(object sender, EventArgs e)
{
try
{
ThrowingMethod();
}
catch
{
}
}
private void ThrowingMethod()
{
try
{
throw new InvalidOperationException("some exception");
}
catch
{
throw;
}
finally
{
MessageBox.Show("finally");
}
}
``` | (Edit: Clarifications from comments incorporated - thanks guys)
Finally is always executed. The only exceptions I know of are;
* You pull the power plug
* If a thread that is running as "background" is terminated because the main program to which it belongs is ending, the finally block in that thread will not be executed. See [Joseph Albahari](http://www.albahari.com/threading/#_Creating_Starting).
* Other async exceptions like stackoverflows and out-of-memory. See [this question](https://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try-catch-finally-if-an-unhandled).
Most of the scenarios where Finally is not executed has to do with catastrohic failure, with the exception of the background thread one, so it is worth being aware of that one in particular. | Exception inside catch block | [
"",
"c#",
""
] |
Consider the following classes:
```
class TypeA;
class TypeB : TypeA;
class TypeC : TypeA;
class TypeD : TypeA;
```
and the following List<> types:
```
List<TypeB> listTypeB;
List<TypeC> listTypeC;
List<TypeD> listTypeD;
```
Now TypeA has a property Prop1 of type Object1 and I want to locate which list has stored within it an item with Prop1 of a given value. Is there a way in which I can do something like the following, so that I only need to write the search code once?
```
bool LocateInAnyList(Object1 findObj)
{
bool found = false;
found = ContainsProp1(findObj, listTypeB);
if(!found)
{
found = ContainsProp1(findObj, listTypeC);
}
if(!found)
{
found = ContainsProp1(findObj, listTypeD);
}
return found;
}
bool ContainsProp1(Object1 searchFor, List<TypeA> listToSearch)
{
bool found = false;
for(int i = 0; (i < listToSearch.Count) & !found; i++)
{
found = listToSearch[i].Prop1 == searchFor;
}
return found;
}
``` | You can use generic
```
bool ContainsProp1<T>(Object1 searchFor, List<T> listToSearch) where T : TypeA
{
bool found = false;
for(int i = 0; (i < listToSearch.Count) & !found; i++)
{
found = listToSearch[i].Prop1 == searchFor;
}
return found;
}
```
If you can use linq, your code can be more clear than that. | Yes. You'll need to make the "contains" method generic, with a constraint so that you can operate only on objects that derive from `TypeA` (and thus have a `Prop1`:)
```
bool ContainsProp1<T>(Object1 searchFor, List<T> listToSearch) where T : TypeA
{
bool found = false;
for(int i = 0; (i < listToSearch.Count) & !found; i++)
{
found = listToSearch[i].Prop1 == searchFor;
}
return found;
}
```
Your first method should then compile as-is. | Passing and processing List<> types containing objects of the same base type | [
"",
"c#",
"inheritance",
"collections",
""
] |
To return a double, do I have to cast to double even if types are double?
e.g.
```
double a = 32.34;
double b = 234.24;
double result = a - b + 1/12 + 3/12;
```
Do I have to cast (double) ? | No, you don't. However, your expression almost certainly doesn't do what you want it to.
The expressions 1/12 and 3/12 will be performed using *integer* arithmetic.
You probably want:
```
double result = a - b + 1/12d + 3/12d;
```
or
```
double result = a - b + 1/(double) 12 + 3/(double) 12;
```
Both of these will force the division to be performed using floating point arithmetic.
The problem here is that if both operands of an arithmetic operator are integers, then the operation is performed using integer arithmetic, *even if it's part of a bigger expression which is of type `double`*. Here, your expression is effectively:
```
double result = a - b + (1 / 12) + (3 / 12);
```
The addition and subtraction is okay, because the types of `a` and `b` force them to be performed using floating point arithmetic - but because division "binds more tightly" than addition and subtraction (i.e. it's like using the brackets above) only the immediate operands are considered.
Does that make sense?
EDIT: As it's so popular, it makes sense to include devinb's comment here too:
```
double result = a - b + 1.0/12.0 + 3.0/12.0;
```
It's all the same thing as far as the compiler is concerned - you just need to decide which is clearer for you:
```
(double) 1
1.0
1d
``` | Nope, no casting is needed. | To return a double, do I have to cast to double even if types are double in c#? | [
"",
"c#",
"casting",
""
] |
I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run.
My code looks like this:
```
for top, bottom in izip(table[::2], table[1::2]):
#do something with top
#do something else with bottom
```
How to make this code less ugly? Or maybe is it good way to do this?
EDIT:
```
table[1::2], table[::2] => table[::2], table[1::2]
``` | Try:
```
def alternate(i):
i = iter(i)
while True:
yield(i.next(), i.next())
>>> list(alternate(range(10)))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
```
This solution works on any sequence, not just lists, and doesn't copy the sequence (it will be far more efficient if you only want the first few elements of a long sequence). | `izip` is a pretty good option, but here's a few alternatives since you're unhappy with it:
```
>>> def chunker(seq, size):
... return (tuple(seq[pos:pos+size]) for pos in xrange(0, len(seq), size))
...
>>> x = range(11)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> chunker(x, 2)
<generator object <genexpr> at 0x00B44328>
>>> list(chunker(x, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10,)]
>>> list(izip(x[1::2], x[::2]))
[(1, 0), (3, 2), (5, 4), (7, 6), (9, 8)]
```
As you can see, this has the advantage of properly handling an uneven amount of elements, which may or not be important to you. There's also this recipe from the [itertools documentation itself](http://docs.python.org/library/itertools.html#recipes):
```
>>> def grouper(n, iterable, fillvalue=None):
... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
... args = [iter(iterable)] * n
... return izip_longest(fillvalue=fillvalue, *args)
...
>>>
>>> from itertools import izip_longest
>>> list(grouper(2, x))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)]
``` | concurrently iterating through even and odd items of list | [
"",
"python",
"for-loop",
"python-itertools",
""
] |
hi i am working on a window application using c#,
i want to know that how to monitor computer activity by internet activity or website.. | You may want to check out 'packet sniffing' tools, for example [Ethereal](http://www.ethereal.com/) or [TCPDump](http://en.wikipedia.org/wiki/Tcpdump) - they are open source and have command-line interfaces, so you may be able to call those from your program and analyse any log files it may produce. Packet sniffers scan your network for packets being sent around, internet activity will typically invlve TCP and IP packets so you could filter for those and look at where they have been sent from / where they are going to. | you can use sharpPcap, it's a packet capture framework for .Net
the library has a lot of useful functions for monitoring packets,
you can filter HTTP packets. | monitoring internet activity? | [
"",
"c#",
""
] |
Not sure if you guys are familiar with [YUI Uploader](http://developer.yahoo.com/yui/uploader/), but after you click "browse" and select a bunch of files, the callback event returns a list of *all* the files that are queued, not just the ones you just finished selecting. This poses a bit of a problem because now instead of just adding the selected files to the UI, you have to clear the list and re-add them all. You can't even compute the difference between the existing files, and all the files, because their file id's are randomly changed too, as with the order of the files in the queue. This slows down the UI because it has to re-add stuff that was already there, *and* confuses the user as all their stuff is randomly reordered. How have people dealt with this? Would it be logical to sort the files by filename to maintain some sort of consistency (even though adding to the end would be more logical), or has anyone devised some complex solution to figure out which files were actually selected in the last operation? | in current version of YUI files added to event.fileList to the end of list with progressing IDs and not shuffling their order. take a look at their multi-file upload example. It even continues numbering order if you remove some files from beginning of queue. | Im using yahoo uploader, but dont understand exactly what you meaning, you can order files the way you want, every time the user select a file you can insert with javascript in the top of the div, span or whatever you are using, and for example what you can do for avoid a user select the same file you can save the event.fileList.fileNUBER in array and compare everytime the onselect event goes on. | Why does YUI Uploader return all queued files after file select? | [
"",
"javascript",
"user-interface",
"yui",
""
] |
I have designed a C# console application to merge and split huge files (about 4GB of size) using OOP design. It involves reading/writing xml, flat-files, and images. I have classes for readers and writers.
The merging took about 00:12, while the splitting took more than 04:30 hours. Then I've enhanced the performance of the splitting to reach 00:50 by distributing the output files into subdirectorys rather than using single directory.
My boss's asking me to convert everything into static procedural programming, but not objects. He says 00:12 for merging comparing to 00:50 for splitting is not balanced. He wants to have the splitting done in 00:30 minutes by converting into static.
Now i know static calls are faster according to [this](http://msdn.microsoft.com/en-us/library/ms973852.aspx). However I disagree that all static will be better since i will have to use "ref" and "out" parameters in methods.
My questions are:
1. What is the reason for splitting files into subdirectory is much more faster than using a single output directory? (i.e. for huge number of files >200,000)
2. Is there a better way than converting my code from object to static, in order to achieve higher performance? | Did you profile your program?
You should profile your code. Objects are fast, unoptimal code is dead slow.
After you optimize it, this task would be I/O bound anyway (which means it spends most of time waiting for disks to fetch another part of data).
And yeah, your boss is better off doing bossy things like playing golf or dilberting around, not telling you bullshit about software design.
'cause you're not trying to play golf for him, do you? | The difference between an instance call and a static call is so miniscule that I would happily wager that it has nothing to do with your performance issue. At all. Yes, static call is *technically* faster (by a tiny, tiny amount), but that is **nothing** compared to all the file IO you are doing. As has already been stated - profile your code, and stop worrying about things like this (premature optimisation). Most likely, the bottleneck is poor collection performance, perhaps fixable with dictionary etc.
Timings:
```
static: 154ms
instance: 156ms
```
So 2ms difference over 50M calls! Forget about it...
Based on:
```
class Program
{
static void Main()
{
StaticMethod(); // JIT
Program p = new Program();
p.InstanceMethod(); // JIT
const int LOOP = 50000000; // 50M
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < LOOP; i++) StaticMethod();
watch.Stop();
Console.WriteLine("static: " + watch.ElapsedMilliseconds + "ms");
watch = Stopwatch.StartNew();
for (int i = 0; i < LOOP; i++) p.InstanceMethod();
watch.Stop();
Console.WriteLine("instance: " + watch.ElapsedMilliseconds + "ms");
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
void InstanceMethod() { }
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
static void StaticMethod() { }
}
```
---
edit:
If we assume (for example) that we create a new method every 20 calls (`if (i % 20 == 0) p = new Program();`), then the metrics change to:
```
static: 174ms
instance: 873ms
```
Again - nowhere near enough to indicate a bottleneck, when that is over 50M calls, and we're still under a second! | which has better performance? static versus objects | [
"",
"c#",
"performance",
"oop",
"static",
""
] |
How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in WinCE/Windows Mobile 5/6 with MFC or Win32 API? | There's this trick I found [here](http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/12a10fae-15b2-4b73-bb86-e7e02d3dc28d/) to draw a borderless control and then draw the border from its parent. or make a static control slightly bigger than the control just to draw the border.
Is there any better Idea? such as making use of Window Clipping Region or something?
***update:***
[Here](http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/48afc8d3-8ecd-4280-bdc7-a3594745207d/) is a discussion with an MSFT on the topic | You can achieve such an effect by deriving your own CEdit class and override WM\_NCPAINT message, this allows you to paint the non-client area yourself and draw you own border when focus is changed:
```
void CMyEdit::OnNcPaint()
{
CWindowDC dc(this);
CRect rect;
GetWindowRect(&rect);
dc.Draw3dRect(0, 0, rect.Width(), rect.Height(), RGB(0,0,255) , RGB(255,0,0) );
}
``` | Windows Mobile/Pocket PC: How do I change the border color of focused/unfocused CEdit, CListCntl, CButton in MFC or Win32 | [
"",
"c++",
"mfc",
"windows-mobile",
"windows-ce",
""
] |
What the heck is wrong with this:
```
if ($bb[$id][0] == "bizz") {
$BoxType = "bus_box";
} else {
$Boxtype = "home_box";
}
<div class="<? echo $BoxType; ?>">
```
`$bb[$id][0]` can either be 'bizz' or 'home' but no matter what it stops after the first step. | PHP variables are case sensitive. The 'T' in `$BoxType` is lower case in the else block. | Not entirely related to your question (which has already been answered), but you may be interested in the ternary operator :)
```
<div class="<?= $bb[$id][0] == "bizz" ? "bus_box" : "home_box" ?>">
``` | Using a different case for a variable name doesn't work | [
"",
"php",
""
] |
HI I'm tring to send some headers in my PHP script such as
```
$headers[] = "BATCH_TYPE: XML_SINGLE";
$headers[] = "VENDOR_ID: 56309";
```
But they are being received as:
Batch-Type
Vendor-ID
..not as they were intended or required - which is causing me problems.
Anyone know why or how to sort?
Thanks,
```
<?php
function httpsPost($Url, $xml_data, $headers)
{
// Initialisation
$ch=curl_init();
// Set parameters
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $Url);
// Return a variable instead of posting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD,"username:password");
// Activate the POST method
curl_setopt($ch, CURLOPT_POST, 1) ;
// Request
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 999);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// execute the connexion
$result = curl_exec($ch);
// Close it
curl_close($ch);
return $result;
}
$request_file = "./post_this.xml";
$fh = fopen($request_file, 'r');
$xml_data = fread($fh, filesize($request_file));
fclose($fh);
$url = 'http://www.xhaus.com/headers';
$headers = array();
$headers[] = "Expect:";
$headers[] = "Accept: text/xml";
$headers[] = "BATCH_TYPE: XML_SINGLE";
$headers[] = "BATCH_COUNT: 1";
$headers[] = "VENDOR_ID: 54367";
$Response = httpsPost($url, $xml_data, $headers);
echo $Response;
?>
``` | After a week of battling with the company of this external server, they were in fact giving me the wrong headers - D'oh! | How are you checking these headers ? I've just tried myself with the following code:-
```
<?php
header("BATCH_TYPE: XML_SINGLE");
```
And got back the following:-
```
HTTP/1.1 200 OK
Date: Wed, 10 Jun 2009 08:56:54 GMT
Server: Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch
X-Powered-By: PHP/5.2.6-3ubuntu4.1
BATCH_TYPE: XML_SINGLE
Vary: Accept-Encoding
Content-Length: 0
Content-Type: text/html
``` | HTTP Post headers, received differently from what's being sent | [
"",
"php",
"http-headers",
"http-post",
""
] |
I have a jQuery wrapped element which I would like to append to a html row. I can't wrap my head around this, since append() seemingly accepts strings but not existing jQuery elements (I might be mistaken here).
I have a following setup:
```
var row='<tr><td>data1</td><td>data2</td><td>';
var img=$('<img src="path/to/img.png"');
img.click(myClickHandler);
```
Now what I'm trying to do is to append this img element to my row and 'close' the row with a closing tag.
I'm doing it as follows:
```
var jRow=$(row);
jRow.append(img);
jRow.append('</td></tr>');
```
After my row is ready I append it to my table:
```
$('#tableId').append(jRow);
```
Well, all above doesn't work, because I get [Object Object] instead of image tag in my added row.
My goal is to have a row with an image in last cell and a working click handler.
Pleease, help. | When you pass a string to **`append()`** it is first "converted" to a DOM element/collection. So, every single string you pass to **`append()`** must be valid HTML/XHTML; you can't add bits of string on later. The image can still be appended to the table row even if you close the tags beforehand. E.g.
```
var row='<tr><td>data1</td><td>data2</td><td></td></tr>';
var img=$('<img src="path/to/img.png"/>');
img.click(myClickHandler);
var jRow = $(row);
$('td:last', jRow).append(img);
```
---
When you pass anything to **`append()`** or **`html()`** or **`prepend()`** (or any other similar method) try to forget about strings; what you just passed is no longer a string; it has been parsed as HTML and has been added to the document as a DOM element (or a number of DOM elements). | I am not 100% sure, but I think HTML fragments should always be "complete", meaning that adding just `"</td></tr>"` will not work.
A solution would be to build a string with a complete HTML fragment, and then append it, instead of appending the pieces one at a time. You can always add the click handler after you created your jQuery object, like this:
```
jRow.find("img").click(function () { ... });
``` | Append a jQuery element to a string that contains html | [
"",
"javascript",
"jquery",
""
] |
A lot of the time when I send image data over WSGI (using `wsgiref`), the image comes out distorted. As an example, examine the following:
[](https://i.stack.imgur.com/8K4j0.gif)
(source: [evanfosmark.com](http://evanfosmark.com/files/goog.gif)) | As you haven't posted the code, here is a simple code which correctly works
with python 2.5 on windows
```
from wsgiref.simple_server import make_server
def serveImage(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'image/png')]
start_response(status, headers)
return open("about.png", "rb").read()
httpd = make_server('', 8000, serveImage)
httpd.serve_forever()
```
may be instead of "rb" you are using "r" | It had to do with `\n` not being converted properly. I'd like to thank Alex Martelli for pointing me in the right direction. | Image distortion after sending through a WSGI app in Python | [
"",
"python",
"wsgi",
""
] |
I have to modify some parts of a large PHP application. The different parts were written, of course, by different people (mostly interns). After looking through the code, I found that there were 2 styles of coding used by the other developers:
* The 'PHP is the glue of the Internet' style, mixing html and php, ex.:
[snip]
```
<tr class="ds_subsubhead_2">
<td colspan="21" align="left"> A <select name="nb_linge" onChange="MM_jumpMenu('parent',this,0)" style="vertical-align:middle"> <option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','9999') ?>" <? if($messagesParPage == '9999') { ?>selected="selected"<? } ?>>Tous</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','25') ?>" <? if($messagesParPage =='25') { ?>selected="selected"<? } ?>>25</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','50') ?>" <? if($messagesParPage =='50') { ?>selected="selected"<? } ?>>50</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','75') ?>" <? if($messagesParPage =='75') { ?>selected="selected"<? } ?>>75</option>
```
[snip] or
```
<td <? if((isset($_GET['t1']))&&($_GET['t2']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t3']))&&($_GET['t4']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t5']))&&($_GET['t6']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
```
[snip] or even
```
<script type="text/javascript" src="<?=$_SESSION["path"]?>lib/js/ajax.js"></script>
```
[snip]
* ... and the more procedural way, ex.:
[snip]
```
$output .= '<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">';
if ( empty($_GET['p']) ) $output .= '<option value=" ">All</option>';
else $output .= '<option value='.$_GET['m'].'>'.$_GET['m'].'</option>';
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ) {
if( !empty($row['maoie']) ) $output .= '<option value="'.$row['maoie'].'">'.$row['maoie'].'</option>';
}
$output .= '</select></form></td>';
$output .= add_more_stuff();
echo $output;
```
Now, I'm not completely sure that this is a *more* procedural way to do things, but at least it is different from the previous one. Which one, do you think, is *generally* better?
I, personally, dont't like 'the glue of the Internet' style. | There is a third option: templates. Templates are more readable than glue or random emission of ascii vomit. I just tend to use HEREDOCd strings and str\_replace, thus:
```
$template = <<<TEMPLATE
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<div id='nav'>{NAV}</div>
<div id='content'>{CONTENT}</div>
</body>
TEMPLATE;
$data = array (
"{TITLE}" => "Page title example",
"{NAV}" => buildNav(),
"{CONTENT}" => buildContent());
str_replace(array_keys($data),array_values($data), $template);
``` | I would ditch both and code the PHP away from any presentation-layer specific HTML. Otherwise things get very nasty, very quickly for anything bigger than 'Hello World' :)
You are shooting yourself in the foot if you want to modify the code later. I would try and kill off this problem by porting to a proper CMS/Abstract presentation.
Neither look good. I wouldn't want to maintain code in either style. **save time later by spending time now** cleaning it up properly.
Even something as basic as moving your HTML into externally loaded format strings and running them through sprintf() or similar might be better than the current situation. And you say you have a mix of these coding styles !?!
**good luck to you sir!**
Both styles should be relegated to the tomb of dynamic internet growing pains. Take a peek through some open source PHP projects to see a good, maintainable coding style in action. Things like <http://sourceforge.net/projects/wikipedia> MediaWiki show a good mix of HTML-In-Source and separation (although it is not perfect IMHO) | PHP logical coding style | [
"",
"php",
""
] |
Considering the following sample code:
```
// delivery strategies
public abstract class DeliveryStrategy { ... }
public class ParcelDelivery : DeliveryStrategy { ... }
public class ShippingContainer : DeliveryStrategy { ... }
```
and the following sample Order class:
```
// order (base) class
public abstract class Order
{
private DeliveryStrategy delivery;
protected Order(DeliveryStrategy delivery)
{
this.delivery = delivery;
}
public DeliveryStrategy Delivery
{
get { return delivery; }
protected set { delivery = value; }
}
}
```
When i derive a new type of order class, it will inherit the Delivery property of type DeliveryStrategy.
Now, when it is given that CustomerOrders must be delivered using the ParcelDelivery strategy, we could consider '**new**'ing the Delivery property in the CustomerOrder class:
```
public class CustomerOrder : Order
{
public CustomerOrder()
: base(new ParcelDelivery())
{ }
// 'new' Delivery property
public new ParcelDelivery Delivery
{
get { return base.Delivery as ParcelDelivery; }
set { base.Delivery = value; }
}
}
```
(The CustomerOrder obviously needs to ensure that is compatible (polymorph) with Order)
This allows direct usage of the ParcelDelivery strategy on CustomerOrder without the need for casting.
Would you consider using this pattern? why / why not?
**Update**: i came up with this pattern, instead of using generics, because i want to use this for multiple properties. I don't want to use generic type arguments for all these properties | I think this is a good pattern. It makes it easier to explicitly use derived types by removing the need to cast the result, and it doesn't 'break' the base class behavior. Actually, a similar pattern is used in some classes in the BCL, for instance look at the DbConnection class hierarchy :
* DbConnection.CreateCommand() returns a DbCommand
* SqlConnection.CreateCommand() hides the base implementation using 'new' to return a SqlCommand.
* (other DbConnection implementations do the same)
So, if you manipulate the connection object through a DbConnection variable, CreateCommand will return a DbCommand ; if you manipulate it through a SqlConnection variable, CreateCommand will return a SqlCommand, avoiding the cast if you're assigning it to a SqlCommand variable. | I'd prefer to make the type generic:
```
public abstract class Order<TDelivery> where TDelivery : Delivery
{
public TDelivery Delivery { ... }
...
}
public class CustomerOrder : Order<ParcelDelivery>
{
...
}
```
This ensures type safety at compile-time, rather than leaving it up to execution time. It also prevents the situation of:
```
CustomerOrder customerOrder = new CustomerOrder();
Order order = customerOrder;
order.Delivery = new NonParcelDelivery(); // Succeeds!
ParcelDelivery delivery = customerOrder.Delivery; // Returns null
```
Ouch.
I regard `new` as usually a last resort. It introduces added complexity both in terms of implementation and use.
If you don't want to go down the generic route, I'd introduce a genuinely new property (with a different name). | Pros and cons of 'new' properties in C# / .Net? | [
"",
"c#",
".net",
"properties",
"new-operator",
""
] |
I am using `split()` to tokenize a String separated with `*` following this format:
```
name*lastName*ID*school*age
%
name*lastName*ID*school*age
%
name*lastName*ID*school*age
```
I'm reading this from a file named "entrada.al" using this code:
```
static void leer() {
try {
String ruta="entrada.al";
File myFile = new File (ruta);
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line=reader.readLine())!=null){
if (!(line.equals("%"))){
String [] separado = line.split("*"); //SPLIT CALL
names.add(separado[0]);
lastNames.add(separado[1]);
ids.add(separado[2]);
ages.add(separado[3]);
}
}
reader.close();
}
```
And I'm getting this exception:
> Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '\*' near index 0
> \*
My guess is that the lack of a `*` after age on the original text file is causing this. How do I get around it? | No, the problem is that `*` is a reserved character in regexes, so you need to escape it.
```
String [] separado = line.split("\\*");
```
`*` means "zero or more of the previous expression" (see the [`Pattern` Javadocs](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html)), and you weren't giving it any previous expression, making your split expression illegal. This is why the error was a [`PatternSyntaxException`](http://java.sun.com/javase/6/docs/api/java/util/regex/PatternSyntaxException.html). | I had similar problem with `regex = "?"`. It happens for all special characters that have some meaning in a regex. So you need to have `"\\"` as a prefix to your regex.
```
String [] separado = line.split("\\*");
``` | Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*' | [
"",
"java",
"regex",
"split",
"tokenize",
""
] |
I have a windows form with a listview control. I have a selectedIndex changed event where i am performing some action. Through reflection I am trying to set the value of the list view.
But the event is not getting fired. Any help will be helpfull.
Edit
The event looks like
```
private void LV1_SelectedIndexChanged(object sender, EventArgs e)
{
if (LV1.SelectedItems.Count>0)
{
if (LV1.SelectedItems[0].Text.ToString() == "testing")
{
// Do some work.
}
}
}
```
I am using relection in another project and changing the selected item as follows
```
Assembly a = Assembly.LoadFrom(exePath);
Type formType = a.GetType(formName);
testForm = (Form)a.CreateInstance(formType.FullName);
if (testForm != null)
{
Type t1 = testForm.GetType();
FieldInfo fi = t1.GetField(controlName, flags);
object ctrl = fi.GetValue(testForm);
ListView l1 = (ListView)ctrl;
l1.Items[0].Selected = true;
}
``` | Automating another application is fun howver not a trivial task. There's a few options but I guess most of them is out of scope for you. One would be to programatically take over the mouse and keyboard and trough those channels manage the program. Another way would be to manipulate memory, As I said neither are trivial to implement and very easily broken if the aplpication is updated.
I would suggest instead of trying to automate the application to look for infliction points. Are there any service endpoints you could automate and achieve the same result? any API or dll's used by the application you could use instead?
If you really have to automate the application there do exist several frameworks for doing that (usually build for testing purposes). The only one I can think off right now is made by Assima as is ment for training purposes. | I think your problem is here:
```
testForm = (Form)a.CreateInstance(formType.FullName);
```
You are creating a new instance of the form. I'm assuming your main project is an exe that runs an shows the form. Your second project is then another exe that runs and wants to change the selected item. By creating a new instance of the form you will be changing the selected item on the new form, not the old one.
What you need to do is somehow pass the form object over to the secondary project. possibly some static method that gets a singleton instance of the form maybe.
I'm still not entirely sure why you are using reflection, you could just give the second project a reference to the first. | SelectedIndexChange event not firing when using through reflection | [
"",
"c#",
".net",
"reflection",
""
] |
I want to run a PHP script from the command line, but I also want to set a variable for that script.
Browser version: `script.php?var=3`
Command line: `php -f script.php` (but how do I give it the variable containing 3?) | **Script:**
```
<?php
// number of arguments passed to the script
var_dump($argc);
// the arguments as an array. first argument is always the script name
var_dump($argv);
```
**Command:**
```
$ php -f test.php foo bar baz
int(4)
array(4) {
[0]=>
string(8) "test.php"
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
}
```
Also, take a look at [using PHP from the command line](http://www.php.net/manual/en/features.commandline.php). | Besides argv (as Ionut mentioned), you can use environment variables:
E.g.:
```
var = 3 php -f test.php
```
In test.php:
```
$var = getenv("var");
``` | Run php script from command line with variable | [
"",
"php",
"command-line",
""
] |
After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages.
What I don't understand is what happens when the version of one of those installed apps changes. If I update one of the apps that's installed to site-packages, then won't that break all my current projects that use it? I never noticed anything in settings.py that let's you specify the version of the app you're importing.
I think in Ruby/Rails, they're able to freeze gems for this sort of situation. But what are we supposed to do in Python/Django? | Having multiple versions of the same package gets messy (setuptools can do it, though).
I've found it cleaner to put each project in its own `virtualenv`. We use `virtualevwrapper` to manage the virtualenvs easily, and the `--no-site-packages` option to make every project really self-contained and portable across machines.
This is the [recommended setup for mod\_wsgi servers](http://code.google.com/p/modwsgi/wiki/VirtualEnvironments). | What we do.
We put only "3rd-party" stuff in site-packages. Django, XLRD, PIL, etc.
We keep our overall project structured as a collection of packages and Django projects. Each project is a portion of the overall site. We have two separate behaviors for port 80 and port 443 (SSL).
```
OverallProject/
aPackage/
anotherPackage/
djangoProject80/
settings.py
logging.ini
app_a_1/
models.py # app a, version 1 schema
app_a_2/
models.py # app a, version 2 schema
app_b_2/
models.py
app_c_1/
models.py
djangoProject443/
test/
tool/
```
We use a version number as part of the app name. This is the major version number, and is tied to the schema, since "uses-the-same-schema" is one definition of major release compatibility.
You have to migrated the data and prove that things work in the new version. Then you can delete the old version and remove the schema from the database. Migrating the data is challenging because you can't run both apps side-by-side.
Most applications have just one current version installed. | Installed apps in Django - what about versions? | [
"",
"python",
"django",
"version-control",
""
] |
I know I can get the screenshot of the entire screen using Graphics.CopyFromScreen(). However, what if I just want the screenshot of a specific application? | Here's some code to get you started:
```
public void CaptureApplication(string procName)
{
var proc = Process.GetProcessesByName(procName)[0];
var rect = new User32.Rect();
User32.GetWindowRect(proc.MainWindowHandle, ref rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(bmp))
{
graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
}
bmp.Save("c:\\tmp\\test.png", ImageFormat.Png);
}
private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
}
```
It works, but needs improvement:
* You may want to use a different mechanism to get the process handle (or at least do some defensive coding)
* If your target window isn't in the foreground, you'll end up with a screenshot that's the right size/position, but will just be filled with whatever is in the foreground (you probably want to pull the given window into the foreground first)
* You probably want to do something other than just save the bmp to a temp directory | > If you want to print form screen you can use
```
PrintWindow(Handle);
```
The PrintWindow win32 api will capture a window bitmap even if the window is covered by other windows or if it is off screen:
```
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
public static Bitmap PrintWindow(IntPtr hwnd)
{
RECT rc;
GetWindowRect(hwnd, out rc);
Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap = gfxBmp.GetHdc();
PrintWindow(hwnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
gfxBmp.Dispose();
return bmp;
}
```
The reference to RECT above can be resolved with the following class:
```
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
private int _Left;
private int _Top;
private int _Right;
private int _Bottom;
public RECT(RECT Rectangle) : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
{
}
public RECT(int Left, int Top, int Right, int Bottom)
{
_Left = Left;
_Top = Top;
_Right = Right;
_Bottom = Bottom;
}
public int X {
get { return _Left; }
set { _Left = value; }
}
public int Y {
get { return _Top; }
set { _Top = value; }
}
public int Left {
get { return _Left; }
set { _Left = value; }
}
public int Top {
get { return _Top; }
set { _Top = value; }
}
public int Right {
get { return _Right; }
set { _Right = value; }
}
public int Bottom {
get { return _Bottom; }
set { _Bottom = value; }
}
public int Height {
get { return _Bottom - _Top; }
set { _Bottom = value + _Top; }
}
public int Width {
get { return _Right - _Left; }
set { _Right = value + _Left; }
}
public Point Location {
get { return new Point(Left, Top); }
set {
_Left = value.X;
_Top = value.Y;
}
}
public Size Size {
get { return new Size(Width, Height); }
set {
_Right = value.Width + _Left;
_Bottom = value.Height + _Top;
}
}
public static implicit operator Rectangle(RECT Rectangle)
{
return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height);
}
public static implicit operator RECT(Rectangle Rectangle)
{
return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);
}
public static bool operator ==(RECT Rectangle1, RECT Rectangle2)
{
return Rectangle1.Equals(Rectangle2);
}
public static bool operator !=(RECT Rectangle1, RECT Rectangle2)
{
return !Rectangle1.Equals(Rectangle2);
}
public override string ToString()
{
return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}";
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public bool Equals(RECT Rectangle)
{
return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;
}
public override bool Equals(object Object)
{
if (Object is RECT) {
return Equals((RECT)Object);
} else if (Object is Rectangle) {
return Equals(new RECT((Rectangle)Object));
}
return false;
}
}
``` | Get a screenshot of a specific application | [
"",
"c#",
"winapi",
"screenshot",
""
] |
I'm trying to make a file that creates a array of 3 strings, than randomly displays one of the three 5 times. Can someone tell me what I'm doing wrong?
```
<?php
$pk[0] = "PK Fire!<br/>";
$pk[1] = "PK Thunder!<br/>";
$pk[2] = "PK Freeze!<br/>";
for($i = 0; $i < 5; $i++)
Echo "" + $pk[rand(0,2)] + "";
?>
``` | . (dot) must be used instead of + to concatenate strings
```
Echo "" . $pk[rand(0,2)] . "";
```
instead of
```
Echo "" + $pk[rand(0,2)] + "";
``` | Jian Lin is correct, you're using "+" when you should be using "." to combine strings.
```
Echo "" + $pk[rand(0,2)] + "";
```
should become
```
echo "" . $pk[rand(0,2)] . "";
```
And really, you can just do:
```
echo $pk[rand(0,2)];
```
instead of concatenating blank strings before and after (which, as they're blank, add nothing). | Why are my arrays showing up as 0 in php? | [
"",
"php",
"arrays",
""
] |
I have a simple ajax application
From this, a popup is launched, with a form.
Both the form resultpage, and the ajax application hava a javascript file in common.
From the popup window, in the form resultpage, I am trying to call a method from the common javascript file, to apply to the parent window.
My javascript file contains an updateLayer method, which when caleld from the parent window, works fine. I get nothing when trying to call it from the popup window.
The resultpage in the popup window has
```
<script type="text/javascript" src="x.js">window.opener.updateLayer("Layer3", "380118179930"); </script>
```
before any html.
Nothing happens in the parentwindow. I have also tried window.parent.
What is the reason and solution for/to this? | I assume this is related to [this question](https://stackoverflow.com/questions/861339/calling-a-javascript-function-from-a-form-result/861452#861452), asked by another user that also happens to be named Josh.
In my answer to that question, I tried to explain that the functions from a Javascript file included in your parent window would be attached to the window object, so you use window.opener to get access to that window object to call them.
It looks like you've almost got this solved, but the problem here is that by including `src="x.js"` in the script tag from your form response, you're effectively overwriting any code placed inside the script. Plus, since x.js is included in the parent window, there's no need to have it in the popup at all, anyway.
The code for your form response should look like this:
```
<script type="text/javascript">
window.opener.updateLayer("Layer3", "380118179930");
</script>
```
I've removed the `src="x.js"` attribute, which would otherwise prevent code between the `<script></script>` tags from being executed. | Your problem can be that you have two JavaScript files with the same content, while no namespaces are applied.
First, your parent includes the file.js where your updateLayer() is defined. Then the parent opens the child window, which also includes that file.js. If you do that, you have two threads running, where each of them may have it's own functions and objects without bothering the other. I assume that your function is global. This can cause problems, if no namespaces are used. Also it can happen that your big ajax library creates iframes and things like that, and you won't see anything from that because it happens under the hood.
So try: top.window.opener.updateLayer("Layer3", "380118179930");
If that doesn't help, try to open a blank window with no included file.js and call that function from the opener. If that works, wrap the contents of that file.js in a namespace like myNamespace = {....big file content inbetween....}, make two versions of that (or better dynamically include the content) and make sure you have two different namespace. JavaScript is most often not working the way you think it should.
Also, make very sure that the url for your opened window has *exactly* the same domain. It can cause security issues so that the browser disallows access from a child window to it's parent. | Problems using window.opener | [
"",
"javascript",
"html",
"ajax",
""
] |
I'm currently wondering what the actual overhead, in the JVM, is for loading extra classes which are never used.
We have code which iterates all the classes in the class path to find classes which implement a certain interface, we then load them.
This allows custom classes to be simply dropped in a directory and they get loaded and registered.
The side affect is that we hit every class in the class path, causing the classes to load. What would be the affect on the JVMs memory?
Does simply loading classes affect the memory much at all? | As usual, I would advise measuring this for your particular scenario.
Having said that, I'm not sure I'd advise scanning the *whole* classpath. If you don't control the classpath (it's your customer's, or similar), potentially they could add anything to it, and your process is going to scan anything they drop into their classpath (possibly unrelated to your app).
I'd suggest that you nominate only certain directories/repositories that classes can be uploaded to, and that way you'll restrict the classpath scanning and reduce the chances of inadvertently picking up stuff you don't intend to. | If you use a separate ClassLoader to load those classes and are [very careful](http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) not to create any references to those classes or instances of them, then when the ClassLoader becomes eligible for garbage collection, so do the classes.
Thus, you could avoid unnecessarily clogging your PermGen space by doing 2 passes with separate ClassLoaders: one to load all the classes and identify those you want to keep, and another to actually use them. | Loading Java Classes which arent needed | [
"",
"java",
"memory",
"class",
"classloader",
""
] |
I have a scenario inwhich users of a site I am building need the ability to enter some basic information into a webform without having to logon. The site is being developed with ASP.NET/C# and is using MSSQL 2005 for its relational data.
The users will be sent an email from the site, providing them a unique link to enter the specific information they are required. The email will be very similar to the style of email we all get when registering for sites such as forums, containing a randomly generated, unique URL paramter specifically pertaining to a single purpose (such as verifying an email address for a forum).
My queries are regarding the secure implementation of this problem. I was considering using a GUID as the unique identifier, but am unsure of its implications in the security world.
1. Is a GUID sufficiently long enough such that values cannot be easily guessed (or brute-forced over time)?
2. Is .NET's GUID implmentation sufficiently random in the sense that there is an equal chance of generation of all possible values in the "key space"?
3. If using a GUID is an acceptable approach, should the site then redirect to the information via URL rewriting or by associating the information in a datatable with the GUID as a reference?
4. Will using a URL rewriting hide the true source of the data?
5. Should I consider using TSQL's SELECT NEWID() as the GUID generator over the .NET implementation?
6. Am I completely wrong with my approach to this problem?
Many thanks,
Carl | 1. Yes, 2128 is long enough.
2. No, GUID implementations are designed to generate **unique** GUIDs rather than random ones. You should use a [cryptographically secure](http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) random number generator (e.g. [`RNGCryptoServiceProvider`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx)) to generate 16 random bytes and initialize a `Guid` structure with that.
3. Yes, it's an acceptable approach overall. Both will work.
4. Yes, if you don't give out any other clues
5. No, `goto 2`
6. No, it's pretty OK. You just need to use a cryptographically secure random number generator to generate the GUID. | 1. No, GUIDs are not fully random, and most of the bits are either static or easily guessable.
2. No, they're not random, see 1. There is actually a very small number of bits that are actually random, and not cryptographically strong random at that.
3. It's not, see 1 and 2.
4. you can, but dont need to... see my solution at the end.
5. No, see 1 and 2
6. Yes.
What you should be using instead of a GUID, is a cryptographically strong random number generator - use [System.Security.Cryptography.RNGCryptoServiceProvider](https://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx), to generate long (say, 32 bytes) string of data, then [base64 encode](https://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.110).aspx) that.
Also, assuming this is some kind of registration with sensitive data, you'd want to time limit the validity of the link, say 60 minutes, or 24 hours - depends on your site.
You'll need to keep a mapping of these values to the specific users. Then you can automatically present him with the proper form as needed. Dont need to do url rewriting, just use that as the user's identifier (on this page).
Of course, dont forget this URL should be HTTPS...
Btw, just a note - its good practice to put some form of text in the email, explaining that users shouldnt click on links in anonymous emails, and typically your site wont send, and they should never enter their password after clicking blablabla....
Oh, almost forgot - another issue you should consider is what happens if the user wants several emails sent to him, e.g. hits register several times. Can he do this over and over again, and get many valid URLs? Is only the last one valid? Or maybe the same value gets resent over and over again? Of course, if an anonymous user can put in a request for this email, then DoS may become an issue... not to mention that if he puts in his own email, he can put in any random address too, flooding some poor shmuck's inbox and possibly causing your mail server to get blacklisted...
No one right answer, but needs to be considered in context of your application. | Implementing secure, unique "single-use" activation URLs in ASP.NET (C#) | [
"",
"c#",
"asp.net",
"t-sql",
"cryptography",
"security",
""
] |
Can anyone explain why you cannot insert a null object into the ASP.NET cache?
```
string exampleItem = null;
HttpRuntime.Cache.Insert("EXAMPLE_KEY",
exampleItem,
Nothing,
DateTime.Now.AddHours(1),
System.Web.Caching.Cache.NoSlidingExpiration);
```
The exception error message states that the "value" object cannot be null. In my application there are valid reasons why we whould want to store a null value in the cache. | Underlying `Cache` is likely a `Hashtable` or `Dictionary<string, object>`, whose getters do not differentiate between no value at that key, or a null value at that key.
```
Hashtable table = new Hashtable();
object x = table["foo"];
table.Add("foo", null);
object y = table["foo"];
Console.WriteLine(x == y); // prints 'True'
```
Consider a using placeholder "null" item, similar to `DbNull.Value`. | As a possible alternative or work-around, you can instead store an object rather than your value. For instance (this assumes your value is a string, but it could be generic)
```
public class CacheItemWrapper
{
public string Value { get; set; }
}
```
...
```
cache.Insert(cacheKey, new CacheItemWrapper { Value = null }, ...);
```
That way you are never inserting null. To get the value back, you just extract it from the wrapper:
```
var val = cache.Get(cacheKey);
if (val != null) return val.Value;
```
(This is all off the top of my head, so apologies for any silly typos.) | ASP.NET can't cache null value | [
"",
"c#",
"asp.net",
"caching",
""
] |
I need a suggestion on on how do I copy a block of memory efficiently, in single attempt if possible, in C++ or assembly language.
I have a pointer to memory location and offset. Think of a memory as a 2D array that I need to copy consisting of rows and columns. | If you need to implement such functionality yourself, I suggest you to check up [Duff's Device](http://en.wikipedia.org/wiki/Duff%27s_device) if it has to be done efficiently. | How about [`std::memcpy`](http://en.cppreference.com/w/cpp/string/byte/memcpy)? | copy block of memory | [
"",
"c++",
"memory",
"copy",
""
] |
Consider this:
```
var i=$('<img src="/path/to/imgI.png"/>');
var j=$('<img src="/path/to/imgJ.png"/>');
$([i,j]).css('cursor','hand');
```
The cursor is not changed however and I don't know why..
When I do it separately, it works.
Thanks. | The array is of two jQuery objects when what you require is the DOM elements within those jQuery objects. This will work:
```
var i=$('<img src="/path/to/imgI.png"/>')[0]; // <= Notice [0]
var j=$('<img src="/path/to/imgJ.png"/>')[0];
$([i,j]).css('cursor','pointer');
```
Alternatively, (using **`add()`**)
```
var i=$('<img src="/path/to/imgI.png"/>');
var j=$('<img src="/path/to/imgJ.png"/>');
$(i).add(j).css('cursor','pointer');
```
EDIT: Also, use **`cursor:pointer;`** instead of **`cursor:hand;`** | Are you sure your problems isn't browser specific? That particular css property is tricky, it requires the property be set two different ways to work in IE and Firefox.
I'd recommend using a class in the img tag to specify the hand property. Then you can specify both rules and get what you are looking for. | Why this type of array wrapping does not work in jQuery? | [
"",
"javascript",
"jquery",
""
] |
I have to following code in VS2008 .net 3.5 using WinForms:
```
byte percent = 70;
byte zero = 0;
Bitmap copy = (Bitmap)image1.Clone();
...
Color oColor = copy.GetPixel(x, y);
byte oR = (byte)(oColor.R - percent < zero ? zero : oColor.R - percent);
```
When I leave the "**`(byte)`**" off the last line of code, I get a compiler error saying it "Cannot implicitly convert type '`int`' to '`byte`'." If everything is of type `byte` and `byte` is an integer type... then why do I need to have the cast? | Because subtraction is coercing up to an integer. As I recall, byte is an unsigned type in C#, so subtraction can take you out of the domain of bytes. | That's because the result of a byte subtraction doesn't fit in a byte:
```
byte - byte = (0..255) - (0..255) = -255..255
``` | Why is a cast required for byte subtraction in C#? | [
"",
"c#",
".net",
"casting",
"integer",
"byte",
""
] |
My first question here.
The question is similar to this one: [PHP: Retrying a query a set number of times or until success](https://stackoverflow.com/questions/712161/php-retrying-a-query-a-set-number-of-times-or-until-success)
Try till success in OO way.
Here example what i'm trying to do:
```
class Creatives {
public function run() {
$auth_token='mypassword';
$id=123123;
$this->retry_till_success ( $this->getCreatives, array($auth_token, $id) );
print $this->creatives;
}
public function getCreatives($auth_token, $id) {
$this->creatives = $this->campagin->get($auth_token, $id);
}
private function retry_till_success($method, $args) {
do {
$try_again = false;
try {
/* how to call the method with */
/* call user method with params pass */
/* do until success */
} catch (SoapFault $fault) {
if($fault->faultstring== 'couldnt connect to host')
$try_again=true;
}
} while ($try_again);
}
}
```
i read about call\_user\_func, but don't know if i could use it inside the class,
I need to make 99.9% success rate in my calls, any suggestion to achieve this will be great.
thank you. | Best way would be to extend SoapClient and add the retry in the \_\_call method.
```
class LocalSoapClient extends SoapClient
{
public function __call($function_name, $arguments)
{
$result = false;
$max_retries = 5;
$retry_count = 0;
while(! $result && $retry_count < $max_retries)
{
try
{
$result = parent::__call($function_name, $arguments);
}
catch(SoapFault $fault)
{
if($fault->faultstring != 'Could not connect to host')
{
throw $fault;
}
}
sleep(1);
$retry_count ++;
}
if($retry_count == $max_retries)
{
throw new SoapFault('Could not connect to host after 5 attempts');
}
return $result;
}
}
```
then when you instantiate your soap client use `new LocalSoapClient()` instead of `new SoapClient()` | [`call_user_func_array()`](http://php.net/call_user_func_array) is great for this:
```
$result = call_user_func_array( array($this, $method), $args );
```
The first argument is the callback [pseudo-type](http://uk.php.net/callback), and the second is an array of parameters which will be passed to the function/method as individual arguments.
As a side note, you might want to look at throttling your retries (e.g. have a sleep time which doubles every time it fails up to a set limit). If the connection to the host is down there may not be much point in retrying as fast as possible. | PHP OO retry logic implementation and passing dynamic method and args | [
"",
"php",
""
] |
I'm currently about two-and-a-half weeks in to my first ASP.Net MVC application, and so far, I love it.
This current project is a port of an ASP.Net WebForms project, and I am trying to maintain functionalty. All is going well.
However, I find myself repeating... myself.
For example, In my BaseController class, in my BaseViewPage, in my BaseViewUserControl, AND in my BaseViewMasterPage, I have the following code:
```
protected LanLordzApplicationManager AppManager
{
get
{
if(Session["Application"] == null)
{
Session["Application"] = new LanLordzApplicationManager(Server.MapPath("~/"));
}
return (LanLordzApplicationManager)Session["Application"];
}
}
protected User CurrentUser
{
get
{
if (Session["UserID"] == null && this.Request.Cookies["AutoLogOnKey"] != null && !string.IsNullOrEmpty(this.Request.Cookies["AutoLogOnKey"].Value))
{
this.CurrentUser = this.AppManager.RecallUser(this.Request.Cookies["AutoLogOnKey"].Value, Request.UserHostAddress);
}
if (Session["UserID"] == null)
{
return null;
}
else
{
return this.AppManager.GetUserByUserID((long)Session["UserID"]);
}
}
set
{
Session["UserID"] = value.UserID;
}
}
```
Now, this is *not* beautiful code. I would like to fix it up a little bit, but as of right now, I'm fixing it in four places. It has been, in fact, the source of a couple of bugs, which meant fixing it in all four places again.
**How would you suggest I keep this system DRY?** Note that both of these objects must be kept on the session for more than a couple of reasons. | You could remove the code from BaseViewPage, BaseViewUserControl and BaseViewMasterPage. All data used in rendering the views can be passed to them from the controller as viewdata which is already available in all the views. This centralizes your code at least to the controller base class. | In App\_Code, create a class "BaseUtils" or somesuch, containing that functionality; then you simply have to include reference it where needed...
```
public class BaseUtils
{
public static LanLordzApplicationManager getAppMgr()
{
HttpSession Session = HttpContext.Current.Session;
if(Session["Application"] == null)
{
Session["Application"] = new LanLordzApplicationManager(Server.MapPath("~/"));
}
return (LanLordzApplicationManager)Session["Application"];
}
}
```
and in your page,
```
protected LanLordzApplicationManager AppManager
{
get
{
return BaseUtils.getAppMgr();
}
}
```
And similarly for the other two methods... | Keeping it DRY in ASP.Net MVC | [
"",
"c#",
"asp.net-mvc",
"dry",
""
] |
Many Swing components support embedded HTML, but I cannot find any official documentation on that subject. (Everything on Sun's pages about HTML seems to be targeted at JEditorPane)
So: Which HTML tags are supported in Swing components?
**EDIT:** Although I said that I'm missing "official documentation", I'd also like any "unofficial" documentation. | Swing supports HTML 3.2 (Wilbur) as Software Monkey said. You can find official documentation to this obsolescent (1996) version of HTML at: <http://www.w3.org/TR/REC-html32.html>
Java 7 documentation on the topic: <http://docs.oracle.com/javase/7/docs/api/javax/swing/text/html/package-summary.html>
Though it is worth of noting that it does not explicitly mention this information is valid for other Swing components. | I believe it's a narrow subset of HTML 3.x, although off the top of my head, I don't remember where I read that. | Which HTML tags are supported in Swing components? | [
"",
"java",
"html",
"swing",
""
] |
When I compile something like this:
```
public class MyClass
{
void myMethod(String name, String options, String query, String comment)
{
...
}
}
```
and compile this to a class file, it seems that argument names are lost. That is, when some other Java code references `MyClass` and wants to call or overwrite `myMethod`, my IDE (currently Eclipse) seems to get this method signature from the class-file:
```
void myMethod(String arg0, String arg1, String arg2, String arg3);
```
I know that Eclipse (and possibly other IDEs too) allows me to provide a link to the source or the Javadoc *(as Bishiboosh pointed out)* of `MyClass` and can take advantage of this. But I'm curious if there is some way to tell `javac` to include the names into the class-file, so that users of that class can see the argument names even if they only have the class file.
## Solution for classes
When I compile a class with `java -g:vars`, the names of parameters are included in the class file. `-g:vars` seems to be equivalent to *Eclipse -> project properties -> Java compiler -> Add variable attributes to generated class files*.
This solution was suggested by several authors, but the answer from Nick finally made me believe.
On my machine, Eclipse sometimes used this info, sometimes it didn't, which was probably my fault or a bug in Eclipse, but not a problem with the class files or the compiler. Anyway, now I know that the information is definitely present.
## But no solution for interfaces
While this works (kind of) fine for classes, it's not working for interfaces.
For me, the logical reason seems to be, that `-g:vars` only provides the names of local variables, which is what the documentation for javac also states. In the body of a method, it's parameters are very similar to local variables, thus they are covered by `-g:vars`. interface methods don't have bodies, so they can't have local variables.
My initial question only asked for classes, because I was not aware that there might be any difference.
## Class file format
As *gid* pointed out, the class file format does not support storage of parameter names. I found a [section in the class file spec](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#43817) that describes a data structure which should hold the parameter names of methods, but this is definitely not used when compiling interfaces.
When compiling a class, I can't tell if the mentioned data structure is used, or if Eclipse infers the parameter names from the usage of parameters inside the method body. An expert could clarify this, but it's not that relevant I think. | To preserve names in the class file for debugging purposes try project properties, Java compiler, then "Add variable attributes to generated class files" (See [Eclipse Help](http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/ref-preferences-compiler.htm)).
Compiling the following source:
```
public class StackOverflowTest {
public void test(String foo, String bar) {
// blah
}
}
```
Is decompiled into:
```
// Compiled from StackOverflowTest.java (version 1.5 : 49.0, super bit)
public class StackOverflowTest {
// Method descriptor #6 ()V
// Stack: 1, Locals: 1
public StackOverflowTest();
0 aload_0 [this]
1 invokespecial java.lang.Object() [8]
4 return
Line numbers:
[pc: 0, line: 1]
Local variable table:
[pc: 0, pc: 5] local: this index: 0 type: StackOverflowTest
// Method descriptor #15 (Ljava/lang/String;Ljava/lang/String;)V
// Stack: 0, Locals: 3
public void test(java.lang.String foo, java.lang.String bar);
0 return
Line numbers:
[pc: 0, line: 4]
Local variable table:
[pc: 0, pc: 1] local: this index: 0 type: StackOverflowTest
[pc: 0, pc: 1] local: foo index: 1 type: java.lang.String
[pc: 0, pc: 1] local: bar index: 2 type: java.lang.String
}
```
See the parameter names are preserved in the class files.
I would suggest you look into how your source is being compiled, which version it is compiled for etc.
**EDIT:**
Ah, I see this is different for interfaces - they don't seem to have this information available for the debugger which I guess makes sense. I don't think there'll be a way round this, if you just want to see the parameter names when you're editing source you'll need to go the javadoc route as Nagrom\_17 suggests (attach the source). | You don't specially need the source to make arg names appear in Eclipse...If you specify the Javadoc, Eclipse will display the args. | Preserving parameter/argument names in compiled Java classes | [
"",
"java",
"eclipse",
"compilation",
"javac",
""
] |
I'm currently musing about some idea I can't get right.
The problem is that I want to use one lambda function to instantiate a captured variable and another lambda to access a property of that variable.
Since the instantiating happens within the lambda the variable isn't actually instantiated the time I want to use it within the second lambda.. this is kind of a chicken and egg problem.
I know that the variable *will be* instantiated the time it's used in the second lambda but the compiler doesn't.
Is there any way my idea could work? Here's the actual code:
```
class Program
{
static void Main(string[] args)
{
SqlCommand cmd;
using (new DisposableComposite(
() => cmd = new SqlCommand(),
() => cmd.Connection)) // <- compiler error - variable not instantiated
{
// code
}
}
}
class DisposableComposite : IDisposable
{
private List<IDisposable> _disposables = new List<IDisposable>();
public DisposableComposite(params Func<IDisposable>[] disposableFuncs)
{
// ensure the code is actually executed
foreach (var func in disposableFuncs)
{
IDisposable obj = func.Invoke();
_disposables.Add(obj);
}
}
public void Dispose()
{
foreach (var disposable in _disposables)
{
disposable.Dispose();
}
}
}
``` | Do you mean just adding:
```
SqlCommand cmd = null;
```
(which solves the "definite assignment" glitch; it *is* definitely assigned... a null ;-p We then update the value before it is used).
IMO, though, you'd do better with nested `using` statements... and it isn't clear (from the code) where the actual connection is going to come from...
```
using(var conn = new SqlConnection(...))
using(var cmd = conn.CreateCommand()) {
// ...
}
``` | You can only avoid this by setting cmd to null before the using block:
```
SqlCommand cmd=null;
using (new DisposableComposite(
() => cmd = new SqlCommand(),
() => cmd.Connection)) // <- compiler error - variable not instantiated
{
// code
}
``` | Captured variable instantiating problem | [
"",
"c#",
"lambda",
"captured-variable",
""
] |
I am interfacing with an ActiveX component that gives me a memory address and the number of bytes.
How can I write a C# program that will access the bytes starting at a given memory address? Is there a way to do it natively, or am I going to have to interface to C++? Does the ActiveX component and my program share the same memory/address space? | I highly suggest you use an IntPtr and Marshal.Copy. Here is some code to get you started.
memAddr is the memory address you are given, and bufSize is the size.
```
IntPtr bufPtr = new IntPtr(memAddr);
byte[] data = new byte[bufSize];
Marshal.Copy(bufPtr, data, 0, bufSize);
```
This doesn't require you to use unsafe code which requires the the /unsafe compiler option and is not verifiable by the CLR.
If you need an array of something other than bytes, just change the second line. Marshal.Copy has a bunch of overloads. | You can use [Marshal.Copy](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.copy.aspx) to copy the data from native memory into an managed array. This way you can then use the data in managed code without using [unsafe](http://msdn.microsoft.com/en-us/library/chfa2zb8.aspx) code. | Access memory address in c# | [
"",
"c#",
"memory-management",
"activex",
""
] |
I am writing a number of scripts to update numerous Access tables. I would like to add a column to each that has a field called "date\_created" that is a timestamp of when the record is created. Doing this through the table view is simple, simply set the DefaultValue = now(). However, how would I accomplish this in sql?
This is my current attempt for tables that already have the column. This example uses "tblLogs".
```
ALTER TABLE tblLogs ALTER COLUMN date_created DEFAULT now()
```
Thanks for your help!
Update - Would there be a way to do this in VBA?
Update 2 - Tested all of the answers and the following by onedaywhen is the shortest and most accurate
```
CurrentProject.Connection.Execute _
"ALTER TABLE tblLogs ALTER date_created DATETIME DEFAULT NOW() NOT NULL;"
``` | I'm assuming:
* your target database is the ACE or Jet engine, rather than SQL Server;
* you want the date *and* time i.e. what is known as `CURRENT_TIMESTAMP` in Standard SQL (not directly supported by ACE/Jet, though) and not to be confused with SQL Server's `TIMESTAMP` data type;
* you want an answer using SQL DDL.
If you created your table using this SQL DDL:
```
CREATE TABLE tblLogs
(
date_created DATETIME NOT NULL
);
```
then the following SQL DDL would add the `DEFAULT` your require:
```
ALTER TABLE tblLogs ALTER
date_created DATETIME DEFAULT NOW() NOT NULL;
```
The above ACE/Jet SQL syntax is ANSI-92 Query Mode flavour. To use this via the MS Access interface (e.g. a Query object's SQL view) see [Microsoft Office Access: About ANSI SQL query mode (MDB)](http://office.microsoft.com/en-gb/access/HP030704831033.aspx). To do this programmatically using SQL DDL requires (AFAIK) the use of OLE DB, which in VBA requires (AFAIK) the use of ADO. DAO always uses ANSI-89 Query Mode syntax, whose SQL DDL syntax lacks support for `DEFAULT`.
If you are using Access (rather than ACE/Jet standalone), you can use a single line of VBA (ADO) code:
```
CurrentProject.Connection.Execute "ALTER TABLE tblLogs ALTER date_created DATETIME DEFAULT NOW() NOT NULL;"
``` | Instead of now() you can use getdate(). Can't check other part of syntax (no sql here and I rarely change tables :)), but should be about same.
edit:
Seems that SQL doesn't allow change defaults so easily. Look at [this page](http://www.mssqltips.com/tip.asp?tip=1425), where practical example is provided - you need to change constraints, because MSSQL treats defaults as constraints. Sorry for misinformation. | Microsoft Access DateTime Default Now via SQL | [
"",
"sql",
"ms-access",
"vba",
"ddl",
""
] |
Lets say that I have a table with a timestamp column full of records and I want to calculate the smallest time difference between two consecutive records using only one query.
Maybe a table like...
```
CREATE TABLE `temperatures` (
`temperature` double,
`time` timestamp DEFAULT CURRENT_TIMESTAMP
);
``` | Assuming that there is a unique constraint on the time stamp (to prevent there being two recordings at the same time):
```
SELECT MIN(timediff(t1.`time`, t2.`time`)) AS delta_t,
FROM temperatures t1 JOIN temperatures t2 ON t1.`time` < t2.`time`
```
This answers the questions rather precisely - and doesn't convey other useful information (such as which two timestamps or temperatures). | What you need is analytical functions `LAG` and `MIN`.
They are missing in `MySQL`, but can be easily emulated using session variables.
This query returns all differences between consecutive records:
```
SELECT (temperature - @r) AS diff,
@r := temperature
FROM (
SELECT @r := 0
) vars,
temperatures
ORDER BY
time
```
This one returns minimal time difference:
```
SELECT (
SELECT id,
@m := LEAST(@m, TIMEDIFF(time, @r)) AS mindiff,
@r := time
FROM (
SELECT @m := INTERVAL 100 YEAR,
@r := NULL
) vars,
temperatures
ORDER BY
time, id
) qo
WHERE qo.id =
(
SELECT id
FROM temperatures
ORDER BY
time DESC, id DESC
LIMIT 1
)
```
See this article in my blog on how to emulate analytic functions in `MySQL`:
* [**Analytic functions: `FIRST_VALUE`, `LAST_VALUE`, `LEAD`, `LAG`**](http://explainextended.com/2009/03/10/analytic-functions-first_value-last_value-lead-lag/)
If you add a `PRIMARY KEY` to you table (which you should always, always do!), then you may use more `SQL`-ish solution:
```
SELECT temperature -
(
SELECT temperature
FROM temperatures ti
WHERE (ti.timestamp, ti.id) < (to.timestamp, to.id)
ORDER BY
ti.timestamp DESC, ti.id DESC
LIMIT 1
)
FROM temperatures to
ORDER BY
to.timestamp, to.id
```
This solution, though, is quite inefficient in `MySQL` due to the [**bug 20111**](http://bugs.mysql.com/bug.php?id=20111).
The subquery will not use the `range` access path, though it will use an index on (`timestamp`, `id`) for ordering.
This may be worked around by creating a `UDF` that returns previous temperature, given the current record's `id`.
See this article in my blog for details:
* [**Analytic functions: optimizing `LAG`, `LEAD`, `FIRST_VALUE`, `LAST_VALUE`**](http://explainextended.com/2009/03/12/analytic-functions-optimizing-lag-lead-first_value-last_value/)
IF you don't use any filtering conditions, then the solution which uses session variable will be the most efficient, though `MySQL` specific.
Similar solutions for `SQL Server` will look like this:
```
SELECT temperature -
(
SELECT TOP 1 temperature
FROM temperatures ti
WHERE ti.timestamp < to.timestamp
OR (ti.timestamp = to.timestamp AND ti.id < to.id)
ORDER BY
ti.timestamp DESC, ti.id DESC
)
FROM temperatures to
ORDER BY
to.timestamp, to.id
```
and
```
SELECT MIN(mindiff)
FROM (
SELECT timestamp -
(
SELECT TOP 1 timestamp
FROM temperatures ti
WHERE ti.timestamp < to.timestamp
OR (ti.timestamp = to.timestamp AND ti.id < to.id)
ORDER BY
ti.timestamp DESC, ti.id DESC
) AS mindiff
FROM temperatures to
ORDER BY
to.timestamp, to.id
) q
```
In `SQL Server`, this will work OK, provided you have an index on `(timestamp, id)` (or just on `(timestamp)`, if your `PRIMARY KEY` is clustered) | How to calculate the smallest period of time between consecutive events? | [
"",
"sql",
"mysql",
"timestamp",
""
] |
Is there any function which replaces params in a string? Something like this:
Code:
```
$format_str = "My name is %name."; /* this was set in a
configuration file - config.php */
$str = xprintf($format_str, array('name' => 'Joe', 'age' => 150));
/* above is somewhere in main code */
```
The expected value of $str after the operation is:
```
My name is Joe.
```
Update: I am aware of sprintf. But, it would not suffice in this case. I have modified the code to show what is the difference. | seems like [strtr](https://www.php.net/strtr) is what is a builtin function which can do the same. (got this from going thru drupal code).
```
>> $format_str = "My name is %name.";
My name is %name.
>> strtr($format_str, array('%name' => 'Joe', '%age' => 150))
My name is Joe.
``` | you could use this:
```
function xprintf($str, $array, $chr = '%') {
foreach ($array as &$key => $val) {
$key = $chr . $key;
}
return strtr($str, $array);
}
$str = xprintf('My name is %name', array('name' => 'Joe'));
``` | PHP variable replacement | [
"",
"php",
""
] |
Here's the deal. I've got articles and issues, both of which can have a release date. (Issues must, articles can.) Whichever date is earlier is the release date.
I've got all the logic for that basically worked out, and it all works perfectly, except I can't quite figure out the order clause to order by this release date. **What is the cleanest SQL method to implement this functionality?** I know basic SQL structure and whatnot, but not this sort of advanced logic...
Thanks in advance! --Matchu | This will work:
```
order by
case when article.date is not null and article.date<issue.date then article.date
else issue.date end
``` | Rather than locating the sort logic in the `ORDER BY` clause (as others propose here), I think you should expose the sort order to the 'end user' via the `SELECT` clause; if your DBMS is SQL-92 compliant, you can use just correlation names in the `ORDER BY` clause e.g.
```
SELECT COALESCE(CASE
WHEN V1.issue_release_date <= V1.article_release_date
THEN V1.issue_release_date
ELSE V1.article_release_date
END, V1.issue_release_date) AS considered_release_date,
<other columns here>
FROM ...
ORDER
BY considered_release_date, <other correlation names here>;
``` | Order by whichever date is earliest | [
"",
"sql",
"ruby-on-rails",
""
] |
I am planning to use libraries in my C++ program. Development is happening on Linux but application is designed to compile on both Linux and Windows. I understand direct equivalent for shared libraries(.so) in windows is DLL, right?
In Linux using g++, I can create shared library using `-fPIC` and `-shared` flags. AFAIK, there is no other code change required for a shared library. But things are different in a Windows DLL. There I should specify the functions which have to be exported using [dllexport](http://msdn.microsoft.com/en-us/library/3y1sfaz2(VS.80,printer).aspx), right?
My question is how do I manage this situation? I mean *dllexport* is invalid in Linux and the compiler will give an error. But it is required in Windows. So how do I write a function which will compile on both platforms without any code change?
**Compilers used**
* g++ - LINUX
* VC++ - Windows
Any help would be great! | We specify `__declspec(dllexport)` for class:
```
#define EXPORT_XX __declspec(dllexport)
class EXPORT_XX A
{
};
```
You can then check for platform and only define the macro on windows. E.g.:
```
#ifdef WIN32
#define EXPORT_XX __declspec(dllexport)
#else
#define EXPORT_XX
#endif
```
We mostly build static libraries so there might be more stuff to do for dynamic libs but the concept is the same - use preprocessor macro to define string that you need to insert into Windows code. | Another alternative is to just use a .def file for your windows project. This file specifies the DLL exports, so you won't have to mess up your code base. (But macros are definately the way to go if you want to avoid the extra file.) | Creating program libraries in Windows and LINUX [C++] | [
"",
"c++",
"windows",
"linux",
"shared-libraries",
""
] |
I want to be able to refactor 500 projects at the same time.
I have about 20 solutions and I don't have a master solution with everything because I haven't [figured out a way to auto generate it](https://stackoverflow.com/questions/414309/generate-solution-file-from-list-of-csproj).
Any suggestions?
Thanks
**Edit**
I've tried slnTools from codeplex to generate a solution and visual studio pretty much took down the entire operating system. Not sure if it was the solution not being generated properly or if it was just a limitation of Windows / Visual Studio. | What exactly is it you want to refactor? [ReSharper](http://www.jetbrains.com/resharper/download/) is probably the best known tool for large scale refactorings... but whether it is appropriate depends on *what* you want to do.
You could always download the trial and give it a whirl... | To create the huge solution, you should be able to start with a macro vaguely like this:
```
Dim d As New System.IO.DirectoryInfo(System.IO.Directory.GetCurrentDirectory())
For Each f As System.IO.FileInfo In d.GetFiles("*.*proj")
DTE.Solution.AddFromFile(f.FullName)
Next
DTE.Solution.Close(True)
```
---
Before you start the mega-refactoring, I'd suggest you use something like NDepend to analyze the dependency structure of the code, and compare it to your goals for refactoring. You'll only need projects in memory that will be affected by a particular refactoring. If you can limit the set that are needed, you'll greatly benefit.
If you can't get them all into memory, you should still be able to partition the work - you'll just have to repeat it. Consider the case where you've got a single class library that is used by ten other projects, and you want to refactor the public interface.
1. Save a copy of the class library
2. Load Project 1 and the class library, and do that refactoring. Close the solution.
3. Restore the class library from the saved copy.
4. Load Project 2 and the class library, and do that refactoring again. Close the solution.
etc. Finally, keep the last changed copy of the class library. If you really repeated the refactoring, all ten projects should be happy.
I'd also take the opportunity to refactor towards flexibility, so that you won't need to do this again. Accessing the class library through interfaces or facade classes can isolate you from changes in public interface. | Bulk Refactoring C# | [
"",
"c#",
"visual-studio",
"refactoring",
""
] |
> **This question already has an answer here:**
> [How do I enumerate an enum in C#?](https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum) *26 answers*
```
public enum Foos
{
A,
B,
C
}
```
Is there a way to loop through the possible values of `Foos`?
Basically?
```
foreach(Foo in Foos)
``` | Yes you can use the [`GetValues`](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues) method:
```
var values = Enum.GetValues(typeof(Foos));
```
Or the typed version:
```
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
```
I long ago added a helper function to my private library for just such an occasion:
```
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
```
Usage:
```
var values = EnumUtil.GetValues<Foos>();
``` | ```
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
``` | How to loop through all enum values in C#? | [
"",
"c#",
".net",
"enums",
"language-features",
""
] |
Java has primitive data types which doesn't derive from object like in Ruby. So can we consider Java as a 100% object oriented language? Another question: Why doesn't Java design primitive data types the object way? | When Java first appeared (versions 1.x) the JVM was really, really slow.
Not implementing primitives as first-class objects was a compromise they had taken for speed purposes, although I think in the long run it was a really bad decision.
"Object oriented" also means lots of things for lots of people.
You can have class-based OO (C++, Java, C#), or you can have prototype-based OO (Javascript, Lua).
100% object oriented doesn't mean much, really. Ruby also has problems that you'll encounter from time to time.
What bothers me about Java is that it doesn't provide the means to abstract ideas efficiently, to extend the language where it has problems. And whenever this issue was raised (see Guy Steele's "Growing a Language") the "oh noes, but what about Joe Sixpack?" argument is given. Even if you design a language that prevents shooting yourself in the foot, there's a difference between accidental complexity and real complexity (see [No Silver Bullet](http://www.cs.nott.ac.uk/~cah/G51ISS/Documents/NoSilverBullet.html)) and mediocre developers will always find creative ways to shoot themselves.
For example Perl 5 is not object-oriented, but it is extensible enough that it allows [Moose](http://www.iinteractive.com/moose/), an object system that allows very advanced techniques for dealing with the complexity of OO. And [syntactic sugar](http://search.cpan.org/~flora/MooseX-Declare-0.22/lib/MooseX/Declare.pm) is no problem. | No, because it has data types that are not objects (such as `int` and `byte`). I believe Smalltalk is truly object-oriented but I have only a little experience with that language (about two months worth some five years ago).
I've also heard claims from the Ruby crowd but I have *zero* experience with that language.
This is, of course, using the definition of "truly OO" meaning it only has objects and no other types. Others may not agree with this definition.
---
It appears, after a little research into Python (I had no idea about the name/object distinction despite having coded in it for a year or so - more fool me, I guess), that it may indeed be truly OO.
The following code works fine:
```
#!/usr/bin/python
i = 7
print id(i)
print type(i)
print i.__str__()
```
outputting:
```
6701648
<type 'int'>
7
```
so even the base integers are objects here. | Is Java 100% object oriented? | [
"",
"java",
"oop",
""
] |
I'm currently working with partner on a PHP project.
We both edit directly to a local server (all files are stored on the server, which is also running a WAMP stack).
I'm looking for an SVN client that will monitor and save all changes to the htdocs folder, and will update a remote SVN repository, through the web.
It would be a great bonus if I could manipulate the SVN client through a web-interface.
For example, say I save `file1.php` to the server. It would update `file1.php` on the svn website.
If I would suddenly discover that my latest revisions to the file are bad, I could head over to the server (or use some web interface from my computer), and replace `file1.php` with an older revision.
I don't want to just install an SVN server on our local machine because I would always like to have a copy saved remotely with the latest changes.
Any recommendations? | I do not know of any software to do this. It would probably not be hard to script this using the standard command line svn client. I.e. have a batch/shell script that runs regularly and checks in everything that has changed.
That said, I would *very strongly* advise against doing this!
The normal working model of source control is that everyone has a local copy to work in, then checks in their changes to a central repository.
The explicit manual checkin makes sure you only check in stuff that works (generally) and lets you give valuable checkin comments.
Then the server can be updated with a known good version from the source control repository.
It sounds like you are working on a production system. I'd strongly advise considering using a dev environment(s) and the above approach. | If i'm getting this right your intention is to use SVN as a versioned, automatic backup system. If this is the case, the most straightforward thing would be to use a file monitoring tool then call the svn command-line client for changed files to commit them to SVN. | good stand-alone svn client | [
"",
"php",
"svn",
"cvs",
"wamp",
""
] |
I've written a small, in house C# program which batch converts between various file formats, mostly relying on other API's. Currently, the UI spawns a BackgroundWorker (not a Thread) to handle the conversions, and then fills a queue with the requests which empties as the worker completes jobs. The queue object themselves are very small (3 Strings to tell the worker what to do) and don't contribute greatly to the program's memory footprint. I've been fairly draconian with my memory management (disposing of Images when finished with them, and manually garbage collecting at certain points.) Still, the program tends to use about 100 MB of memory at a time, and uses about 50% of total CPU time. It seems like if I naively implemented threading, it would quickly run out of system memory (unless the CLR does some sort of magic I don't know about.)
Is there a simple/efficient way to spawn threads to prevent the system from running out of memory besides catching OutOfMemory exceptions and rolling back the thread that died (seems very inefficient, but there's no way to preserve state without using prohibitive amounts of memory)? | If you use the [ThreadPool.QueueUserWorkItem](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx) to spawn the conversions you will automatically get a limit on how many threads that are running. The ThreadPool manages this internally and will process queued calls as soon as a pool thread becomes available. | Put a limit on the queue size and make sender wait if it's full. You would have to find the right queue size limit empirically though. | Preventing multithreaded apps from running out of memory | [
"",
"c#",
"multithreading",
"memory",
""
] |
I've got an MVC user control with the following basic structure:
```
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>
<%= Math.Round(Model) %>
```
Which gives this error message when I use it:
> Compiler Error Message: CS0452: The
> type 'decimal' must be a reference
> type in order to use it as parameter
> 'TModel' in the generic type or method
> 'System.Web.Mvc.ViewUserControl'
Is there a way to get this to work (somehow tricking the framework into treating the Decimal as a reference type maybe?) Or is what I'm trying to do just fundamentally wrong? | I would suggest you wrap the value type within a ViewModel. This will allow for some flexibility in the future (which may or may not be needed).
```
public class MyUserControlViewModel
{
public Decimal MyValue { get; private set; }
public MyUserControlViewModel(Decimal dec)
{
MyValue = dec;
}
}
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyUserControlViewModel>" %>
<%= Math.Round(Model.MyValue) %>
``` | Don't have to wrap into class, if you want a fast way, use this
```
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Nullable<Decimal>>" %>
```
also you can consider use
```
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
```
and validate by code | Using a value type in strongly typed MVC view user control | [
"",
"c#",
"asp.net-mvc",
""
] |
I'm looking for a way to find all controls on Window by their type,
*for example:* find all `TextBoxes`, find all controls implementing specific interface etc. | This should do the trick:
```
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null) yield return (T)Enumerable.Empty<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i);
if (ithChild == null) continue;
if (ithChild is T t) yield return t;
foreach (T childOfChild in FindVisualChildren<T>(ithChild)) yield return childOfChild;
}
}
```
then you enumerate over the controls like so
```
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}
``` | This is the easiest way:
```
IEnumerable<myType> collection = control.Children.OfType<myType>();
```
where control is the root element of the window.
EDIT - As pointed out in the comments. This only goes one level deep. See the accepted answer for an option that goes deeper. | Find all controls in WPF Window by type | [
"",
"c#",
".net",
"wpf",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.