Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a nice way to extract tokens that start with a pre-defined string and end with a pre-defined string?
For example, let's say the starting string is "[" and the ending string is "]". If I have the following string:
"hello[world]this[[is]me"
The output should be:
token[0] = "world"
token[1] = "[is"
(Note: the second token has a 'start' string in it) | I think you can use the [Apache Commons Lang](http://commons.apache.org/lang/) feature that exists in [StringUtils](http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html):
```
substringsBetween(java.lang.String str,
java.lang.String open,
java.lang.String close)
```
The API docs say it:
> Searches a String for substrings
> delimited by a start and end tag,
> returning all matching substrings in
> an array.
The Commons Lang substringsBetween API can be found here:
<http://commons.apache.org/lang/apidocs/org/apache/commons/lang/StringUtils.html#substringsBetween(java.lang.String,%20java.lang.String,%20java.lang.String)> | Here is the way I would go to avoid dependency on commons lang.
```
public static String escapeRegexp(String regexp){
String specChars = "\\$.*+?|()[]{}^";
String result = regexp;
for (int i=0;i<specChars.length();i++){
Character curChar = specChars.charAt(i);
result = result.replaceAll(
"\\"+curChar,
"\\\\" + (i<2?"\\":"") + curChar); // \ and $ must have special treatment
}
return result;
}
public static List<String> findGroup(String content, String pattern, int group) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
List<String> result = new ArrayList<String>();
while (m.find()) {
result.add(m.group(group));
}
return result;
}
public static List<String> tokenize(String content, String firstToken, String lastToken){
String regexp = lastToken.length()>1
?escapeRegexp(firstToken) + "(.*?)"+ escapeRegexp(lastToken)
:escapeRegexp(firstToken) + "([^"+lastToken+"]*)"+ escapeRegexp(lastToken);
return findGroup(content, regexp, 1);
}
```
Use it like this :
```
String content = "hello[world]this[[is]me";
List<String> tokens = tokenize(content,"[","]");
``` | Finding tokens in a Java String | [
"",
"java",
"string",
""
] |
I'm using the following code for rounding to 2dp:
```
sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double
```
It successfully rounds 6.666 to 6.67, but it doesn't work properly when rounding
5.555. It returns 5.55, whereas it should (at least in my opinion) return 5.56.
How can I get it to round up when the next digit is 5? i.e. return 5.56.
edit: I now realise that this is happening because when I enter 5.555 with cin it gets
saved as 5.554999997.
I'm going to try rounding in two stages- first to 3dp and then to 2dp. any other
(more elegant) ideas? | It seems you have to use math round function for correct rounding.
```
printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);
```
This gives the following output on my machine:
```
5.55 5.56
``` | The number `5.555` cannot be represented as an exact number in IEEE754. Printing out the constant `5.555` with `"%.50f"` results in:
```
5.55499999999999971578290569595992565155029300000000
```
so it *will* be rounded down. Try using this instead:
```
printf ("%.2f\n",x+0.0005);
```
although you need to be careful of numbers that *can* be represented exactly, since they'll be rounded up wrongly by this expression.
You need to understand the limitations of floating point representations. If it's important that you get accuracy, you can use (or code) a BCD or other decimal class that doesn't have the shortcoming of IEEE754 representation. | Rounding doubles - .5 - sprintf | [
"",
"c++",
"rounding",
"printf",
""
] |
I'm working on an container class that looks something like this:
```
class hexFile {
public:
HANDLE theFile;
unsigned __int64 fileLength;
hexFile(const std::wstring& fileName)
{
theFile = CreateFile(fileName.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
if (theFile == INVALID_HANDLE_VALUE);
{
throw std::runtime_error(eAsciiMsg("Could not open file!"));
}
BY_HANDLE_FILE_INFORMATION sizeFinder;
GetFileInformationByHandle(theFile, &sizeFinder);
fileLength = sizeFinder.nFileSizeHigh;
fileLength <<= 32;
fileLength += sizeFinder.nFileSizeLow;
};
~hexFile()
{
CloseHandle(theFile);
};
hexIterator begin()
{
hexIterator theIterator(this, true);
return theIterator;
};
hexIterator end()
{
hexIterator theIterator(this, false);
return theIterator;
};
};
```
And an iterator class to match that looks like this:
```
class hexIterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t>
{
hexFile *parent;
public:
bool highCharacter;
__int64 filePosition;
hexIterator(hexFile* file, bool begin);
hexIterator(const hexIterator& toCopy);
~hexIterator();
hexIterator& operator++()
{
return ++this;
}
hexIterator& operator++(hexIterator& toPlus);
hexIterator& operator--()
{
return --this;
}
hexIterator& operator--(hexIterator& toMinus);
hexIterator& operator=(const hexIterator& toCopy);
bool operator==(const hexIterator& toCompare) const;
bool operator!=(const hexIterator& toCompare) const;
wchar_t& operator*();
wchar_t* operator->();
};
```
My problem is... both classes need to implemented in terms of the other. I'm unsure how to reference the container inside the iterator, for example, because when the iterator is defined, the container hasn't been defined yet.
How might one accomplish this?
Billy3 | Forward declare one before the other. You can use references to a forward declared class in the declaration of another class, so this should work:
```
class hexFile; // forward
class hexIterator : ,,, {
...
};
class hexFile {
...
};
``` | Start your `.h` file with a forward reference:
```
class hexFile;
```
then follow with the full definition of `class hexIterator` (which will compile because it only needs a *pointer* to `hexFile`), then the full deifnition of `class hexFile` (which will compile just fine now because by then the compiler knows everything about `hexIterator`).
In the `.cpp` file, since you include the `.h` of course, everything will be known and you can implement the methods in any order you wish. | C++ Container / Iterator Dependency Problem | [
"",
"c++",
"iterator",
"containers",
""
] |
I want to convert `TIF` to an image type that is viewable in a web page.
The `TIFs` are black and white so `JPG` does not work well at all and ends up even larger after conversion.
Here are some tests I have performed using C# and `Image.Save` to do the conversion:
Orignal `TIF` is 7KB (bit depth: 1).
Converted to:
* JPG: 101KB (bit depth: 24)
* BMP: 256KB (bit depth: 1)
* GIF: 17KB (bit depth: 8)
* PNG: 11KB (bit depth: 1)
I then converted a multipage `TIF` which has 3 pages. Original size was 134KB (bit depth: 1).
Converted 3 images totals:
* JPG: 1324KB (bit depth: 24)
* BMP: 768KB (bit depth: 1)
* GIF: 221KB (bit depth: 8)
* PNG: 155KB (bit depth: 1)
I am starting with a multipage `TIF` and I need to convert to be viewable in a browser. It looks like `PNG` would be the best format to use based on my basic tests I have outlined above. Are there other image formats that I should be using / considering?
Are the any other options I am missing to get the file size down?
**EDIT:** I haved added more information regarding the bit depth of each format. The `BMP` and `PNG` maintain the same bit depth as the `TIF`. Is there a way to reduce the `GIF` or `JPG` bit depth to hopefully reduce the size significantly? | PNG is certainly your best choice here.
The reason your PNG ends up larger than the original TIF might be that the runtime doesn't do all the compression it possibly could. If you really need to compress every last little byte out of the PNG file, I would suggest using a tool like [AdvancePNG](http://advancemame.sourceforge.net/comp-readme.html) or [OptiPNG](http://optipng.sourceforge.net/) in order to compress the PNGs after you write them out. The author of OptiPNG has written a good article with links to a [few other PNG optimizers](http://optipng.sourceforge.net/pngtech/optipng.html). | Use PNG, it supports 1-bit color mode and works even in IE4 (if you don't need partial transparency). Do your customers use IE3? | What is the best web viewable format to save a TIF with a 1 bit depth? | [
"",
"c#",
".net",
"image",
"tiff",
""
] |
We have a social site, and want to integrate facebook connect to save time on the user needing to select their gender, etc. etc. and also use FB Connect as a method to skip signing up with us.
Each user on our site has a unique user name that they go by... One thing I can't wrap my head around, is if someone logs in with Facebook connect, how do I assign them a username? I mean, what if they dont want to user their real name? (assuming I would use their firstnameLastname, and add a number behind it if it existed already.. i.e: johnsmith, or johnsmith1, etc)
Perhaps I am confused, or am missing something... So how do I generate a user name?
I have the facebook connect button working, and it pops up with a slew of friends id's when they login...
so is there any good NON-facebook-made code samples? The runner app they have is a mess... | See [Facebook Connect documentation](http://wiki.developers.facebook.com/index.php/Facebook_Connect), esp [How To Write A Good Connect App](http://wiki.developers.facebook.com/index.php/How_To_Write_A_Good_Connect_App) and [Linking Accounts and Finding Friends.](http://wiki.developers.facebook.com/index.php/Account_Linking)
Facebook Connect, as I understand it, is like OpenID used by stackoverflow. The linking is done using hash of email address, but for your application's user name, you could pick whatever you want. You can mimic what stackoverflow does, and set it temporarily as "unknown (Facebook)" until the user picks a unique user name. The user can continue to log back into your site using Connect, so she can stay "unknown (Facebook)" forever, which some people do on this site too. | I think you can use the email address recieved from Facebook ;) | Generate a user name | [
"",
"php",
"facebook",
""
] |
How to compare IP Address that is stored in an array of Ip[0] with remote Endpoint?? Please Help me. | Something like this should work ...
```
var ips = new[] { IPAddress.Parse( "127.0.0.1"),
IPAddress.Parse( "192.168.1.1"),
IPAddress.Parse( "10.0.0.1" ) };
var ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
if (ips[0].Equals(ep.Address))
{
Console.WriteLine("Equal!");
}
``` | All the above variants will work but there's another option not mentioned here:
Use the IpAddress GetAddressBytes method to obtain the address as bytes and compare them. This could be usefull if you need to make other processing (such as figuring if an Ip is in an IP class or something like this).. | how to compare ip addresses | [
"",
"c#",
"sockets",
"ip-address",
""
] |
## Edit 1
Is it possible to do this with get/set? Something like the below? This works for me but I am worried I am missing something not to mention all the *staticness*.
```
///<summary>
/// Class to track and maintain Heads Up Display information
///</summary>
public static class HUD
{
///<summary>
///Declare variables to store HUD values
///</summary>
private static string _lastName;
private static string _firstName;
private static string _middleName;
private static string _suffix;
private static string _sSN;
private static string _personID;
private static string _masterID;
private static string _enrollmentID;
private static string _planID;
// Store a reference to THE form that holds the HUD and is visible
private static FrmModuleHost _frmHUDHost;
public static string PersonId
{
get { return _personID; }
set
{
FrmHudHost.tbxHUD_PersonID.Text = value;
_personID = value;
}
}
public static string SSn
{
get { return _sSN; }
set
{
FrmHudHost.tbxHUD_SSN.Text = value;
_sSN = value;
}
}
public static string MiddleName
{
get { return _middleName; }
set
{
FrmHudHost.tbxHUD_MiddleName.Text = value;
_middleName = value;
}
}
public static string FirstName
{
get { return _firstName; }
set
{
FrmHudHost.tbxHUD_FirstName.Text = value;
_firstName = value;
}
}
public static string LastName
{
get { return _lastName; }
set
{
FrmHudHost.tbxHUD_LastName.Text = value;
_lastName = value;
}
}
public static string Suffix
{
get { return _suffix; }
set
{
FrmHudHost.tbxHUD_SuffixName.Text = value;
_suffix = value;
}
}
public static string MasterID
{
get { return _masterID; }
set
{
FrmHudHost.tbxHUD_MasterID.Text = value;
_masterID = value;
}
}
public static string EnrollmentID
{
get { return _enrollmentID; }
set
{
FrmHudHost.tbxHUD_EnrollmontPeriod.Text = value;
_enrollmentID = value;
}
}
public static string PlanID
{
get { return _planID; }
set
{
FrmHudHost.tbxHUD_PlanID.Text = value;
_planID = value;
}
}
public static FrmModuleHost FrmHudHost
{
get { return _frmHUDHost; }
set { _frmHUDHost = value; }
}
}
```
---
## Original Post
I have a class that is responsible for updating a Heads Up Display of current selected member info. My class looks like this -->
```
public static class HUD
{
///<summary>
///Declare variables to store HUD values
///</summary>
public static string _lastName;
public static string _firstName;
public static string _middleName;
public static string _suffix;
public static string _sSN;
public static string _personID;
public static string _masterID;
public static string _enrollmentPeriod;
public static string _planID;
///<summary>
/// Method to update the display with current information
///</summary>
public static void UpdateHUD (FrmModuleHost frm, params String[] args)
{
frm.tbxHUD_LastName.Text = args[0];
_lastName = args[0];
frm.tbxHUD_FirstName.Text = args[1];
_firstName = args[1];
frm.tbxHUD_MiddleName.Text = args[2];
_middleName = args[2];
frm.tbxHUD_SSN.Text = args[3];
_sSN = args[3];
frm.tbxHUD_PersonID.Text = args[4];
_personID = args[4];
}
}
```
What I am trying to figure out is how I can tell what args are being passed. What you see below is what is called from the Search Page as that is all that is available at that point. The other 4 values will be loaded 1 at a time on various pages. A person HAS A enrollment which HAS A plan if that helps.
```
private void GetResults()
{
var lName = getCurrentRowVal("Last Name");
var fName = getCurrentRowVal("First Name");
var pID = getCurrentRowVal("Person ID");
var sSN = getCurrentRowVal("SSN");
var mName = getCurrentRowVal("Middle Name");
HUD.UpdateHUD(FrmWwcModuleHost, lName, fName, mName, sSN, pID);
}
```
Now when I call this from the Enrollment Page I will want everything to stay and add the EnrollmentID.
```
private void GetResults()
{
var enrollmentID = getCurrentRowVal("EnrollmentID");
HUD.UpdateHUD(FrmWwcModuleHost, enrollmentID);
}
```
My question is, How do I do that and know which arg[] index to call and not overwrite the existing values?
Is it as simple as always providing ALL parameters as they are set? So my call from the Enrollment Page would instead look like this -->
```
private void GetResults()
{
var enrollmentID = getCurrentRowVal("EnrollmentID");
HUD.UpdateHUD(FrmWwcModuleHost, HUD._lastName, HUD._firstName, HUD._middleName, HUD._sSN, HUD._personID, enrollmentID);
}
```
Thanks for any insights! | I did not see a reference to a particular version of .net you are using. Here is how I handle this in .net 3.5.
First create a class for passing the update values in, but make all of the properties nullable (since all of your items are string, they are already nullable). If the values are nullable, add actual property setters, and LastNameChanged properties.
```
public class UpdateData {
public string LastName { get; set;};
public string FirstName { get; set;};
public string MiddleName { get; set;};
...
}
```
Now your method signature looks like this:
```
public static void UpdateHUD (FrmModuleHost frm, UpdateData data)
{
if (!string.IsNullOrEmpty(data.FirstName) {
frm.tbxHUD_LastName.Text = data.FirstName;
_lastName = data.FirstName;
}
if (!string.IsNullOrEmpty(data.LastName) {
frm.tbxHUD_FirstName.Text = data.LastName;
_firstName = data.FirstName;
}
if (!string.IsNullOrEmpty(data.MiddleName) {
frm.tbxHUD_MiddleName.Text = data.MiddleName;
_middleName = data.FirstName;
}
```
Next is the setting the UpdateData and calling the method:
```
UpdateHUD(FrmWwcModuleHost, new UpateData{ FirstName = "test1", LastName = "test2", ...});
```
Final note: you are using a lot of statics here. You might consider changing most of them. Move the static variables to an actual class with properties (but no statics), and reference the class in your code. | You'll really need to ditch the params style call and establish real parameters for your methods. Just create multiple overloads for your most common call signatures. | Correct use of Properties to maintain a HUD in a nested Form? | [
"",
"c#",
"winforms",
"oop",
"properties",
""
] |
In Python, is there a way to bind an unbound method without calling it?
I am writing a wxPython program, and for a certain class I decided it would be nice to group the data of all of my buttons together as a class-level list of tuples, like so:
```
class MyWidget(wx.Window):
buttons = [
("OK", OnOK),
("Cancel", OnCancel)
]
...
def setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).bind(wx.EVT_BUTTON, handler)
```
The problem is, since all of the values of `handler` are unbound methods, my program explodes in a spectacular blaze and I weep.
I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn’t find anything. Right now, I am using `functools.partial` to work around this, but does anyone know if there’s a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it? | All functions are also *descriptors*, so you can bind them by calling their `__get__` method:
```
bound_handler = handler.__get__(self, MyWidget)
```
Here's R. Hettinger's excellent [guide](https://docs.python.org/2/howto/descriptor.html) to descriptors.
---
As a self-contained example pulled from [Keith's](https://stackoverflow.com/users/834176/keith-pinson) [comment](https://stackoverflow.com/questions/1015307/python-bind-an-unbound-method#comment8431145_1015405):
```
def bind(instance, func, as_name=None):
"""
Bind the function *func* to *instance*, with either provided name *as_name*
or the existing name of *func*. The provided *func* should accept the
instance as the first argument, i.e. "self".
"""
if as_name is None:
as_name = func.__name__
bound_method = func.__get__(instance, instance.__class__)
setattr(instance, as_name, bound_method)
return bound_method
class Thing:
def __init__(self, val):
self.val = val
something = Thing(21)
def double(self):
return 2 * self.val
bind(something, double)
something.double() # returns 42
``` | This can be done with [`types.MethodType`](https://docs.python.org/3/library/types.html#types.MethodType):
```
import types
bound_handler = types.MethodType(handler, self)
``` | How to bind an unbound method without calling it? | [
"",
"python",
"class",
"methods",
"bind",
""
] |
C++ standard says in section 4.12,
*An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false any other value is converted to true.*
Which means that the following code is valid,
```
if(5)
std::cout << "WOW!";
```
It is syntactically valid but semantically it doesn't make any sense. My question is why C++ is allowing such strange things? AFAIK, it is not making any advantage rather than making confusion. | I *think* it's historical, and a by product of how C used to evaluate bool like concepts...
C didn't use to have a boolean type, and in the 'down to the metal' paradigm of C, pointers and numeric types, etc. that were set to NULL were also implicitly `false`.
If you think of it as 'nothing/zero == `false`' and 'anything else == `true`' it actually does make sense. | Actually, in many languages, including C/Python/Perl/BASIC non-zero integer/pointer value
is always considered true, 0 considered false.
This is known conventions in many programming languages, so there is no reason, why this shoudn't be in C++?
The question is why in Java this is not so? | Why C++ allows arithmetic or enumeration values to be implicitly converted to boolean? | [
"",
"c++",
"boolean",
""
] |
I tried, to no avail! **My problem is php's setcookie() fails in IE6.** It's fully functioning (albeit buggy) for Firefox 3 and IE7/8. The following is the code. IE6 displays fail. Simple question: why?
```
<?
header('P3P: CP="DEV PSAi NAV STP DEM OTRo NOI IDC
DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
setcookie('hello', 'poopoo');
echo $_COOKIE['hello'];
?>
```
**I suspected P3P** ([link](http://www.sitepoint.com/article/p3p-cookies-ie6/2/)), **or maybe some bug with the timezone**-- IE6 javascript not converting time to the same standard that php uses (so that all server-issued cookies are automatically expired).
Here's what I've done:
For the p3p issue, I inserted the above header tag. I've also created a policy file, and a policy reference, and run the my site through w3c's p3p checker with no errors.
For the timezone issues, I reset the time zone in browscap.ini. I also tweaked my clock forward, and backward by 24 hours.
If you can give me any new things to try, it would be very much appreciated. All I need is a Hello World cookie setter for IE6.
I appreciate it.
\*Update: **I caught wind that the standalone IE6 has issues that match this. Can anyone with IE6 do a quick check that you can add items to the cart on my [alpha](http://mgxvideo.com/mgxcopy-alpha)?** | **Final Update: Bug caused by standalone ie6 run on vista. Dl'ed official msft virtual pc and virtual hd and the site worked perfect.** | What are the security settings for IE?
Could it be that the security settings on it don't allow you to write cookies for it? | PHP + ie6 + cookies: failing a hello world world for cookies | [
"",
"php",
"cookies",
"internet-explorer-6",
"setcookie",
""
] |
i have a page on which i have some rating function like people who like the post can rate up or who don't can rate down.
on that link im calling a php file with some parameters passed in the anchor tag. Then in that php file im saving that rating with +1 or -1 (whichever is the case) in the database and after doing that im redirecting to that first page from where we have rated.
Now this whole function is reloading my whole page which i dont want.Is there any way with which i can do this rating without reloading the page,i want that when a person clicks on rate then just after click the rating should be shown according to what the user just did(+ or -) and that too without reloading the whole page.Is there any way to do that in php??????? | Yes, it's called "Ajax". However, you don't do this on the server-side with PHP, you do it on the client-side with JavaScript. There are [plenty of tutorials](http://www.google.com/search?q=ajax+tutorial&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) around, I suggest you take a look.
Note that there are many JavaScript libraries out there to make this extremely easy. I'd recommend taking a look at [jQuery](http://jquery.com/) because I've personally found it to be the easiest to learn and use. | It seems a few answers have already been posted recommending different libraries. If you would like the avoid the (admittedly minimal) overhead of an included library, the following tutorial shows how to use a simple XMLHttpRequest object.
<http://www.xul.fr/en-xml-ajax.html>
The "xhr.responseText" is what you would receive back from the php processing (which would typically be done in a small, single-purpose script seperate from the primary page). | rating system without reloading a page | [
"",
"php",
""
] |
I have an ASP.NET Project. I am connecting to the DB and then closing and disposing of the connection object. But when anyone enters my site, MS Access creates a temporary dbname.ldb. When I want to download my original mdb file from my server it won't let me access the mdb file. I can't do anything if there is ldb file in server. It's locking mdb file and I can't move it. So what's the problem? I am opening connection and closing it. So why this ldb file not deleting itself after the connection is closed. | The connection can be left open if the scripts produces an error of any kind before to close it. Check the scripts with a customized error 500 page that logs in a text file the errors and you will see if this is the case. Anyway the ldb file is not dangerous so you can create a script to remove them once a day or so. This is one of the drawbacks about working web applications with MS Access. Try to migrate to MSSQL if you can or to MySQL, this last can be used from .NET or classic ASP with no problem with ADO or ADO.NET with the appropiate driver. | Your web application within IIS is keeping the connection open with connection pooling. The IIS application will eventually close if there are no further connections within the time IIS is set to terminate your web application or you can restart the application (and copy the file before anyone gets in).
That's just one reason Access is not a good choice of database for this kind of application. | How Can I Remove Access Db's temporary ldb file | [
"",
"c#",
"asp.net",
"ms-access",
"ado.net",
"jet",
""
] |
What's the difference between a .class file and a .java file? I am trying to get my applet to work but currently I can only run it in Eclipse, I can't yet embed in HTML.
Thanks
\*\*Edit: How to compile with JVM then? | A .class file is a compiled .java file.
.java is all text and is human readable.
.class is binary (usually).
You compile a java file into a class file by going to the command line, navigating to the .java file, and running
```
javac "c:\the\path\to\your\file\yourFileName.java"
```
You must have a java SDK installed on your computer (get it from [Oracle](http://www.oracle.com/technetwork/java/javase/downloads/index.html)), and make sure the javac.exe file is locatable in your computer's PATH environment variable.
Also, check out Java's **[Lesson 1: Compiling & Running a Simple Program](http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.html)**
If any of this is unclear, please comment on this response and I can help out :) | * .class -> compiled (for JVM)
* .java -> source (for humans) | .class vs .java | [
"",
"java",
"class",
"applet",
""
] |
I'm writing a class-library (IE BHO) in C# and currently wrangling with the large volume of what I think is junk output coming from REGASM's generated registry keys.
The short version is this: I only want to expose a handful of classes (currently: ONE class) to IE (and the rest of COM). Only one class has the ClassInterfaceAttribute and GUID stuff set, and I can test that the add-on only requires the COM registry keys for this class -- and yet, REGASM generates GUIDs and registry keys for every class in the entire project.
This is annoying and somewhat disturbing as I do not want my class names sitting in users' registry unless they absolutely *have* to be there.
To be fair, many of those other classes are marked public because I use them in a driver app from another project in the same solution, to work around IE's debugging black hole...
I'm still very green to COM in general (especially relating to .Net) and I was wondering what is the best way to hide all my other classes from regasm? Or, at least, why these classes that -- even though they are marked public -- are showing up when I haven't set any of the COM flags for them?
Thanks! | Use `internal` access modifier for stuff that doesn't need to have `public` modifier. For stuff that really needs `public` access use ComVisible attribute to partially hide it.
For example:
```
[ComVisible(false)]
public class ClassToHide {
//whatever
};
public class ClassToExpose {
public void MethodToExpose() {}
[ComVisible(false)]
public void MethodToHide() {}
};
```
All public member functions and member variables of all public classes are COM-visible by default. So first think of making them internal and if you really need them public hide them from COM with ComVisible. | Try using the /regfile switch - this will output a reg file rather than directly writing all your class names to the registry.
When you have the .reg file you can remove any entries you dont want to be added to the target systems registry, and deploy only those values to the target machine. Depending on how you choose to deploy your software, this might be easier and you would not have to change the code for any of your types.
In fact if you dont have access to the sourcecode, this would be the only way to achieve this. | C#: Regasm generating registry entries for every class in my COM DLL? | [
"",
"c#",
".net",
"com",
"registry",
"regasm",
""
] |
In my program, we store a user's IP address in a record. When we display a list of records to a user, we don't want to give away the other user's IP, so we SHA1 hash it. Then, when the user clicks on a record, it goes to a URL like this:
```
http://www.example.com/allrecordsbyipaddress.php?ipaddress=SHA1HASHOFTHEIPADDRESS
```
Now, I need to list all the records by the IP address specified in the SHA1 hash. I tried this:
```
SELECT * FROM records
WHERE SHA1(IPADDRESS)="da39a3ee5e6b4b0d3255bfef95601890afd80709"
```
but this does not work. How would I do this?
Thanks,
Isaac Waller | I'd store the SHA1 of the IP in the database along with the raw IP, so that the query would become
```
SELECT * FROM records WHERE ip_sha1 = "..."
```
Then I'd make sure that the SHA1 calculation happens *exactly one place* in code, so that there's no opportunity for it be be done slightly differently in multiple places. That also gives you the opportunity to mix a salt into the calculation, so that someone can't simply compute the SHA1 on an IP address they're interested in and pass that in by hand.
Storing the SHA1 hash the database also gives you the opportunity to add a secondary index on ip\_sha1 to speed up that SELECT. If you have a very large data set, doing the SHA1 in the WHERE clauses forces the database to do a complete table scan, along with redoing a calculation for every record on every scan. | Don't know if it matters, but your `SHA1` hash `da39a3ee5e6b4b0d3255bfef95601890afd80709` is a well-known hash of an empty string.
Is it just an example or you forgot to provide an actual `IP` address to the hash calculation function?
**Update:**
Does your webpage code generate `SHA1` hashes in lowercase?
This check will fail in `MySQL`:
```
SELECT SHA1('') = 'DA39A3EE5E6B4B0D3255BFEF95601890AFD80709'
```
In this case, use this:
```
SELECT SHA1('') = LOWER('DA39A3EE5E6B4B0D3255BFEF95601890AFD80709')
```
, which will succeed.
Also, you can precalculate the `SHA1` hash when you insert the records into the table:
```
INSERT
INTO ip_records (ip, ip_sha)
VALUES (@ip, SHA1(CONCAT('my_secret_salt', @ip))
SELECT *
FROM ip_records
WHERE ip_sha = @my_salted_sha1_from_webpage
```
This will return you the original `IP` and allow indexing of `ip_sha`, so that this query will work fast. | SQL SHA1 inside WHERE | [
"",
"sql",
"mysql",
"sha1",
"where-clause",
""
] |
> **Possible Duplicate:**
> [Whats the difference between the 'ref' and 'out' keywords?](https://stackoverflow.com/questions/388464/whats-the-difference-between-the-ref-and-out-keywords)
What is the difference between `ref` and `out`? I am confused about when to use `ref` and `out`. So please explain how to use `ref` and `out`, and in which situations. | * You use **Ref** when you pass an initialized parameter and you expect the method/function to modify it.
* You use **Out** when you pass an un-initialized parameter and the method will have to initialize and fill that parameter (you get a warning or even error otherwise).
bool IsUserValid(string username);
void IsUserValid(string username, out bool valid);
The declarations above are roughly the same. It's easier to return the value, so in this case you will use the return type. But if your method also needs to return the birth date of the user you can't return both parameters in the return, you have to use out parameters to return one of them (or void the method and return both as out). | One thing to watch out for is when (not) to use "ref" with reference-type parameters.
The "ref" is for the reference itself, not for the contents of the object that the reference points to.
If you pass a reference "by value" (that is, without 'ref' or 'out'), you can't change the **reference** (so a "new" will not survive the call), you can however still change the values of the properties this reference points to (if the class allows so). | What is diff Between Ref And Out? | [
"",
"c#",
".net",
"syntax",
""
] |
I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it `next();` calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java. | There's a method in the excellent [Google Collections](https://github.com/google/guava) library which does this:
```
Set<String> names = ...;
Iterable<String> infinite = Iterables.cycle(names);
```
(I can't recommend the Google Collections library strongly enough. It rocks very hard. I'm biased as I work for Google, but I think pretty much every Googler writing Java would tell you how useful the collections are.) | ```
Iterator it = mylist.iterator();
while (it.hasNext())
{
MyType t = (MyType)it.next();
// do something
if (!it.hasNext())
it = mylist.iterator();
}
``` | How can I make an iterator that never ends? | [
"",
"java",
"iterator",
"infinite",
""
] |
I am trying to play audio in a Java applet but it is not working. What could be the problem?
EDIT: Besides the limited number of files that Java can play, the problem was that I didn't realize that the bin folder (in Eclipse workspace) contains the .class file that is run. So my code referring to the getDocumentBase() couldn't find the audio file. -\_-"
```
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Viewer extends Applet
implements MouseListener, MouseMotionListener {
AudioClip sound1;
AudioClip tap;
AudioClip clap;
public void init() {
sound1 = this.getAudioClip(getDocumentBase(),"boom.au");
tap = getAudioClip(getDocumentBase(), "tap.au");
clap = getAudioClip(getDocumentBase(), "clap.au");
this.resize(600,600);
addMouseListener(this);
setBackground(Color.BLACK);
}
public void paint (Graphics g) {
}
public void mouseClicked(MouseEvent e) {
sound1.play();
System.out.println("BOOM!");
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
tap.play();
System.out.println("tap!");
}
public void mouseReleased(MouseEvent e) { }
public void mouseDragged(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
}
``` | EDIT: Besides the limited number of files that Java can play, the problem was that I didn't realize that the bin folder (in Eclipse workspace) contains the .class file that is run. So my code referring to the getDocumentBase() couldn't find the audio file. -\_-" | It appears that Sun's applet implementation is very choosy about exactly what sounds formats it will play. Specifically ["Currently, the Java [applet] API supports only one sound format: 8 bit, µ-law, 8000 Hz, one-channel, Sun ".au" files."](http://java.sun.com/docs/books/tutorial/deployment/applet/sound.html) | Audio in Java Applet not playing | [
"",
"java",
"applet",
"audio",
""
] |
I've been shifting through the drupal documentation and forums but it's all a little daunting. If anyone has a simple or straight forward method for adding fields to the Site information page in the administration section i'd really appreciate it.
As a background, i'm just trying to add user customizable fields site wide fields/values. | In a custom module, you can use `hook_form_alter()` to add extra fields to that form. For example:
```
function mymodule_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'system_site_information_settings') {
$form['my_module_extra_setting'] = array(
'#type' => 'checkbox',
'#title' => t('Use my setting'),
'#default_value' => variable_get('my_module_extra_setting', TRUE),
);
}
}
```
Anywhere in your code you need access to the saved setting itself, you can use the same call that's used to populate that form element's default value: `variable_get('my_module_extra_setting', TRUE)` | In order to save the value from your new custom field you will need to add a second submit item to the submit array eg:
```
$form['#submit'][] = 'misc_system_settings_form_submit';
```
and then add a function to handle the submission, eg:
```
function misc_system_settings_form_submit($form_id, $form_values) {
// Handle saving of custom data here
variable_set('access_denied_message', $form_values['values']['custom_access_denied_message']);
}
``` | Add fields to the Site information section on Drupal 6.12 | [
"",
"php",
"drupal",
"content-management-system",
"drupal-6",
"content-management",
""
] |
I have a pretty large table: 20+ million rows and I need to update about 5% of that - or 1 million rows.
Unfortunately, I am updating the (int) column that is being used as the clustered index.
**My question is:
What is the fastest way to update these rows?**
I have tried updating the rows directly:
```
update t1
set t1.groupId = t2.groupId
from
table t1
join newtable t2 on t1.email = t2.email
```
but this takes WAY too long (I stopped it after 3 hours)
I assume that this is because the entire row (which has 2 datetimes, 2 varchars, and 2 ints) is being moved around for each update.
What if I dropped the clustered index first, then did the updates, then recreated the clustered index? Would that be faster?
Note: I have a nonclustered index on email, in case anyone thinks it's the select part of the query that is slow. It's not. | Here's what I did (and it was much faster):
1. I dropped the clustered index.
2. I ALSO dropped foreign keys
references (the two other int
columns).
3. I ran the update statement
4. I recreated the index, which was faster than expected. (This is the original reason I asked SO first).
This brought the entire process down to a matter of seconds. **Yes, ~ 1 million rows in about 15 seconds.**
The second step was crucial because the foreign keys were forcing the update to do some sort of spool on the related tables, which each also have a large number of rows.
The number of physical reads were tripled because of these foreign key lookups.
I'm not sure why SQL Server needs to do that, but my guess is that it still performs the integrity check even if I'm not updating that column but I am moving the entire row (clustered column update).
---
As a side note, I had also tried running the update in batches:
```
update top(1000) t1
set t1.groupId = t2.groupId
from
table t1
join newtable t2 on t1.email = t2.email
```
This was fine (and seemed to scale up to about 10K per batch) but it still was on the order of 1-2 minutes each batch.
---
In summary, I've learned that for bulk updates, temporarily removing indexes can be very helpful. | I think the comment earlier is right. You have sort of answered your own question.
Because
> Clustered indexes sort and store the
> data rows in the table based on their
> key values (source msdn),
you may be better just dropping the clustered index (keep the index on email). When the operation is done then recreating the clustered index.
As long as groupid is not involved in any other indexes I wouldn't touch them. If group id is involved in other indexes then drop them. I would leave at least an index on email, just to make the join fast. | How to speed up a massive update to the clustered column? | [
"",
"sql",
"sql-server",
"performance",
"indexing",
""
] |
HTML markup:
```
<ul id="portfolio"><li class="web">
<span class="info">August 2007 <a href="http://awebsite.com" rel="external">visit</a></span>
<a href="/assets/image.jpg" class="fancybox" rel="web">
<img src="/assets/imagelarge.jpg" alt="Rising Star Ranch" />
<span class="title">Some Title</span> Some other text...
</a>
</li>
</ul>
```
jQuery:
```
$("ul#portfolio li").fadeTo("slow", 0.3);
```
In Firefox 3 and 3.5 as well as IE7, this behaves as expected and fades out all elements within the 'li'. In IE8, nothing is faded at all, and no Javascript errors show up when debugging.
The page is located at
<http://joecoledesign.com/portfolio>
Thanks! | Have you tried putting quotes around ul#portfolio li ? The selector is just a string, so it needs quotes. Without quotes doesn't work even in my Firefox.
```
$("ul#portfolio li").fadeTo("slow", 0.3);
```
Edit: OK, try to apply the fade to all subelements: span and img one by one for starters. It could indeed be an IE bug.
Edit: you are also missing a closing quote on the id="portfolio". Come on, man, try to work these things out before you post.
Edit: btw, the above works fine in IE8 - I just put it together and threw it up into a blank IE8 page - the whole thing faded.
Edit: It's quite possible something else on your page is doing it as it works fine standalone. | Very cool page Joe! The only thing that comes to mind WRT IE8 is that jQuery may not have caught up to it, or that something may be funny with your browser (such as your javascript settings may be tweaked). | IE8 jQuery FadeTo | [
"",
"javascript",
"jquery",
"xhtml",
"internet-explorer-8",
""
] |
I know that `WebForms` has a `RadioButtonList` control, but I can't find one for `WinForms`. What I need is to have 3 RadioButtons grouped together, so that only 1 can be selected at a time. I'm finding that I have to do this through code, which is a pain. Am I just not seeing `RadioButtonList` somewhere, or does it really not exist in `WinForms`? | [Apparently not](http://bytes.com/groups/net-vb/378283-where-radiobuttonlist).
You can group three RadioButtons together using a GroupBox or a Panel [as is done here](http://msdn.microsoft.com/en-us/library/sefz7fxc.aspx). | If you just want to group radio buttons, it's enough to put them in a container, then they will act like a group, but if you need data-binding like how a [`ComboBox`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox?WT.mc_id=DT-MVP-5003235&view=netframework-4.8) or [`ListBox`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listbox?WT.mc_id=DT-MVP-5003235&view=netframework-4.8) or [`CheckedListBox`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.checkedlistbox?WT.mc_id=DT-MVP-5003235&view=netframework-4.8) works, you need a `RadioButtonList` control.
Windows forms doesn't have a built-in `RadioButtonList` control. You can create your own control by deriving form `ListBox` and making it owner-draw and draw radio buttons yourself. This is the way which `CheckedListBox` is created as well.
This way, the control supports data-binding and will benefit from all features of `ListBox`, including `DataSource`, `SelectedValue`, `DisplayMember`, `ValueMember` and so on. For example you can simply use it this way:
```
this.radioButtonList1.DataSource = peopleTable;
this.radioButtonList1.DisplayMember = "Name";
this.radioButtonList1.ValueMember= "Id";
```
Or for example for an `enum`, simply this way:
```
this.radioButtonList1.DataSource = Enum.GetValues(typeof(DayOfWeek));
```
In below image, the second `RadioButtonList` is disabled by setting `Enabled = false;`:
[](https://i.stack.imgur.com/w8uxK.png)
[](https://i.stack.imgur.com/NbzCB.png)
Also the control supports right to left as well:
[](https://i.stack.imgur.com/MKIvM.png)
It also supports multi column:
[](https://i.stack.imgur.com/7S8xe.png)
## RadioButtonList
Here is the source code for control. You can use it like a normal `ListBox` by adding items or setting data source with/without using data-binding:
```
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
public class RadioButtonList : ListBox
{
Size s;
public RadioButtonList()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
using (var g = Graphics.FromHwnd(IntPtr.Zero))
s = RadioButtonRenderer.GetGlyphSize(
Graphics.FromHwnd(IntPtr.Zero), RadioButtonState.CheckedNormal);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
var text = (Items.Count > 0) ? GetItemText(Items[e.Index]) : Name;
Rectangle r = e.Bounds; Point p;
var flags = TextFormatFlags.Default | TextFormatFlags.NoPrefix;
var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
var state = selected ?
(Enabled ? RadioButtonState.CheckedNormal :
RadioButtonState.CheckedDisabled) :
(Enabled ? RadioButtonState.UncheckedNormal :
RadioButtonState.UncheckedDisabled);
if (RightToLeft == System.Windows.Forms.RightToLeft.Yes)
{
p = new Point(r.Right - r.Height + (ItemHeight - s.Width) / 2,
r.Top + (ItemHeight - s.Height) / 2);
r = new Rectangle(r.Left, r.Top, r.Width - r.Height, r.Height);
flags |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
}
else
{
p = new Point(r.Left + (ItemHeight - s.Width) / 2,
r.Top + (ItemHeight - s.Height) / 2);
r = new Rectangle(r.Left + r.Height, r.Top, r.Width - r.Height, r.Height);
}
var bc = selected ? (Enabled ? SystemColors.Highlight :
SystemColors.InactiveBorder) : BackColor;
var fc = selected ? (Enabled ? SystemColors.HighlightText :
SystemColors.GrayText) : ForeColor;
using (var b = new SolidBrush(bc))
e.Graphics.FillRectangle(b, e.Bounds);
RadioButtonRenderer.DrawRadioButton(e.Graphics, p, state);
TextRenderer.DrawText(e.Graphics, text, Font, r, fc, bc, flags);
e.DrawFocusRectangle();
base.OnDrawItem(e);
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override SelectionMode SelectionMode
{
get { return System.Windows.Forms.SelectionMode.One; }
set { }
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override int ItemHeight
{
get { return (this.Font.Height + 2); }
set { }
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override DrawMode DrawMode
{
get { return base.DrawMode; }
set { base.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; }
}
}
``` | WinForms RadioButtonList doesn't exist? | [
"",
"c#",
"winforms",
"radio-button",
"radiobuttonlist",
""
] |
I read When to Use Static Classes in C# but the top answer didn't necessarily answer my question. I've an application that interfaces with quite a bit of similar hardware, via an HTTP server. Each device must be logged into and the credentials are normally the same. I'm using Properties.Settings.Default.etc to handle application wide settings; however, for the ease I keep track of the last used username/password when individually logging into a device. The defaults that are settable through an options window are used first and remain the same unless changed via the options window, despite the temporary settings changing and being used in the defaults stead.
Anyway, that's the scenario...with regards to the question, I'm doing this:
```
private static class TemporarySettings
{
public static string Username = Properties.Settings.Default["Username"].ToString();
public static string Password = Properties.Settings.Default["Password"].ToString();
}
```
Is that stupid? | It's not stupid, and it may solve your problem perfectly (if it does, don't change it). There are some problems that this approach might cause down the road, though, and it helps to know what those are.
1. If you want to change the user name and password without restarting your application, you won't have that option. You can write logic to watch the config file for change and reload the values if they change.
2. If you want to "reuse" your code (especially if you put more behavior like monitoring for change) for multiple sets of username and password, you'll need to convert this to an instance.
3. If you ever want to unit test classes that depend on this class, you will have a very difficult time stubbing the values.
To reiterate, though, you shouldn't shy away from the simplest solution (as you have defined) because of these *potential* issues unless you think there's a realistic chance that you'll be burned by them in the future. Otherwise, it will probably not be a very difficult refactoring to switch to an instance class later when the need arises. | Even better, mark them `readonly` or use properties that only have a getters. | Static classes...is it OK to do this? | [
"",
"c#",
"class",
"static",
""
] |
I want to pass a file path as a parameter to an executable from PHP, and the file path may contain spaces. The executable doesn't seem to handle quotes around the parameter, so I thought maybe I could pass the short DOS name instead of the long name.
Does PHP know anything about the old-style DOS 8.3 file names? | php/win32 ships with the [COM/.net extension built-in](http://de.php.net/manual/en/com.installation.php). You can use it to create a WSH [FileSystemObject](http://msdn.microsoft.com/en-us/library/6kxy1a51(VS.85).aspx) and then query the [ShortPath property](http://msdn.microsoft.com/en-us/library/htyh9b2z(VS.85).aspx) of the [File object](http://msdn.microsoft.com/en-us/library/1ft05taf(VS.85).aspx).
```
<?php
$objFSO = new COM("Scripting.FileSystemObject");
$objFile = $objFSO->GetFile(FILE);
echo "path: ", $objFile->Path, "\nshort path: ", $objFile->ShortPath;
```
prints e.g.
```
path: C:\Dokumente und Einstellungen\Volker\Desktop\test.php
short path: C:\DOKUME~1\Volker\Desktop\test.php
``` | You may want to have a look at `escapeshellarg()` and put the parameter in between double quotes. | Can I get the short DOS name of a file from PHP? | [
"",
"php",
"dos",
""
] |
I'm trying to get the server URL of a currently running appengine java app from code. That is, if the app is running on my local dev machine I would like to somehow get returned "<http://localhost:8080>" but if it is running in prod I'd like to be returned "<http://myappid.appspot.com>". Are there any java or appengine API's that can do this? I'd like to not have a to manually change and read from a config file or a constant.
Thanks.
* Aleem | You should be able to use getServerName():
```
boolean local = "localhost".equals(httpServletRequest.getServerName());
```
There are other methods you can also use if you need more info, e.g. getServerPort(). | This is working for me in Java on appengine:
```
String hostUrl;
String environment = System.getProperty("com.google.appengine.runtime.environment");
if (StringUtils.equals("Production", environment)) {
String applicationId = System.getProperty("com.google.appengine.application.id");
String version = System.getProperty("com.google.appengine.application.version");
hostUrl = "http://"+version+"."+applicationId+".appspot.com/";
} else {
hostUrl = "http://localhost:8888";
}
``` | How to get the current server URL of appengine app? | [
"",
"java",
"google-app-engine",
""
] |
Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable?
At the moment I have users enter stuff in using raw\_input(), but I would like something a bit more powerful than that, and have it displayed on the CLI. | You could have a look at [urwid](http://excess.org/urwid/), a curses-based, full-fledged UI toolkit for python. It allows you to define very sophisticated interfaces and it includes different edit box types for different types of text. | Well, you can launch the user's $EDITOR with subprocess, editing a temporary file:
```
import tempfile
import subprocess
import os
t = tempfile.NamedTemporaryFile(delete=False)
try:
editor = os.environ['EDITOR']
except KeyError:
editor = 'nano'
subprocess.call([editor, t.name])
``` | Python module for editing text in CLI | [
"",
"python",
"text-editor",
"command-line-interface",
""
] |
```
List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");
List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");
```
Is there a method to create a third list that has `{"Blah", "Bleh", "Blih", "Ooga", "Booga", "Wooga"}` or, alternatively, change `list1` so it has the three additional elements in list2? | I guess this is the solution:
```
list1.AddRange(list2)
``` | With LINQ, you can do:
```
List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");
List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");
var finalList = list1.Concat( list2 ).ToList();
``` | How to splice two C# lists into one? Or maybe use a different collection type? | [
"",
"c#",
"generics",
"collections",
""
] |
I am running function Foo from somebody else's library in a single-threaded application currently. Most of the time, I make a call to Foo and it's really quick, some times, I make a call to Foo and it takes forever. I am not a patient man, if Foo is going to take forever, I want to stop execution of Foo and not call it with those arguments.
What is the best way to call Foo in a controlled manner (my current environment is POSIX/C++) such that I can stop execution after a certain number of seconds. I feel like the right thing to do here is to create a second thread to call Foo, while in my main thread I create a timer function that will eventually signal the second thread if it runs out of time.
Is there another, more apt model (and solution)? If not, would Boost's Signals2 library and Threads do the trick? | You can call Foo on a second thread with a timeout. For example:
```
#include <boost/date_time.hpp>
#include <boost/thread/thread.hpp>
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(500);
boost::thread thrd(&Foo);
if (thrd.timed_join(timeout))
{
//finished
}
else
{
//Not finished;
}
``` | You can use the following class:
```
class timer
{
typedef boost::signals2::signal<void ()> timeout_slot;
public:
typedef timeout_slot::slot_type timeout_slot_t;
public:
timer() : _interval(0), _is_active(false) {};
timer(int interval) : _interval(interval), _is_active(false) {};
virtual ~timer() { stop(); };
inline boost::signals2::connection connect(const timeout_slot_t& subscriber) { return _signalTimeout.connect(subscriber); };
void start()
{
boost::lock_guard<boost::mutex> lock(_guard);
if (is_active())
return; // Already executed.
if (_interval <= 0)
return;
_timer_thread.interrupt();
_timer_thread.join();
timer_worker job;
_timer_thread = boost::thread(job, this);
_is_active = true;
};
void stop()
{
boost::lock_guard<boost::mutex> lock(_guard);
if (!is_active())
return; // Already executed.
_timer_thread.interrupt();
_timer_thread.join();
_is_active = false;
};
inline bool is_active() const { return _is_active; };
inline int get_interval() const { return _interval; };
void set_interval(const int msec)
{
if (msec <= 0 || _interval == msec)
return;
boost::lock_guard<boost::mutex> lock(_guard);
// Keep timer activity status.
bool was_active = is_active();
if (was_active)
stop();
// Initialize timer with new interval.
_interval = msec;
if (was_active)
start();
};
protected:
friend struct timer_worker;
// The timer worker thread.
struct timer_worker
{
void operator()(timer* t)
{
boost::posix_time::milliseconds duration(t->get_interval());
try
{
while (1)
{
boost::this_thread::sleep<boost::posix_time::milliseconds>(duration);
{
boost::this_thread::disable_interruption di;
{
t->_signalTimeout();
}
}
}
}
catch (boost::thread_interrupted const& )
{
// Handle the thread interruption exception.
// This exception raises on boots::this_thread::interrupt.
}
};
};
protected:
int _interval;
bool _is_active;
boost::mutex _guard;
boost::thread _timer_thread;
// Signal slots
timeout_slot _signalTimeout;
};
```
An example of usage:
```
void _test_timer_handler()
{
std::cout << "_test_timer_handler\n";
}
BOOST_AUTO_TEST_CASE( test_timer )
{
emtorrus::timer timer;
BOOST_CHECK(!timer.is_active());
BOOST_CHECK(timer.get_interval() == 0);
timer.set_interval(1000);
timer.connect(_test_timer_handler);
timer.start();
BOOST_CHECK(timer.is_active());
std::cout << "timer test started\n";
boost::this_thread::sleep<boost::posix_time::milliseconds>(boost::posix_time::milliseconds(5500));
timer.stop();
BOOST_CHECK(!timer.is_active());
BOOST_CHECK(_test_timer_count == 5);
}
``` | Can I create a software watchdog timer thread in C++ using Boost Signals2 and Threads? | [
"",
"c++",
"boost-thread",
"boost-signals",
"watchdog",
""
] |
i search for a good solution for mapping data in c#.
At first i have a Character "a" and a angle "0.0" degree.
What is the best solution for the Mapping ? A list ?
One requirement is that i must search for the degree if it not in the "list" then i add a new one.. and so on
thanks for help :)
**EDIT: I must find out if the angle exists ! If the angle not exists then add a new char** | Dictionary< double,char>
Example:
```
Dictionary< double, char> dic = new Dictionary< double, char>();
//Adding a new item
void AddItem(char c, double angle)
{
if (!dic.ContainsKey(angle))
dic.Add(angle,c);
}
//Retreiving an item
char GetItem(double angle)
{
char c;
if (!dic.TryGetValue(angle, out c))
return '';
else
return c;
}
``` | Use dictionary.
```
var d =new Dictionary<string,double> ()`
``` | Mapping of some Data in c# | [
"",
"c#",
"list",
"mapping",
""
] |
I've been playing around with the [Xerces-C](http://xerces.apache.org/xerces-c/) XML library.
I have this simple example I'm playing with.
I can't seem to get it to run without leaking memory and without segfaulting.
It's one or the other.
The segfault always occurs when I delete the parser object under "Clean up".
I've tried using both the 2.8 & 2.7 versions of the library.
**Note:** I took all of the exception checking out of the code, I get the same results with it and without it. For readability and simplicity I removed it from the code below.
**Any Xerces-savvy people out there care to make some suggestions?**
I can't really tell much from the back trace, it's just jumping down into the superclass destructor and segfaulting there.
**Backtrace:**
```
(gdb) bt
#0 0x9618ae42 in __kill ()
#1 0x9618ae34 in kill$UNIX2003 ()
#2 0x961fd23a in raise ()
#3 0x96209679 in abort ()
#4 0x95c5c005 in __gnu_cxx::__verbose_terminate_handler ()
#5 0x95c5a10c in __gxx_personality_v0 ()
#6 0x95c5a14b in std::terminate ()
#7 0x95c5a6da in __cxa_pure_virtual ()
#8 0x003e923e in xercesc_2_8::AbstractDOMParser::cleanUp ()
#9 0x003ead2a in xercesc_2_8::AbstractDOMParser::~AbstractDOMParser ()
#10 0x0057022d in xercesc_2_8::XercesDOMParser::~XercesDOMParser ()
#11 0x000026c9 in main (argc=2, argv=0xbffff460) at test.C:77
```
**The code:**
```
#include <string>
#include <vector>
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
using namespace std;
XERCES_CPP_NAMESPACE_USE
int main(int argc, char const* argv[])
{
string skXmlMetadata = "<?xml version=\"1.0\"?>\n <xmlMetadata>b</xmlMetadata>";
XMLPlatformUtils::Initialize();
XercesDOMParser* xmlParser = NULL;
DOMWriter* xmlWriter = NULL;
ErrorHandler* errHandler = NULL;
const XMLByte* xmlBuf = NULL;
MemBufInputSource* memBufIS = NULL;
DOMNode* xmlDoc = NULL;
xmlParser = new XercesDOMParser();
xmlParser->setValidationScheme( XercesDOMParser::Val_Never );
xmlParser->setDoNamespaces( false );
xmlParser->setDoSchema( false );
xmlParser->setLoadExternalDTD( false );
errHandler = (ErrorHandler*) new HandlerBase();
xmlParser->setErrorHandler( errHandler );
// Create buffer for current xmlMetadata
xmlBuf = (const XMLByte*) skXmlMetadata.c_str();
const char* bufID = "XmlMetadata";
memBufIS = new MemBufInputSource( xmlBuf, skXmlMetadata.length(), bufID, false );
// Parse
xmlParser->resetErrors();
xmlParser->parse( *memBufIS );
xmlDoc = xmlParser->getDocument();
// Write created xml to input SkArray
XMLCh* metadata = NULL;
xmlWriter = DOMImplementation::getImplementation()->createDOMWriter();
xmlWriter->setFeature( XMLUni::fgDOMWRTFormatPrettyPrint, true );
metadata = xmlWriter->writeToString( *xmlDoc );
xmlWriter->release();
// Print out our parsed document
char* xmlMetadata = XMLString::transcode( metadata );
string c = xmlMetadata;
cout << c << endl;
// Clean up
XMLString::release( &xmlMetadata );
xmlDoc->release();
delete xmlParser; // Dies here
delete memBufIS;
delete errHandler;
XMLPlatformUtils::Terminate();
return 0;
}
``` | " xmlDoc->release(); " is the culprit. You dont own that Node unless you say " xmlParser->adoptDocument() "
<http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#fe052561c37d70b62ac57ab6706d75aa> | Lets explore the evidence...
```
#6 0x95c5a14b in std::terminate ()
```
I can tell you this is called when a destructor throws an exception. Destructors throwing exceptions is a big no-no. Xerces may be doing something wonky.
Or it might be caused by this line
```
#7 0x95c5a6da in __cxa_pure_virtual ()
```
where something might be missing in a virtual function table. Perhaps one of the DOM object's members destructor? Perhaps this generates an exception?
[This link](http://www.artima.com/cppsource/pure_virtual.html) offers a great explanation on what might cause the virtual table lookups to fail. In short, it can be caused by a dangling base-class pointer hanging around someone trying to make a polymorphic function call on that pointer.
Example given from the link above:
```
// From sample program 5:
AbstractShape* p1 = new Rectangle(width, height, valuePerSquareUnit);
std::cout << "value = " << p1->value() << std::endl;
AbstractShape* p2 = p1; // Need another copy of the pointer.
delete p1;
std::cout << "now value = " << p2->value() << std::endl;
```
Speaking of dangling pointers, it looks like the XercesDomParser is holding objects you newed:
```
errHandler = (ErrorHandler*) new HandlerBase();
xmlParser->setErrorHandler( errHandler )
```
but later deleted/released
```
// Clean up
XMLString::release( &xmlMetadata );
xmlDoc->release();
delete xmlParser;
delete memBufIS;
delete errHandler;
```
Could the order you are destroying things be incorrect and cause some of the above problems? On the face of it, things look OK, but that's where I would experiment and double check the documentation on how things are supposed to be torn down. | Xerces-C problems; segfault on call to object destructor | [
"",
"c++",
"xml",
"segmentation-fault",
"xerces-c",
""
] |
In Eclipse is there a provision to copy multiple items and then paste the items selectively from the clip board? IntelliJ has this feature and I used to find it very useful. Does Eclipse have this and if so what is the key board short cut to view items in the clip board? | There is a [multi-clipboard plugin](http://www.eclipse-plugins.info/eclipse/plugin_details.jsp?id=930) to do just that. | You may check [More Clipboard](http://marketplace.eclipse.org/content/more-clipboard#.UdULNz6GXQo) plugin. It's less complicated than Multi Clipboard and just works. | Eclipse and clip board | [
"",
"java",
"eclipse",
"intellij-idea",
""
] |
I tried using the `ssl` module in Python 2.6 but I was told that it wasn't available. After installing OpenSSL, I recompiled 2.6 but the problem persists.
Any suggestions? | Did you install the OpenSSL development libraries? I had to install `openssl-devel` on CentOS, for example. On Ubuntu, `sudo apt-get build-dep python2.5` did the trick (even for Python 2.6). | Use the binaries provided by python.org or by your OS distributor. It's a lot easier than building it yourself, and all the features are usually compiled in.
If you really need to build it yourself, you'll need to provide more information here about what build options you provided, what your environment is like, and perhaps provide some logs. | Adding SSL support to Python 2.6 | [
"",
"python",
"ssl",
"openssl",
""
] |
I am relatively new to MYSQL and have had an issue that has been bugging me for a while. I've tried googling all over the place for the answer, but have unable to find an acceptable solution as of yet.
Here is the query I am running currently to find the best possible match for a given search term:
```
$query="SELECT * from `vocabulary` WHERE translation = 'word' OR translation LIKE '%word%'";
```
The results it returns are comprehensive in that they include all relevant rows. However, they are not sorted in any particular order, and I would like to have the ones with an exact match displayed first when I print results in PHP. Like this:
---
1 | word <-exact match
2 | crossword <- partial matches sorted alphabetically /
3 | words
4 | wordsmith
---
Thank you very much in advance for your assistance.
-macspacejunkie | ```
SELECT * from vocabulary
WHERE translation like 'word'
union all
SELECT * from vocabulary
WHERE translation LIKE '%word%' and translation not like 'word'
```
will list exact matches first | LIKE is not [fulltext search](http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html). In Fulltext search, `MATCH(...) AGAINST(...)` returns a matching score that can be roughly approximated as relevancy. | How to sort MYSQL fulltext search results by relevancy | [
"",
"php",
"mysql",
"sorting",
"full-text-search",
""
] |
Is there any way I can rename the window titlebar of an application that I've launched? I.e. if I launched Notepad.exe, I could rename its title bar from "Untitled - Notepad" to "New Notepad Name". | You can do it using P/Invoke:
```
[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);
private void StartMyNotepad()
{
Process p = Process.Start("notepad.exe");
Thread.Sleep(100); // <-- ugly hack
SetWindowText(p.MainWindowHandle, "My Notepad");
}
```
The background of the ugly hack in the code sample is that it seems as if you call SetWindowText immediately after starting the process, the title will not change. Perhaps the message ends up too early in the message queue of Notepad, so that notepad will set the title again afterwards.
Also note that this is a very brief change; if the user selects File -> New (or does anything else that will cause Notepad to update the window title), the original title will be back... | Actually, I sorted it myself and it works perfectly. Thanks anyway.
```
[DllImport("user32.dll")]
static extern SetWindowText(IntPtr hWnd, string windowName);
IntPtr handle = p.MainWindowHandle;
SetWindowText(handle, "This is my new title");
``` | C# - How can I rename a process window that I started? | [
"",
"c#",
"process",
"window",
"titlebar",
""
] |
I don't know the official terms for what this is called, but would greatly appreciate any advice.
The scenario is as follows: I have an index.html page on my domain to serve as a 'Under Construction' page, while I develop the website behind that using Drupal on an index.php page.
Is there any way in which I can have Google index the links on index.php so long while I develop it or is this a stupid way of doing things?
Thanks in advance. | This could be against Google's standards and could result in your site being removed from Google's listings - providing one type of content to users, and another to Google's Spider.
It could be done using .htaccess re-writes though | I would be very hesitant to serve up different pages to Google than to a regular visitor. While details are sketchy due to Google's secrecy, your site may be penalised in Google's search engine.
Besides, if the pages those links go to don't have useful content on them yet, you are unlikely to get much benefit from any of the major search engines. And if you did have the content already, you may as well just put it online (soft launch). | Search engine redirecting | [
"",
"php",
"html",
"search",
"search-engine",
""
] |
> **Possible Duplicate:**
> [How to format a JSON date?](https://stackoverflow.com/questions/206384/how-to-format-a-json-date)
My webs service is returning a DateTime to a jQuery call. The service returns the data in this format:
```
/Date(1245398693390)/
```
How can I convert this into a JavaScript-friendly date? | What is returned is milliseconds since epoch. You could do:
```
var d = new Date();
d.setTime(1245398693390);
document.write(d);
```
On how to format the date exactly as you want, see full `Date` reference at <http://www.w3schools.com/jsref/jsref_obj_date.asp>
You could strip the non-digits by either parsing the integer ([as suggested here](https://stackoverflow.com/a/2316066/88001)):
```
var date = new Date(parseInt(jsonDate.substr(6)));
```
Or applying the following regular expression (from Tominator in the comments):
```
var jsonDate = jqueryCall(); // returns "/Date(1245398693390)/";
var re = /-?\d+/;
var m = re.exec(jsonDate);
var d = new Date(parseInt(m[0]));
``` | I have been using this method for a while:
```
using System;
public static class ExtensionMethods {
// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
}
```
Assuming you are developing against .NET 3.5, it's a straight copy/paste. You can otherwise port it.
You can encapsulate this in a JSON object, or simply write it to the response stream.
On the Javascript/JSON side, you convert this to a date by simply passing the ticks into a new Date object:
```
jQuery.ajax({
...
success: function(msg) {
var d = new Date(msg);
}
}
``` | Converting .NET DateTime to JSON | [
"",
"javascript",
"json",
"datetime",
""
] |
How can I truncate a VARCHAR to the table field length AUTOMATICALLY in Derby using SQL?
To be specific:
```
CREATE TABLE A ( B VARCHAR(2) );
INSERT INTO A B VALUES ('1234');
```
would throw a SQLException:
```
A truncation error was encountered trying to shrink VARCHAR '123' to length 2.
```
Is there a easy way to suppress this exception? | No. You should chop it off after checking the meta-data. Or if you don't wanna check the meta-data everytime, then you must keep both your code and database in sync. But thats not a big deal, its a usual practice in validators. | You can trim the varchar before inserting it.
use the trim function in your insert script/procedure.
I'm not familiar with Derby, but in MSSQL I do exactly the same thing, using trim to avoid truncation error (only where I don't need the full data), it's much more preferable to increase the length of the varchar | Truncate a VARCHAR to specific length in Derby AUTOMATICALLY | [
"",
"java",
"string",
"varchar",
"derby",
"javadb",
""
] |
Could someone give me an example of the best way to add an iterator to a custom class pre Java 5's iterable interface?
Would wrapping a Collection be the best option? Something like
```
public Iterator iterator() {
return wrappedCollection.iterator();
}
```
In my initial post I confused Iterator with Iterable. The end result I am interested in is being able to operate on the custom class with the following.
```
Iterator it = customClass.iterator();
while (it.hasNext()) {
//do stuff
}
``` | If you're just wrapping a collection you can use a forwarding method.
```
public class Custom implements Collection {
Collection c; // create an instance here or in the constructor
...
// forwarding method
public Iterator iterator()
{
return c.iterator();
}
}
```
I think it would be better to implement whatever type of Collection Interface you're wrapping, though, instead of Iterator. | Did you add a method that looks like
```
public Iterator iterator() {
return new YourCustomIterator(...);
}
```
? | Examples of how to add an iterator to a custom class in Java 1.4? | [
"",
"java",
"iterator",
"java1.4",
""
] |
I want to have a dynamic `where` condition.
In the following example:
```
var opportunites = from opp in oppDC.Opportunities
join org in oppDC.Organizations
on opp.OrganizationID equals org.OrgnizationID
where opp.Title.StartsWith(title)
select new
{
opp.OpportunityID,
opp.Title,
opp.PostedBy,
opp.Address1,
opp.CreatedDate,
org.OrganizationName
};
```
Some times I have `Title` and sometimes I don't. And also I want to add date in `where` clause dynamically.
For example, like this SQL:
```
string whereClause;
string SQL = whereClause == string.Empty ?
"Select * from someTable" : "Select * from someTable" + whereclause
``` | You can rewrite it like this:
```
var opportunites = from opp in oppDC.Opportunities
join org in oppDC.Organizations on opp.OrganizationID equals org.OrgnizationID
select new
{
opp.OpportunityID,
opp.Title,
opp.PostedBy,
opp.Address1,
opp.CreatedDate,
org.OrganizationName
};
if(condition)
{
opportunites = opportunites.Where(opp => opp.Title.StartsWith(title));
}
```
**EDIT:** To answer your question in the comments, yes, you can keep appending to the original Queryable. Remember, this is all lazily executed, so at this point all it's doing it building up the IQueryable so you can keep chaining them together as needed:
```
if(!String.IsNullOrEmpty(title))
{
opportunites = opportunites.Where(.....);
}
if(!String.IsNullOrEmpty(name))
{
opportunites = opportunites.Where(.....);
}
``` | You can dynamically add a where clause to your IQueryable expression like this:
```
var finalQuery = opportunities.Where( x => x.Title == title );
```
and for the date similarly.
However, you will have to wait to create your anonymous type until after you've finished dynamically added your where clauses ***if*** your anonymous type doesn't contain the fields you want to query for in your where clause.
So you might have something that looks like this:
```
var opportunities = from opp in oppDC.Opportunities
join org in oppDC.Organizations on
opp.OrganizationID equals org.OrgnizationID
select opp
if(!String.IsNullOrEmpty(title))
{
opportunities = opportunities.Where(opp => opp.Title == title);
}
//do the same thing for the date
opportunities = from opp in opportunities
select new
{
opp.OpportunityID,
opp.Title,
opp.PostedBy,
opp.Address1,
opp.CreatedDate,
org.OrganizationName
};
``` | How do I implement a dynamic 'where' clause in LINQ? | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I have a really long string in a certain pattern such as:
```
userAccountName: abc userCompany: xyz userEmail: a@xyz.com userAddress1: userAddress2: userAddress3: userTown: ...
```
and so on. This pattern repeats.
I need to find a way to process this string so that I have the values of `userAccountName:`, `userCompany:`, etc. (i.e. preferably in an associative array or some such convenient format).
Is there an easy way to do this or will I have to write my own logic to split this string up into different parts? | I think the solution closest to what I was looking for, I found at <http://www.justin-cook.com/wp/2006/03/31/php-parse-a-string-between-two-strings/>. I hope this proves useful to someone else. Thanks everyone for all the suggested solutions. | Simple regular expressions like this `userAccountName:\s*(\w+)\s+` can be used to capture matches and then use the captured matches to create a data structure. | Parse multiple predictably formatted substrings of user data existing in a single string | [
"",
"php",
"regex",
"string",
"text-parsing",
""
] |
Is there a generic approach to "compressing" nested objects to a single level:
```
var myObj = {
a: "hello",
b: {
c: "world"
}
}
compress(myObj) == {
a: "hello",
b_c: "world"
}
```
I guess there would be some recursion involved, but I figured I don't need to reinvent the wheel here... !? | ```
function flatten(obj, includePrototype, into, prefix) {
into = into || {};
prefix = prefix || "";
for (var k in obj) {
if (includePrototype || obj.hasOwnProperty(k)) {
var prop = obj[k];
if (prop && typeof prop === "object" &&
!(prop instanceof Date || prop instanceof RegExp)) {
flatten(prop, includePrototype, into, prefix + k + "_");
}
else {
into[prefix + k] = prop;
}
}
}
return into;
}
```
You can include members inherited members by passing `true` into the second parameter.
A few caveats:
* recursive objects will not work. For example:
```
var o = { a: "foo" };
o.b = o;
flatten(o);
```
will recurse until it throws an exception.
* Like ruquay's answer, this pulls out array elements just like normal object properties. If you want to keep arrays intact, add "`|| prop instanceof Array`" to the exceptions.
* If you call this on objects from a different window or frame, dates and regular expressions will not be included, since `instanceof` will not work properly. You can fix that by replacing it with the default toString method like this:
```
Object.prototype.toString.call(prop) === "[object Date]"
Object.prototype.toString.call(prop) === "[object RegExp]"
Object.prototype.toString.call(prop) === "[object Array]"
``` | Here's a quick one, but watch out, b/c it will *not* work w/ arrays and null values (b/c their typeof returns "object").
```
var flatten = function(obj, prefix) {
if(typeof prefix === "undefined") {
prefix = "";
}
var copy = {};
for (var p in obj) {
if(obj.hasOwnProperty(p)) {
if(typeof obj[p] === "object") {
var tmp = flatten(obj[p], p + "_");
for(var q in tmp) {
if(tmp.hasOwnProperty(q)) {
copy[prefix + q] = tmp[q];
}
}
}
else {
copy[prefix + p] = obj[p];
}
}
}
return copy;
}
var myObj = {
a: "level 1",
b: {
a: "level 2",
b: {
a: "level 3",
b: "level 3"
}
}
}
var flattened = flatten(myObj);
``` | compressing object hierarchies in JavaScript | [
"",
"javascript",
"json",
"coffeescript",
""
] |
* I've edited original text to save potential readers some time and health. Maybe someone will actually use this.
I know it's basic stuff. Probably like very, very basic.
How to get all possible combinations of given set.
E.g.
string set = "abc";
I expect to get:
a b c aa ab ac aaa aab aac aba abb abc aca acb acc baa bab ...
and the list goes on (if no limit for length is set).
I'm looking for a very clean code for that - all that I've found was kind of dirty and not working correctly. The same I can say about code I wrote.
I need such code because I'm writing brute force (md5) implementation working on multiple threads. The pattern is that there's Parent process that feeds threads with chunks of their very own combinations, so they would work on these on their own.
Example: first thread gets package of 100 permutations, second gets next 100 etc.
Let me know if I should post the final program anywhere.
EDIT #2
Once again thank you guys.
Thanks to you I've finished my Slave/Master Brute-Force application implemented with MPICH2 (yep, can work under linux and windows across for example network) and since the day is almost over here, and I've already wasted a lot of time (and sun) I'll proceed with my next task ... :)
You shown me that StackOverflow community is awesome - thanks! | Here's some C++ code that generates permutations of a power set up to a given length.
The function `getPowPerms` takes a set of characters (as a vector of strings) and a maximum length, and returns a vector of permuted strings:
```
#include <iostream>
using std::cout;
#include <string>
using std::string;
#include <vector>
using std::vector;
vector<string> getPowPerms( const vector<string>& set, unsigned length ) {
if( length == 0 ) return vector<string>();
if( length == 1 ) return set;
vector<string> substrs = getPowPerms(set,length-1);
vector<string> result = substrs;
for( unsigned i = 0; i < substrs.size(); ++i ) {
for( unsigned j = 0; j < set.size(); ++j ) {
result.push_back( set[j] + substrs[i] );
}
}
return result;
}
int main() {
const int MAX_SIZE = 3;
string str = "abc";
vector<string> set; // use vector for ease-of-access
for( unsigned i = 0; i < str.size(); ++i ) set.push_back( str.substr(i,1) );
vector<string> perms = getPowPerms( set, MAX_SIZE );
for( unsigned i = 0; i < perms.size(); ++i ) cout << perms[i] << '\n';
}
```
When run, this example prints
```
a b c aa ba ca ab bb cb ... acc bcc ccc
```
**Update:** I'm not sure if this is useful, but here is a "generator" function called `next` that creates the next item in the list given the current item.
Perhaps you could generate the first *N* items and send them somewhere, then generate the next *N* items and send them somewhere else.
```
string next( const string& cur, const string& set ) {
string result = cur;
bool carry = true;
int loc = cur.size() - 1;
char last = *set.rbegin(), first = *set.begin();
while( loc >= 0 && carry ) {
if( result[loc] != last ) { // increment
int found = set.find(result[loc]);
if( found != string::npos && found < set.size()-1 ) {
result[loc] = set.at(found+1);
}
carry = false;
} else { // reset and carry
result[loc] = first;
}
--loc;
}
if( carry ) { // overflow
result.insert( result.begin(), first );
}
return result;
}
int main() {
string set = "abc";
string cur = "a";
for( int i = 0; i < 20; ++i ) {
cout << cur << '\n'; // displays a b c aa ab ac ba bb bc ...
cur = next( cur, set );
}
}
``` | C++ has a function next\_permutation(), but I don't think that's what you want.
You should be able to do it quite easily with a recursive function. e.g.
```
void combinations(string s, int len, string prefix) {
if (len<1) {
cout << prefix << endl;
} else {
for (int i=0;i<s.size();i++) {
combinations(s, len-1, prefix + s[i])
}
}
}
```
EDIT: For the threading part, I assume you are working on a password brute forcer?
If so, I guess the password testing part is what you want to speed up rather than password generation.
Therefore, you could simply create a parent process which generates all combinations, then every *k*th password is given to thread *k mod N* (where *N* is the number of threads) for checking. | How to get count of next combinations for given set? | [
"",
"c++",
"string",
"combinatorics",
""
] |
Could someone explain condition synchronization to me?
An example (preferably in C#) would be greatly appreciated also. | It sounds like your professor is talking about threading. Threading enables computer programs to do more than one thing at a time. The act of starting a new thread while one is already running is called "spinning up a thread" by computer programmers.
Threads can share the same memory space. Condition Synchronization (or merely synchronization) is any mechanism that protects areas of memory from being modified by two different threads at the same time.
Let's say you are out doing shopping, and the wife is at home paying the bills. This is a naive example, and it doesn't really work this way in real life, but it will serve as a simple illustration.
Your wife is paying a bill online. At the same time, you are swiping your credit card at the grocery store. Both acts involve moving money out of your checking account. To simulate this activity, we write the following code:
```
public class MyBanking
{
static double myAccountBalance;
//
public void DebitAccount(double debitAmount)
{
Console.Writeline("Your Old Balance is: " + myAccountBalance.ToString());
Console.Writeline("Your Debit is: " + debitAmount.ToString());
myAccountBalance = myAccountBalance - amount;
Console.Writeline("Your New Balance is: " + myAccountBalance.ToString());
}
}
```
Hypothetically, your wife is running one instance ("copy") of this class on one thread, you are running an instance on another thread. The myAccountBalance variable is declared static to allow it to be shared between both running instances (you and your wife have only one checking account).
You make your debit by calling the code like this:
```
MyBanking bankingObject = new MyBanking();
bankingObject.DebitAccount(100);
```
Your wife makes her debit at the same time:
```
MyBanking bankingObject = new MyBanking();
bankingObject.DebitAccount(50);
```
What happens if your thread gets interrupted by your wife's thread after your old balance is printed on the screen, but before the new balance is printed? Your wife's thread debits the account and returns control back to your thread. Your wife sees this on the screen:
```
Your Old Balance is: 2000
Your Debit is: 50
Your New Balance Is: 1950
```
When the computer prints the new balance on your screen, it will be wrong, because your wife's debit will have been counted also. You will see something like this:
```
Your Old Balance is: 2000
Your Debit is: 100
Your New Balance Is: 1850
```
To fix this, we surround our method code with a lock statement. The lock statement **causes all other threads to wait for our instance to finish.** The new code looks like this:
```
public class MyBanking
{
static double myAccountBalance;
//
public void DebitAccount(double debitAmount)
{
lock (this)
{
Console.Writeline("Your Old Balance is: " + myAccountBalance.ToString());
Console.Writeline("Your Debit is: " + debitAmount.ToString());
myAccountBalance = myAccountBalance - amount;
Console.Writeline("Your New Balance is: " + myAccountBalance.ToString());
}
}
}
```
Your wife's thread will now wait for your code within the lock statement to finish executing, before your wife's code begins executing. Your new balance will now be correct, because there is no longer the possibility of your wife's thread changing the balance while you complete YOUR transaction. On your screen, you will now see this:
```
Your Old Balance is: 2000
Your Debit is: 100
Your New Balance Is: 1900
```
Your wife will see this:
```
Your Old Balance is: 1900
Your Debit is: 50
Your New Balance Is: 1850
```
This is synchronization. | Basically it's a design pattern for threads that need
a) synchronize access to a resource
b) sometimes wait for other threads until a certain conditions is met
You ask this in a C# context, .NET provides support for this with Monitor.Wait and Monitor.Pulse (and with wrappers around various Win32 objects like WaitEventhandle).
Here is a nice [queue example](https://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net) on SO.
The main technical details look like:
```
lock(buffer) // is Monitor.Enter(buffer) ... finally Monitor.Leave(buffer)
{
while (buffer.Count < 1)
{
Monitor.Wait(buffer);
}
...
}
```
Notice how there is a Wait-while-locked in there. It looks like a deadlock but Wait will release the lock while it is waiting. The code inside the `lock() { }` still has exclusive access to buffer when it runs.
And then another thread has to signal when it puts something into the buffer:
```
Monitor.Pulse(buffer);
``` | What is condition synchronization? | [
"",
"c#",
"synchronization",
"conditional-statements",
""
] |
I've been using Kohana for a couple months now, and am still relatively new to the MVC style of organizing your code/presentation/db-layer. Unfortunately, while there is plenty of documentation on how to create a controller, establish a view, and interact with a db via a model, I've not found many resources that deal with clean, and suggested development patterns.
Let me give a quick example:
My latest project has one controller, because I'm not sure if I should be making many more than that...or when I should make a new one. How exactly do I determine when a new controller is needed, along with when a new model is needed? | I'd suggest you to have a look at the [resource oriented architecture](http://en.wikipedia.org/wiki/Resource_oriented_architecture), first. This won't give you any direct guidelines of how to organize your code. However, when thinking in terms of resources life is more easy when it comes to deciding whether or not to create a new controller. Once you manage to identify a resource in your system, it's usually a good thing to create a model plus a controller for it - although, this is just a rule of thumb.
Some additional points:
* look for resources and create a model and a controller for each of them (rule of thumb)
* don't be afraid to create models for resources that don't persist
* think about controllers as "plumbing" or "wiring" of user to the business domain - their role is to handle user requests and forward the answer back to them - keep them as thin as possible | The rule thumb is as follows: when I identify a new kind of "item" that my app. needs to manage, I ask my self these questions:
(1) Should items of these kind be persistent?
(2) Are there going to be many instances of this item?
If the answer to both questions is positive I conclude that the said item should be a model (or model-element or domain-class, depending on the terminology of your MVC framework). When I define a new model element I also define a controller for it that will support the four basic operations: create, retrieve, update, delete (it likely that your framework can generate a default controller for you). | Proper Design of a MVC Project | [
"",
"php",
"design-patterns",
"model-view-controller",
"kohana",
""
] |
I have a class A maintaining a list of objects class B.
But each object of class B can be referenced in any object of class A.
Class B also maintains a list of objects of class A where it is being referenced.
The program can and will create (several) objects of both class A and B 'at will' and also delete them.
If I use C# I can add and delete objects from both classes with following code
```
public class A
{
private List<B>ListOfObjects_B;
public bool Add(B Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_B.IndexOf(B) <0))
{
ListOfObjects_B.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(B Object)
{
bool bDeleted = ListOfObjects_B.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
public class B
{
private List<A>ListOfObjects_A;
public bool Add(A Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_A.IndexOf(A) <0))
{
ListOfObjects_A.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(A Object)
{
bool bDeleted = ListOfObjects_A.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
```
This will work as because of removing/adding the object to the ListOfObjects the SECOND time (by recursion) the function will be called it will fail to delete/add thereby avoiding an infinite loop.
But I don't like this code even though A and B do not know 'much' about the other class and just call a Delete/Add function.
I suppose this kind of problem is general and a design pattern exists for handling it in such a way that recursion can be avoided and updating both lists will be 'just better'.
What design pattern should I use? I would appreciate if some code would be added as well. | You can simplify thing by moving the "object association concern" into a dedicated class. Here's what I have in mind.
Define a class called AssociationTable. This class will maintain a list of pairs where each pair holds a reference to an A object and a reference to a B object.
Each A object (and each B object) will hold a reference to the AssociationTable object.
A.Add(B) will be implemented as table.add(this, b);
B.Add(A) will be implemented as table.add(a, this);
Deletion will be implemented as table.delete(this, b) or table.delete(a, this)
```
class Pair {
A a; B b;
Pair(A a, B b) { this.a = a; this.b = b; }
// Also override Equals(), HashCode()
}
class AssociationTalbe {
Set<Pair> pairs = ...;
void add(A a, B b) { pairs.add(new Pair(a, b)); }
void remove(A a, B b) { pairs.remove(new Pair(a, b)); }
}
class A {
AssociationTable table;
public A(AssociationTable t) { table = t; }
void add(B b) { table.add(this, b); }
void remove(B b) { table.remove(this, b); }
}
```
Edit:
The problem with this design is garbage collection. the table will hold references to objects thereby supressing their collection. In Java you could use a WeakReference object to overcome this issue. I am pretty sure there's something similar in the .Net world
Also, the table could be a singleton. I don't like singletons too much. In here, a singleton will make the A-B association unique across your program. This may be something that is undesirable but it depends on your concrete needs.
Finally, (just to put things in context) this design works the same way as Many-to-Many relationships in relational data bases. | I recently wrote [a class to handle a similar problem](http://www.thomaslevesque.com/2009/06/12/c-parentchild-relationship-and-xml-serialization/). It is actually a simpler scenario (parent/child relationship with the children referencing their parent), but you could probably adapt it for your needs. The main difference is that the `Parent` property in my implementation should be replaced by a collection of parents. | What design pattern? | [
"",
"c#",
"design-patterns",
""
] |
My dictionary:
```
Dictionary<double, string> dic = new Dictionary<double, string>();
```
How can I return the last element in my dictionary? | What do you mean by Last? Do you mean Last value added?
The `Dictionary<TKey,TValue>` class is an unordered collection. Adding and removing items can change what is considered to be the first and last element. Hence there is no way to get the Last element added.
There is an ordered dictionary class available in the form of `SortedDictionary<TKey,TValue>`. But this will be ordered based on comparison of the keys and not the order in which values were added.
**EDIT**
Several people have mentioned using the following LINQ style approach
```
var last = dictionary.Values.Last();
```
Be very wary about using this method. It will return the last value in the Values collection. This may or may not be the last value you added to the Dictionary. It's probably as likely to not be as it is to be. | Dictionaries are unordered collections - as such, there is no concept of a first or last element. If you are looking for a class that behaves like a dictionary but maintains the insertion order of items, consider using [`OrderedDictionary`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx).
If you are looking for a collection that sorts the items, consider using [`SortedDictionary<TKey,TValue>`](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx).
If you have an existing dictionary, and you are looking for the 'last' element given some sort order, you could use linq to sort the collection, something like:
```
myDictionary.Values.OrderBy( x => x.Key ).Last();
```
By wary of using `Dictionary.Keys.Last()` - while the key list is sorted using the default `IComparer` for the type of the key, the value you get may not be the value you expect. | Get the last element in a dictionary? | [
"",
"c#",
".net",
"dictionary",
""
] |
I'm using DbLinq which should be the equivalent of Linq2SQL for this question. I'm need to generate a Linq2SQL query where I specify the columns I want returned at runtime. I can achieve that using the Dynamic Linq extension methods but I can't work out how to extract the result.
```
string someProperty = "phonenumber";
string id = "1234";
Table<MyClass> table = context.GetTable<MyClass>();
var queryResult = (from item in table where item.Id == id select item).Select("new (" + someProperty + ")");
```
The Linq expression generates the proper SQL of:
```
select phonenumber from mytable where id = '1234'
```
And in the debugger I can see the phonenumber value is sitting there in the Results View. The problem is I can't work out how to get the phonenumber value from the queryResult object? The type of queryResult is:
```
QueryProvider<DynamicClass1>
```
Edit:
I discovered a way to do it but it seems very crude.
```
IEnumerator result = (from item in table where item.Id == id select item).Select("new (" + someProperty + ")").GetEnumerator();
result.MoveNext();
var resultObj = result.Current;
PropertyInfo resultProperty = resultObj.GetType().GetProperty(someProperty);
Console.WriteLine(resultProperty.GetValue(resultObj, null));
```
Perhaps someone knows a cleaner way? | The solution was:
```
string someProperty = "phonenumber";
PropertyInfo property = typeof(T).GetProperty(propertyName);
string id = "1234";
Table<MyClass> table = context.GetTable<MyClass>();
Expression<Func<T, Object>> mySelect = DynamicExpression.ParseLambda<T, Object>(property.Name);
var query = (from asset in table where asset.Id == id select asset).Select(mySelect);
return query.FirstOrDefault();
``` | Linq uses deferred execution method to get data. [Deferred execution](http://msdn.microsoft.com/en-us/library/bb943859.aspx) means that the evaluation of an expression is delayed until its realized value is actually required.
In your case queryResult is a IEnumerable object, which means no data has actually been evaluated yet. You can evaluate queryResult object by calling result.ToList() or result.ToDictionary(), or any other methods that will return an object with non-IEnumerable data types.
Hope this is helpful. | Access Linq result contained in a dynamic class | [
"",
"c#",
"linq",
"linq-to-sql",
"dynamic-linq",
""
] |
I have met an interesting problem while implementing the Observer pattern with C++ and STL. Consider this classic example:
```
class Observer {
public:
virtual void notify() = 0;
};
class Subject {
public:
void addObserver( Observer* );
void remObserver( Observer* );
private:
void notifyAll();
};
void Subject::notifyAll() {
for (all registered observers) { observer->notify(); }
}
```
This example can be found in every book on design patterns. Unfortunately, real-life systems are more complex, so here is the first problem: some observers decide to add other observers to the Subject on being notified. This invalidates the "for" loop and all the iterators, that I use. The solution is rather easy - I make a snapshot of the registered observers list and iterate over the snapshot. Adding new observers does not invalidate the snapshot, so everything seems ok. But here comes another problem: observers decide to destroy themselves on being notified. Even worse, one single observer can decide to destroy all other observers (they are controlled from the scripts), and that invalidates both the queue and a snapshot. I find myself iterating over de-allocated pointers.
My question is how should I handle the situations, when observers kill each other? Are there any ready-to-use patterns? I always thought that "Observer" is the easiest design pattern in the world, but now it seems it is not that easy to implement it correctly...
**Thank you, everyone for your interest. Let us have a decisions summary:**
**[1] "Don't do it"** Sorry, but it is a must. Observers are controlled from the scripts and are garbage-collected. I cannot control the garbage collection to prevent their de-allocation;
**[2] "Use boost::signal"** The most promising decision, but I cannot introduce boost on the project, such decisions must be made by the project leader only (we are writing under Playstation);
**[3] "Use shared\_\_ptr"** That will prevent observers from de-allocation. Some sub-systems may rely on memory pool cleanup, so I don't think I can use shared\_ptr.
**[4] "Postpone observer deallocation"** Queue observers for removal while notifying, then use the second cycle to delete them. Unfortunately, I cannot prevent the deallocation, so I use a trick of wrapping observer with some kind of "adaptor", keeping actually the list of "adaptors". On destructor, observers unassign from their adaptors, then I take my second cycle to destroy empty adaptors.
p.s. is it ok, that I edit my question to summarize all the post? I am noob on StackOverflow... | Very interesting issue.
Try this:
1. Change remObserver to null out the entry, rather than just removing it (and invalidating the list iterators).
2. Change your notifyAll loop to be:
for (all registered observers) { if (observer) observer->notify(); }
3. Add another loop at the end of notifyAll to remove all null entries from your observer list | Personally, I use [boost::signals](http://www.boost.org/doc/libs/1_39_0/doc/html/signals.html) to implement my observers; I'll have to check, but I believe it handles the above scenarios (**edited**: found it, see ["When can disconnections occur"](http://www.boost.org/doc/libs/1_39_0/doc/html/signals/tutorial.html)). It simplifies your implementation, and it doesn't rely on creating custom class:
```
class Subject {
public:
boost::signals::connection addObserver( const boost::function<void ()>& func )
{ return sig.connect(func); }
private:
boost::signal<void ()> sig;
void notifyAll() { sig(); }
};
void some_func() { /* impl */ }
int main() {
Subject foo;
boost::signals::connection c = foo.addObserver(boost::bind(&some_func));
c.disconnect(); // remove yourself.
}
``` | Problems implementing the "Observer" pattern | [
"",
"c++",
"design-patterns",
"observer-pattern",
""
] |
I've got a large (read: nightmare) method which has grown over the years to support my project's ever growing list of commandline arguments. I mean several pages of readme docs for brief blurbs per argument.
As I've added each feature, I've simply "registered" a way of handling that argument by adding a few lines to that method.
However, that method is now unsightly, bug prone, and difficult to understand. Here's an example of the shorter of the two methods currently handling this:
```
//All double dash arguments modify global options of the program,
//such as --all --debug --timeout etc.
void consoleParser::wordArgParse(std::vector<criterion *> *results)
{
TCHAR const *compareCurWordArg = curToken.c_str()+2;
if (!_tcsicmp(compareCurWordArg,_T("all")))
{
globalOptions::showall = TRUE;
} else if (!_tcsnicmp(compareCurWordArg,_T("custom"),6))
{
if (curToken[9] == L':')
{
globalOptions::display = curToken.substr(10,curToken.length()-11);
} else
{
globalOptions::display = curToken.substr(9,curToken.length()-10);
}
} else if (*compareCurWordArg == L'c' || *compareCurWordArg == L'C')
{
if (curToken[3] == L':')
{
globalOptions::display = curToken.substr(5,curToken.length()-6);
} else
{
globalOptions::display = curToken.substr(4,curToken.length()-5);
}
} else if (!_tcsicmp(compareCurWordArg,_T("debug")))
{
globalOptions::debug = TRUE;
} else if (!_tcsicmp(compareCurWordArg,L"expand"))
{
globalOptions::expandRegex = false;
} else if (!_tcsicmp(compareCurWordArg,L"fileLook"))
{
globalOptions::display = L"---- #f ----#nCompany: #d#nFile Description: #e#nFile Version: #g"
L"#nProduct Name: #i#nCopyright: #j#nOriginal file name: #k#nFile Size: #u#nCreated Time: #c"
L"#nModified Time: #m#nAccessed Time: #a#nMD5: #5#nSHA1: #1";
} else if (!_tcsicmp(compareCurWordArg,_T("peinfo")))
{
globalOptions::display = _T("[#p] #f");
} else if (!_tcsicmp(compareCurWordArg,L"enable-filesystem-redirector-64"))
{
globalOptions::disable64Redirector = false;
} else if (!_tcsnicmp(compareCurWordArg,_T("encoding"),8))
{
//Performance enhancement -- encoding compare only done once.
compareCurWordArg += 8;
if (!_tcsicmp(compareCurWordArg,_T("acp")))
{
globalOptions::encoding = globalOptions::ENCODING_TYPE_ACP;
} else if (!_tcsicmp(compareCurWordArg,_T("oem")))
{
globalOptions::encoding = globalOptions::ENCODING_TYPE_OEM;
} else if (!_tcsicmp(compareCurWordArg,_T("utf8")))
{
globalOptions::encoding = globalOptions::ENCODING_TYPE_UTF8;
} else if (!_tcsicmp(compareCurWordArg,_T("utf16")))
{
globalOptions::encoding = globalOptions::ENCODING_TYPE_UTF16;
} else
{
throw eMsg(L"Unrecognised encoding word argument!\r\nValid choices are --encodingACP --encodingOEM --encodingUTF8 and --encodingUTF16. Terminate.");
}
} else if (!_tcsnicmp(compareCurWordArg,L"files",5))
{
compareCurWordArg += 5;
if (*compareCurWordArg == L':') compareCurWordArg++;
std::wstring filePath(compareCurWordArg);
globalOptions::regexes.insert(globalOptions::regexes.end(), new filesRegexPlaceHolder);
results->insert(results->end(),new filesRegexPlaceHolder);
boost::algorithm::trim_if(filePath,std::bind2nd(std::equal_to<wchar_t>(),L'"'));
loadFiles(filePath);
} else if (!_tcsicmp(compareCurWordArg,_T("full")))
{
globalOptions::fullPath = TRUE;
} else if (!_tcsicmp(compareCurWordArg,_T("fs32")))
{
globalOptions::disable64Redirector = false;
} else if (!_tcsicmp(compareCurWordArg,_T("long")))
{
globalOptions::display = _T("#t #s #m #f");
globalOptions::summary = TRUE;
} else if (!_tcsnicmp(compareCurWordArg,_T("limit"),5))
{
compareCurWordArg += 5;
if (*compareCurWordArg == _T(':'))
compareCurWordArg++;
globalOptions::lineLimit = _tcstoui64(compareCurWordArg,NULL,10);
if (!globalOptions::lineLimit)
{
std::wcerr << eMsg(L"Warning: You are limiting to infinity lines. Check one of your --limit options!\r\n");
}
} else if (!_tcsicmp(compareCurWordArg,_T("short")))
{
globalOptions::display = _T("#8");
} else if (!_tcsicmp(compareCurWordArg,_T("summary")))
{
globalOptions::summary = TRUE;
} else if (!_tcsicmp(compareCurWordArg,_T("norecursion")))
{
globalOptions::noSubDirs = TRUE;
} else if (!_tcsnicmp(compareCurWordArg,_T("timeout"),7))
{
compareCurWordArg += 7;
if (*compareCurWordArg == _T(':'))
compareCurWordArg++;
globalOptions::timeout = _tcstoul(compareCurWordArg,NULL,10);
if (!globalOptions::timeout)
{
std::wcerr << eMsg(L"Warning: You are limiting to infinite time. Check one of your --timeout options!\r\n");
}
} else if (!_tcsnicmp(compareCurWordArg,_T("tx"),2))
{
compareCurWordArg += 2;
if (*compareCurWordArg == _T(':'))
compareCurWordArg++;
globalOptions::timeout = _tcstoul(compareCurWordArg,NULL,10);
if (!globalOptions::timeout)
{
std::wcerr << eMsg(L"Warning: You are limiting to infinite time. Check one of your --timeout options!\r\n");
}
} else
{
throw eMsg(L"Could not understand word argument! Ensure all of your directives are spelled correctly. Terminate.");
}
}
```
I'd post the long one but it's over 500 lines.
Are there better ways of handling this particular problem or should I just leave it as a long method?
EDIT: I'm not looking for a tokenizing library -- I already did the dirty work on that. I'm curious if it would make sense to make stub methods out of the larger dirty method.
Billy3 | I'm sure that there's an equivalent of getopt(3) function for Windows.
Here's the first hit from Google - [Pete Wilson](http://www.pwilson.net/sample.html).
Or you can look into [Boost Program Options](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options.html) for a decent C++ library. | What you're needing is a [command line option parser library](http://www.google.com.au/search?hl=en&q=command+line+option+parser+c%2B%2B&btnG=Google+Search&meta=&aq=f&oq=Command+line+option+parser) to take care of the messy details of processing the commandline arguments.
I'm not sure which one is the best for C++ since I'm a C# developer who uses [CSharpOptParse](http://sourceforge.net/projects/csharpoptparse/)...but the concept should be the same so hopefully knowing what to look for will point you in the right direction. | Break apart long commandline testing method | [
"",
"c++",
"methods",
""
] |
I am launching a java jar file which often requires more than the default 64MB max heap size. A 256MB heap size is sufficient for this app though. Is there anyway to specify (in the manifest maybe?) to always use a 256MB max heap size when launching the jar? (More specific details below, if needed.)
---
This is a command-line app that I've written in Java, which does some image manipulation. On high-res images (about 12 megapixels and above, which is not uncommon) I get an OutOfMemoryError.
Currently I'm launching the app from a jar file, i.e.
`java -jar MyApp.jar params...`
I can avoid an OutOfMemoryError by specifying 256MB max heap size on the command line, i.e.:
`java -Xmx256m -jar MyApp.jar params...`
However, I don't want to have to specify this, since I know that 256MB is sufficient even for high-res images. I'd like to have that information saved in the jar file. Is that possible? | you could also use a wrapper like [launch4j](http://launch4j.sourceforge.net/index.html) which will make an executable for most OS:es and allows you to specify VM options. | Write a batch or shell script containing the following line. Put into the folder, where MyApp.jar is stored.
```
java -Xmx256M -jar MyApp.jar
```
After that always open this batch/script file in order to launch the JAR file.
Although, This will not embed specification of virtual memory size into jar file itself. But, It can override the problem to write the same command often on command line. | Can I set Java max heap size for running from a jar file? | [
"",
"java",
"memory-management",
"jar",
""
] |
C# question here..
I have a UTF-8 string that is being interpreted by a non-Unicode program in C++.. This text which is displayed improperly, but as far as I can tell, is intact, is then applied as an output filename..
Anyway, in a C# project, I am trying to open this file with an *System.Windows.Forms.OpenFileDialog* object. The filenames I am getting from this object's *.FileNames[]* is in Unicode (UCS-2). This string, however, has been misinterpreted.. For example, if the original string was **0xe3 0x81 0x82**, a FileName[].ToCharArray() reveals that it is now **0x00e3 0x0081 0x201a** .... .. It might seem like the OpenFileDialog object only padded it, but it is not.. In the third character that the OpenFileDialog produced, it is different and I cannot figure out what happened to this byte..
My question is: Is there any way to treat the filenames highlighted in the OpenFileDialog box as UTF-8?
I don't think it's relevant, but if you need to know, the string is in Japanese..
Thanks,
kreb
**UPDATE**
First of all, thanks to everyone who's offered their suggestions here, they're very much appreciated.
Now, to answer the suggestions to modify the C++ application to handle the strings properly, it doesn't seem to be feasible. It isn't just one application that is doing this to the strings.. There are actually a great number of these applications in my company that I have to work with, and it would take huge amount of manpower and time that simply isn't available. However, sean e's idea would probably be the best choice if I were to take this route..
@Remy Lebeau: I think hit the nail right on the head, I will try your proposed solution and report back.. :) I guess the caveat with your solution is that the *Default* encoding has to be the same on the C# application environment as the C++ application environment that created the file, which certainly makes sense as it would have to use the same code page..
@Jeff Johnson: I'm not pasting the filenames from the C++ app to the C# app.. I am calling OpenFileDialog.ShowDialog() and getting the OpenFileDialog.FileNames on DialogResult.OK.. I did try to use Encoding.UTF8.GetBytes(), but like Remy Lebeau pointed out, it won't work because the original UTF8 bytes are lost..
@everyone else: Thanks for the ideas.. :)
kreb
**UPDATE**
@Remy Lebeau: Your idea worked perfectly! As long as the environment of the C++ app is the same as the environment of the C# app is the same (same locale for non-Unicode programs) I am able to retrieve the correct text.. :)
Now I have more problems.. Haha.. Is there any way to determine the encoding of a string? The code now works for UTF8 strings that were mistakenly interpreted as ANSI strings, but screws up UCS-2 strings. I need to be able to determine the encoding and process each accordingly. GetEncoding() doesn't seem to be useful.. =/ And neither is StreamReader's CurrentEncoding property (always says UTF-8)..
P.S. Should I open this new question in a new post? | 0x201a is the Unicode "low single comma quotation mark" character. 0x82 is the Latin-1 (ISO-8859-1, Windows codepage 1252) encoding of that character. That means the bytes of the filename are being interpretted as plain Ansi instead of as UTF-8, and thus being decoded from Ansi to Unicode accordingly. That is not surprising, as the filesystem has no concept of UTF-8, and Windows assumes non-Unicode filenames are using the OS's default Ansi encoding.
To do what you are looking for, you need access to the original UTF-8 encoded bytes so you can decode them properly. One thing you can try is to pass the FileName to the GetBytes() method of System.Text.Encoding.Default (in theory, that is using the same encoding that was used to decode the filename, so it should be able to produce the same bytes as the original), and then pass the resulting bytes to the GetString() method of System.Text.Encoding.UTF8. | I think your problem is at the begining:
> I have a UTF-8 string that is being
> interpreted by a non-Unicode program
> in C++.. This text which is displayed
> improperly, but as far as I can tell,
> is intact, is then applied as an
> output filename..
If you load a UTF-8 string with a non-unicode program and then serialize it, it will contain non-unicode chars.
Is there any way that your C++ program can handle Unicode? | OpenFileDialog filename as UTF8 | [
"",
"c#",
"windows",
"unicode",
"utf-8",
""
] |
What's the correct C# syntax to do the following using sexier syntax?
```
string[] arr = ///....
List<string> lst = new List<string>();
foreach (var i in arr) {
lst.Add(i);
}
```
I feel like this could be a one liner using something like:
arr.Select(x => lst.Add(x));
but I'm not quite bright enough to figure out the right syntax. | .ToList() is fine, but to be honest, you don't need LINQ for that:
```
List<int> list = new List<int>(arr);
``` | ```
List<string> lst = arr.ToList();
```
<http://msdn.microsoft.com/en-us/library/bb342261.aspx> | Using LINQ/Lambdas to copy a String[] into a List<String>? | [
"",
"c#",
"linq",
""
] |
There is a strange behavior I cannot understand.
Agreed that float point number are approximations, so even operations that are obviously returning a number without decimal numbers can be approximated to something with decimals.
I'm doing this:
```
int num = (int)(195.95F * 100);
```
and since it's a floating point operation I get 19594 instead of 19595.. but this is kind of correct.
What puzzles me is that if I do
```
float flo = 195.95F * 100;
int num = (int) flo;
```
I get the correct result of 19595.
Any idea of why this happens? | I looked to see if this was the compiler doing the math, but it behaves this way even if you force it out:
```
static void Main()
{
int i = (int)(GetF() * GetI()); // 19594
float f = GetF() * GetI();
int j = (int)f; // 19595
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int GetI() { return 100; }
[MethodImpl(MethodImplOptions.NoInlining)]
static float GetF() { return 195.95F; }
```
It looks like the difference is whether it stays in the registers (wider than normal r4) or is forced to a `float` variable:
```
L_0001: call float32 Program::GetF()
L_0006: call int32 Program::GetI()
L_000b: conv.r4
L_000c: mul
L_000d: conv.i4
L_000e: stloc.0
```
vs
```
L_000f: call float32 Program::GetF()
L_0014: call int32 Program::GetI()
L_0019: conv.r4
L_001a: mul
L_001b: stloc.1
L_001c: ldloc.1
L_001d: conv.i4
L_001e: stloc.2
```
The only difference is the `stloc.1` / `ldloc.1`.
This is supported by the fact that if you do an optimised build (which will remove the local variable) I get the same answer (19594) for both. | this code...
```
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
float result = 195.95F*100;
int intresult = (int)(195.95F * 100);
}
}
}
```
give this IL
```
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 14 (0xe)
.maxstack 1
.locals init ([0] float32 result,
[1] int32 intresult)
IL_0000: nop
IL_0001: ldc.r4 19595.
IL_0006: stloc.0
IL_0007: ldc.i4 0x4c8a
IL_000c: stloc.1
IL_000d: ret
} // end of method Program::Main
```
look at IL\_00001 -> the compier has done the calc..
Otherwise there are the decimal -> binary conversion problem | Problem converting from int to float | [
"",
"c#",
"floating-point",
""
] |
I'm writing a small app that requires a few listboxes, buttons, textboxes. It'll be linked with Boost, MySQL, etc. C++ static libs. The project requires win32 functions. I figure Winforms will be fine (MFC and CodeJock require too much time).
So C++/CLI seems perfect for the job. Just use standard C++ along side the GUI. Then I run across threads suggesting you write your GUI in C# instead. Then use p/Invoke (slow) or a C++/CLI interface to your standard C++ DLL's.
Example: <http://social.msdn.microsoft.com/Forums/en-US/clr/thread/6ae877ac-07b4-4d26-8582-de475ee9a5cb>
Why? What advantage is there in using C# for your winforms GUI instead of C++/CLI (they look the same, the commands are the same). What disadvantage is there in using C++/CLI executable instead of standard C++ executable. I can understand if cross-platform compatibility was an issue, but then you could simply not use managed features (other than the GUI).
I don't understand why you would use C#, and then go so far to separate it with an "engine DLL". Unless of course the "engine DLL" was being used for other applications as well.
Thanks | I think most recommendations with regard to this question center around the fact that C# is just a better environment to create .NET applications with than C++/CLI. The syntax is cleaner, the tooling is better - both within Visual Studio and from 3rd parties. You will get more and better support from developers who will almost all be more familiar with C#.
C++/CLI applications are different enough from standard C++ with all those ^ and % characters that I at least feel it is NOT C++.
Most advice is also coming from the point of view that you want to create a .NET application and C++/CLI is used more as a glue layer. Whenever I have used C++/CLI, it was grudgingly and almost always because some third-party library had many complex C/C++ objects that it passed around. When using C# and P/Invoke, you often have to create classes to mirror the structs and classes that are in the C++ header files of the software you are interfacing with. Keeping those in sync is labor intensive and making mistakes is easy to do. Furthermore, figuring out how to marshal a struct with pointers to structs of arrays of struct will make your brain melt!
My general advice is to use C# (or VB.NET) to create as much code as feasible for your application. Use P/Invoke when your need to call the Win32 API and/or 3rd party SDKs is limited and the interfaces and parameters are simple. Use C++/CLI as a glue layer when this is not possible.
In a team environment, your fellow developers will thank you for limiting your usage of C++/CLI to only where it is absolutely, positively required. C++/CLI expertise is just not that common. | Personally, I love C++/CLI, but I'd still rather write my UI in C#.
C++/CLI is **great** for working directly with Win32 or talking to legacy code, but it's a little too verbose for my liking when it comes to UI code. WinForms UI code in C# is nice and simple (for the most part, haha). Writing UI code in C++ is almost always messy (just look at MFC).
Why not just create your UI in one C# assembly and put all of your lower-level code in a C++/CLI assembly? The nice thing about C++/CLI is that you can create a managed layer that your C# code can easily call. That managed layer can then easily forward calls to a native layer of straight C++ or C code. | .NET GUI - C# vs C++/CLI | [
"",
"c#",
"windows",
"user-interface",
"c++-cli",
""
] |
In pre-.NET world I always assumed that int is faster than byte since this is how processor works.
Now it's matter habit of using int even when bytes could work, for example when byte is what is stored in database
Question: How .NET handles byte type versus int from point view of performance/memory.
Update:
Thanks for the input. Unfortunately, nobody really answered the question. How .NET handles byte vs. int.
And if there is no difference in performance, then I like how chills42 put it:
int for arithmetics
bytes for binary
Which I will continue to do. | OK, I just opened disassembly window. There is nothing there but regular "mov byte"
So, .NET/CLR does not add anything to this. And all arithmetic operations done against int values, so no difference between bytes and int there. | Your pre-.NET assumption were faulty -- there have always been plenty of computer systems around that, while nominally "byte-addressable", would have to set a single byte by reading a full word, masking it out to alter the one byte of it, write it all down -- slower than just setting a full word. It depends on the internals of the way the processor and memory are connected, not on the programmer-visible architecture.
Whether in .NET or native code, focus first on using the data as semantically correct for your application, not on trying to double guess the computer system's architect -- "Premature optimization is the root of all evil in programming", to quote Knuth quoting Hoare. | performance of byte vs. int in .NET | [
"",
"c#",
".net",
""
] |
I am using IE 6 (corporate mandated version) on XP, as well as (primarily) Firefox 3. In these, I am making a DHTML table using the prototype.js library version 1.6.0.3.
I have event handler javascript code to add a row to the table, which works fine under Firefox, but is completely ignored under Internet Explorer. I can walk through the code in the MS "script debugger" (yes, I know it's old and deprecated, but it was available), so I know the event is being hooked.
The code is something of the form:
```
var xTable = $( 'x_list') // id of x...
var aRow = new Element( 'tr')
aRow.setAttribute( 'id', id)
. . .
var xEl = new Element( 'td')
. . .
aRow.insert( xEl)
. . .
// alert( aRow.inspect() )
// alert( xTable.inspect() )
debugger // check insert() implementation under IE
xTable.insert( aRow)
```
Has anybody else had experience with conflicts between Element.insert() and Explorer? | You have to insert new TR elements into a TBODY not directly into TABLE. Otherwise IE won't show/insert/whatever it. | Try creating a `<tbody>` element inside the `<table>` you're working with, and then appending to that element instead of the `<table>`.
That's the first thing I would try. I vaguely remember Javascript manipulation of tables being weird if there was no `<tbody>` element. | prototype.js - Element.insert( Element) ignored under IE 6? | [
"",
"javascript",
"internet-explorer",
"internet-explorer-6",
"prototypejs",
""
] |
I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.
For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over again to the numbers yielded. The generator always yields bigger numbers than the one passed as argument, and for 2 different numbers will never yield the same number.
mygenerator(2): 4 5
mygenerator(4) : 10 11 12
mygenerator(5): 9 300 500
So the set (9,10,11,12,300,500) has "distance" 2 from the original number, 2. If I apply it to the number 9, I will get a set of numbers with distance "3" from the original 2.
Essentially what I want is to create a set that has a specified distance from a given number and I have problems figuring out how to do that in Python. Help much appreciated :) | This solution does not require to keep all results in memory: (in case it doesn't fit in memory etc)
```
def grandKids(generation, kidsFunc, val):
layer = [val]
for i in xrange(generation):
layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
return layer
```
Example:
```
def kids(x): # children indices in a 1-based binary heap
yield x*2
yield x*2+1
>>> list(grandKids(3, kids, 2))
[16, 17, 18, 19, 20, 21, 22, 23]
```
Btw, solution in Haskell:
```
grandKids generation kidsFunc val =
iterate (concatMap kidsFunc) [val] !! generation
``` | Suppose our generator yields square and cube of given number that way it will output unique
so if we want to get numbers at dist D in simplest case we can recursively get numbers at dist D-1 and then apply generator to them
```
def mygen(N):
yield N**2
yield N**3
def getSet(N, dist):
if dist == 0:
return [N]
numbers = []
for n in getSet(N, dist-1):
numbers += list(mygen(n))
return numbers
print getSet(2,0)
print getSet(2,1)
print getSet(2,2)
print getSet(2,3)
```
output is
```
[2]
[4, 8]
[16, 64, 64, 512]
[256, 4096, 4096, 262144, 4096, 262144, 262144, 134217728]
``` | Generate from generators | [
"",
"python",
"generator",
""
] |
did someone tried this code library and have opinion about it?
<http://code.msdn.microsoft.com/exprserialization>
10x | It looks like the project was abandoned but I did some work on it and now it works with .NET 4.0 and Silverlight. I made bug fixes to their code and also made it more DAL-independent.
<http://expressiontree.codeplex.com/> | I have found that it cannot serialize custom closures and I am currently writing my own binary serializer. With that said the fact that expression tree serialization was not included in .net 4.0 is extremely dissapointing. | Opinions on Expression Tree Serialization Library from CodePlex? | [
"",
"c#",
"linq",
"wcf",
"entity-framework",
"serialization",
""
] |
So i have been looking into JNI calls so i can interact with some pre written C++ programs, i dont know any C++ but am trying to learn some basics. I have just been trying to do a simple call to a method outside my JNI method but always get the following error:
error c3861 'myMethod': identifier not found
```
#include <stdio.h>
#include <string.h>
#include "StringFuncs.h"
JNIEXPORT jstring JNICALL Java_StringFuncs_changeWord(JNIEnv *env, jobject obj, jstring inStr, jint inLen)
{
const char *inString;
inString = env->GetStringUTFChars(inStr, NULL);
char otherString[40];
strcpy_s(otherString,inString);
if(myMethod())
{
memset(otherString, '-', inLen);
}
jstring newString = env->NewStringUTF((const char*)otherString);
return newString;
}
bool myMethod()
{
return true;
}
int main()
{
return 0;
}
```
Any words of wisdome? | You have to declare your methods before you call them. So in your header type
bool myMethod();
Or you can move the code above your \_changeWord function, then the declaration/definition is in one. | Move myMethod() above Java\_StringFuncs\_changeWord() in the source file. | Method Calls in C++ with JNI? | [
"",
"c++",
"methods",
"java-native-interface",
""
] |
Is it possible to get an XML file (not HTML) from a server, add/remove/edit particular parts of it with client-side JavaScript, and then send it back to the server to save it? JSON or any other markup/data interchange format works too. | Yes. Using jQuery...
```
$.get("myGetUrl.php", function(data) {
var xml = $(data);
xml.find("myNode").text("newValue");
$.post("myPostUrl.php", xml, function(resp) {
alert(resp);
}, "xml");
});
``` | Yes it's possible. Seach for "XML DOM", and you can edit it on the client quite easily. | Editing an XML file with JavaScript? | [
"",
"javascript",
"xml",
""
] |
Working on some code and I'm given the error when running it from the command prompt...
```
NameError: name 'Popen' is not defined
```
but I've imported both `import os` and `import sys`.
Here's part of the code
```
exepath = os.path.join(EXE File location is here)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
```
Am I missing something elementary? I wouldn't doubt it. Thanks! | you should do:
```
import subprocess
subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
# etc.
``` | Popen is defined in the subprocess module
```
import subprocess
...
subprocess.Popen(...)
```
Or:
```
from subprocess import Popen
Popen(...)
``` | Popen and python | [
"",
"python",
"popen",
""
] |
I need to implement a background process that runs on a remote windows server 24/7. My development environment is C#/ASP.NET 3.5. The purpose of the process is to:
* Send reminder e-mails to employees and customers at appropriate times (say 5:00PM on the day before a job is scheduled)
* Query and save GPS coordinates of employees when they are supposed to be out on jobs so that I can later verify that their positions were where they were supposed to be.
If the process fails (which it probably will, especially when updates are added), I need for it to be restarted immediately (or within just a few minutes) as I would have very serious problems if this process failed to send a notification, log a GPS coordinate, or any of the other tasks its meant to perform. | 1. Implement your process as a Windows service.
For a straightforward example of how
to code a Windows service this in
.Net see <http://www.developer.com/net/csharp/article.php/2173801> .
2. To control what happens should the
service fail configure this through
the "Recovery" tab on your service
in services.msc. (see image below)
3. For higly critical operation you
might look into setting up a server cluster for mitigating single
server failure (see <http://msdn.microsoft.com/en-us/library/ms952401.aspx> ).
[](https://i.stack.imgur.com/nFrdY.gif)
(source: [microsoft.com](https://technet.microsoft.com/en-us/library/Bb742520.ssvc104_big(en-us,TechNet.10).gif)) | You need a Windows Service. You can do non-visual iterative operations in windows services. | How to keep a process running on a remote windows server | [
"",
"c#",
"asp.net",
"multithreading",
"process",
""
] |
If I'm presenting code usually I show it in a syntax-highlighting text editor. But I've been doing more "live coding" in some presentations recently where it's important to show off some IDE tooling.
How should I set up Eclipse when preparing for a presentation or demo?
* Is there a way to save and switch out
presenter settings?
* Is there a convenient way to increase
font-size?
* Any neat tools or tricks worth mentioning? (Like ZoomIt or the zoom feature in OSX) | "Is there a way to save and switch out presenter settings?"
**Create a new "Perspective" for each specific task you are going to do at the conference.** So when you develop at home you would use c++/java/debug perspective and then when you present you would use c++-presentation/java-presentation/debug-presentation perspective.
How to create the new perspective for each task:
* Copy your current development presentation
* Change to a lower resolution 800x600 or 1024x800
* Tweak all different sizes of each GUI item in each perspective and make sure it looks good on a presentation
* Get a bunch of feedback from friends to see what they think should change about your eclipse setup.
---
Is there a convenient way to increase font-size?
**You can change the font used by your OS and that will affect the font used by Eclipse.** Or you can change the font from within Eclipse using:
* Menubar "Window" --> Menuitem "Preferences --> Left-textwindow "General" --> "Appearance" --> "Colors and Fonts"
* Double click the item you want to change the font for
---
Any neat tools or tricks worth mentioning?
**I'm sure there are... but presentations aren't about neat tricks.** All the best presentations i've seen use very simple tools and the presentation is good because of the presenter's talking and interacting with the crowd. All the worst presentations i've seen depend on some neat trick that fails... | As graham.reeds says, but I prefer to crank up the font size rather than turn down the resolution.
Have everything you need for the presentation in its own workspace, so you don't get confused by all the real projects you normally work on. I once spent 30 minutes in a tutorial trying to work out why I couldn't get a test to pass, and discovered that I had been editing a test in one project but running a test with the same name in another. Luckily I had exercises for the audience to get on with in the meantime, but I wouldn't want to go through that embarrassment again!
Another benefit of a separate workspace is that style settings for presentation mode do not affect those for everyday work.
Also, turn off all apps that might pop something up during the presentation: mail monitors, instant messaging, etc. | How should I set up Eclipse when preparing for a presentation or demo? | [
"",
"java",
"eclipse",
""
] |
I have a cron job the executes a PHP script. The cron is setup to run every minute, this is done only for testing purposes. The PHP script it is executing is designed to convert videos uploaded to the server by users to a flash format (eg... .flv). The script executes fine when manually doing it via command line, however when executing via cron it starts fine but after one minute it just stops.
It seems that when the next cron is executed it "kills" the last cron execution.
I added the following PHP function:
```
ignore_user_abort(true);
```
In hopes that it would not abort the last execution, I tested setting the cron to run every 5 minutes, which works fine, however a conversion of a video may take over 5 minutes so I need to figure out why its stoping when another cron is executed.
Any help would be appreciated.
Thank you!
EDIT:
My cron looks like:
```
*/1 * * * * php /path_to_file/convert.php
``` | I don't think cron kills any processes. However, cron isn't really suitable for long running processes. What may be happening here is that your script tramples all over itself when it is executed multiple times. For example, both PHP processes may be trying to write to the same file at the same time.
First, make sure you not only look in the php error log but also try to capture output from the PHP file itself. E.g:
```
*/1 * * * * * php /path/to/convert.php & >> /var/log/convert.log
```
You could also use a simplistic lockfile to ensure that convert.php isn't executed multiple times. Something like:
```
if (file_exists('/tmp/convert.lock')) {
exit();
}
touch('/tmp/convert.lock');
// convert here
unlink('/tmp/convert.lock');
``` | `cron` itself won't stop a previous instance of a job running so, if there's a problem, there's almost certainly something in your PHP doing it. You'll need to post that code. | Does a cron job kill last cron execution? | [
"",
"php",
"cron",
"scheduled-tasks",
""
] |
Assume that I have a class that exposes the following event:
```
public event EventHandler Closing
```
How should methods that are registered to this event be named? Do you prefer to follow the convention that Visual Studio uses when it assigns names to the methods it generates (aka. +=, Tab, Tab)? For example:
```
private void TheClass_Closing( object sender, EventArgs e )
```
Or do you use your own style to name these methods?
I've tried different ways to name these methods (like `TheClassClosing`, `HandleClosing`, etc.). But I haven't found a good style to indicate that the intent of a method is to handle a registered event. I personally don't like the style (underscore) that Visual Studio uses to generate method names.
I know that registered event-handling methods are always private and that there is no naming convention like the one for methods that *raise* events (e.g., `OnClosing`). | The two common options for naming is either after what the method does:
```
theObject.Closing += SaveResults;
```
Or alternatively after what the method handles:
```
theObject.Closing += ClosingHandler;
```
Which is preferable really depends a bit on context.
In the first case it is immediately clear what the handler is going to do, which makes the code registering the handler more readable... but looking at the handler `SaveResults` in isolation it is not going to be necessarily obvious when it is going to be called, unless the event arguments have an obvious name (`ClosingEventArgs` or some such).
In the second case, the registration is more opaque (okay, so what is going to happen when `Closing` happens?), but on the other hand, looking at the handler implementation it will be obvious what is going on.
I guess the one to choose depends on which of the two you want to be more obvious; the site of the registration, or the implementation of the handler.
Or alternatively, you can go for the unholy combination of both methods:
```
theObject.Closing += ClosingHandlerSaveResults;
```
Now both the registration site and the implementation are equally obvious, and neither looks particularly elegant (plus, it probably violates the DRY principle).
For the record I prefer the first naming scheme when `theObject` is contained in a different scope from the implementation of `SaveResults`, and the second scheme when I am wiring up handlers to events that are all contained within the same class. | Name it after what the handler actually does.
```
// event += event handler
saveButton.Click += SaveData();
startButton.Click += StartTheTimer();
``` | Naming methods that are registered to events | [
"",
"c#",
".net",
"events",
"naming-conventions",
""
] |
I have a window containing an iframe, containing an iframe, like so:
```
+---------------+
| Top |
| +-----------+ |
| | Middle | |
| | +-------+ | |
| | | Inner | | |
| | +-------+ | |
| +-----------+ |
+---------------+
```
Top and Middle are on the same domain, but Inner is on a different domain. I need Inner to communicate with Top. The only way I know of to do this which is supported in IE7 (which I need to support) is to change the hash of the window's location. However, I don't want the information to be flickering in the location bar, so I've introduced the Middle iframe.
I want Inner to change Middle's hash. Middle will read its hash and inform Top, whom it has permission to speak to directly.
**However**, in Firefox 3, I've been unable to write to Middle's hash from Inner. No error is raised, but the hash appears unchanged. Writing to its `location.href` raises a permissions error.
Top can write to Middle's hash, however, and Middle can write to Inner's hash, and Top can write to Inner's hash, and Inner and Middle can both write to Top's hash, so the *only ordered pair* that doesn't work is the one I want! (I've been working on this for a while.)
I've reproduced this in a minimal test case. At first, I served all three pages from the same domain. When I put Inner on a different domain, I get the problematic behavior. When I put Middle on the second domain, everyone can write to everyone again.
Why can't Inner write to Middle's hash?
---
**Addendum**: Many people have suggested that this shouldn't be possible because of the same-origin policy. This is exactly the policy I am trying to get around. This exact case--setting (but not reading) another window's location--is supposed to be possible across domains. I haven't found browser documentation to this effect, but I have found many articles and demos. This is essentially the precursor to HTML 5's `postMessage()`.
Ref: <http://softwareas.com/cross-domain-communication-with-iframes> | Parent frames can set children's iframe 'src' attribute (here with jquery) using:
```
$("#iframeWindow").attr('src', "http://<CHILD URL>/#hello");
```
Children iframes can set parent window's href (address bar content) using:
```
window.top.location.href = "http://<PARENT URL>/#hello"
```
and in the parent and/or child, you need to poll for changes,
```
var last = "";
setInterval(function() {
if(last == window.location.href) return;
last = window.location.href;
//do stuff with 'window.location.hash'
}, 1000);
```
note, it would be nice if you could
```
window.top.location.href = window.top.location.href + "#hello"
```
but reading of location object (href and hash) is not allowed
tested on 3rd Nov 11, on chrome, ie6/7/9, firefox 3.6/4
edit1: can put a demo live if people would like
edit2: <http://dl.dropboxusercontent.com/u/14376395/html/xdomain.html> :)
edit3: beware: if you're using this method, make sure you have control over all iframe'd pages otherwise nefarious 3rd party sites could potentially control yours using hash tags
edit4: better solution <http://ternarylabs.com/2011/03/27/secure-cross-domain-iframe-communication/> currently being used by the Google JavaScript API
edit5: dropbox domain name changed to 'dl.dropboxusercontent.com' | To be able to set the location.hash you must first get the location. The same origin policy forbids you from getting the location. | Why can't an iframe set its parent's location.hash? | [
"",
"javascript",
"firefox",
"iframe",
"security",
""
] |
Often, when I am developing in PHP, I want to see minor changes instantaneously. This requires me to either FTP to a web server and then refresh, or use a localhost server, both of which(as I understand) are essentially the same thing.
What I would like to know is, is there an IDE or other way to parse PHP output in a dynamic fashion? I guess what I am thinking of is the WYSIWYG pane in some editors able to display code real-time.
I understand the client-server paradigm, but would rather not have to upload the same file 40 times when making changes/error handling/etc. | You can always just save your files *inside* your localhost folder. Tools like [xampp](http://www.apachefriends.org/en/xampp.html) make running a php server effortless. Open the file in a browser, and whenever you make changes they will instantly be visible without having to copy the files around. | I've heard that ActiveState's Komodo is IDE for php behaving more-less the way you described (at least it has dynamic syntax check, so it has to parse the script locally).
Try [Komodo Website.](http://www.activestate.com/komodo/) | Can I parse PHP locally without the use of a local host server? | [
"",
"php",
"ide",
"wysiwyg",
""
] |
Does anyone know of a reliable way to validate International Bank Account Number (IBAN) and Bank Identifier Code (BIC) in java? | These might be worth a look:
<http://soastation.googlepages.com/iban-checkdigit-src.jar>
<http://developers.sun.com/docs/javacaps/designing/capsswftintprj.ghfyv.html> | Apache Commons Validator has IBAN validation (since version 1.4)
Home page: <http://commons.apache.org/validator/>
Javadoc: <https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/checkdigit/IBANCheckDigit.html>
Maven dependency:
```
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>
```
*Edit: Updated javadoc link.* | reliable way to validate IBAN/BIC in java | [
"",
"java",
"banking",
""
] |
I have a string:
> This is a text, "Your Balance left $0.10", End 0
How can I extract the string in between the double quotes and have only the text (without the double quotes):
> Your Balance left $0.10
I have tried `preg_match_all()` but with no luck. | As long as the format stays the same you can do this using a regular expression. `"([^"]+)"` will match the pattern
* Double-quote
* At least one non-double-quote
* Double-quote
The brackets around the `[^"]+` means that that portion will be returned as a separate group.
```
<?php
$str = 'This is a text, "Your Balance left $0.10", End 0';
//forward slashes are the start and end delimeters
//third parameter is the array we want to fill with matches
if (preg_match('/"([^"]+)"/', $str, $m)) {
print $m[1];
} else {
//preg_match returns the number of matches found,
//so if here didn't match pattern
}
//output: Your Balance left $0.10
``` | For everyone hunting for a full featured string parser, try this:
```
(?:(?:"(?:\\"|[^"])+")|(?:'(?:\\'|[^'])+'));
```
Use in preg\_match:
```
$haystack = "something else before 'Lars\' Teststring in quotes' something else after";
preg_match("/(?:(?:\"(?:\\\\\"|[^\"])+\")|(?:'(?:\\\'|[^'])+'))/is",$haystack,$match);
```
Returns:
```
Array
(
[0] => 'Lars\' Teststring in quotes'
)
```
This works with single and double quoted string fragments. | How to extract a string from double quotes? | [
"",
"php",
"string",
"preg-match",
"preg-match-all",
"double-quotes",
""
] |
I am looking for an open source library to parse and execute formula/functions in C#.
I would like to create a bunch of objects that derive from an interface (i.e. IFormulaEntity) which would have properties/methods/values and the allow a user to specify formulas for those objects.
For example, I might have
```
public class Employee : IForumulaEntity
{
public double Salary { get; set; }
public void SendMessage(string message)
}
```
Then allow an application user to write something like;
```
Employee person = <get from datasource>
if (person.Salary > 1000)
person.Salary += 1000;
person.SendMessage("Hello");
```
This "looks like C#" but it would be a simplified programming language. I know it's alot to ask. I would expect my users to be reasonably capable (i.e. can write their own Excel formulas). | Look into the Rules Engine functionality that is part of Windows Workflow Foundation.
This is not a place one would think to look. However, as part of the work they did to produce a UI that allows a Workflow developer to use configurable rules and expressions, they've come up with a way to do the same thing in your own application, even if you are not using Workflow at all. Their documentation includes examples of hosting this functionality in a Windows Forms application. | I've used ANTLR, FSLEX/FSYACC and Managed Babel. All do what you are asking, and while all are free, only the first is open source.
Antlr: <http://antlr.org/>
FSLEX: <http://www.strangelights.com/fsharp/wiki/default.aspx/FSharpWiki/fslex.html>
Managed Babel: <http://msdn.microsoft.com/en-us/library/bb165963.aspx> | Parse and execute formulas with C# | [
"",
"c#",
"parsing",
""
] |
I'm trying to develop a feed for an intranet document management system, so that staff can be notified of new documents. I have actually completed coding it, but there is no way to authenticate the user.
Also I'm not successful in adding the feed to news readers, but works with firefox Live Bookmark.
Any Ideas
Update:
Since I couldn't explain really well, I'll be specific I want it to work inside OutLook RSS Feeds.
Thanks | Well it's not very common, but i read an article about it a while ago
<http://labs.silverorange.com/archive/2003/july/privaterss>
that might help you out | You may try [HTTP authentication](http://ru.php.net/features.http-auth) (either basic or digest).
As for newsreaders, please clarify what are you doing and what's going wrong. | Is it possible to use authentication in RSS feeds using php? | [
"",
"php",
"feed",
"syndication-feed",
""
] |
I am quite new to windows forms. I would like to know if it is possible to fire a method in form 1 on click of a button in form 2?
My form 1 has a combobox. My form 2 has a Save button. What I would like to achieve is:
When the user clicks on Save in form 2, I need to check if form 1 is open. If it is open, I want to get the instance and call the method that would repopulate the combo on form 1.
I would really appreciate if I get some pointers on how I can do work this out. If there any other better way than this, please do let me know.
Thanks :)
**Added:**
Both form 1 and form 2 are independent of each other, and can be opened by the user in any order. | You can get a list of all currently open forms in your application through the [Application.OpenForms](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.openforms.aspx) property. You can loop over that list to find Form1. Note though that (in theory) there can be more than one instance of Form1 (if your application can and has created more than one instance).
Sample:
```
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form1))
{
((Form1)form).Close();
}
}
```
This code will call `YourMethod` on all open instances of Form1.
(edited the code sample to be 2.0-compatible) | Of course this is possible, all you need is a reference to Form1 and a public method on that class.
My suggestion is to pass the Form1 reference in the constructor of Form2. | Firing a method in form 1 on click of a button on form2 | [
"",
"c#",
"winforms",
".net-2.0",
""
] |
How do I pass along an event between classes?
I know that sounds ridiculous (and it is) but I've been stumped on this for the past little while. Search didn't turn up a similar question so I figured I would pose it.
Here are the objects involved:
```
WinForm -> Speaker -> Tweeter
-> Woofer
```
[Speaker, Tweeter, Woofer] all declare a "SpeakToMe" event that sends a simple string message. The events are declared using the standard pattern:
```
public delegate void SpeakToMeHandler(object sender, SpeakToMeEventArgs e);
public event SpeakToMeHandler SpeakToMe;
protected virtual void OnSpeakToMe(string message)
{
if (SpeakToMe != null) SpeakToMe(this, new SpeakToMeEventArgs(DateTime.Now.ToString() + " - " + message));
}
```
SpeakToMeEventArgs is a simple class inheriting from EventArgs & containing a string property (Message).
On their own, each of these events works fine. E.g., I set a button in the form to create, subscribe, and fire the event for [Speaker, Tweeter, Woofer]. Each reports back properly.
The problem is when Speaker creates a [Tweeter, Woofer] and subscribes to their events.
What I want is for [Tweeter, Woofer] to fire their event, Speaker to consume it and fire it's own event. I thought this should be very straight forward:
```
void tweeter_SpeakToMe(object sender, SpeakToMeEventArgs e)
{
Console.Out.WriteLine("the tweeter is speaking: " + e.Message);
this.OnSpeakToMe("tweeter rockin' out [" + e.Message + "]");
}
```
Stepping through this function (in Speaker), Console.Out.WriteLine works. Continuing to step through OnSpeakToMe, shows that the delegate is null.
Speaker's SpeakToMe event is subscribed to by the form. I understood that this should prevent the event's delegate from being null.
I'm sure this is an easy one, what am I missing?
Btw, in case you're curious as to why I'm looking for this. [Speaker, Tweeter, Woofer] are my demo stand-ins for a really long data processing operation. The form runs several of these concurrently and requires progress updates from each class.
As always, any and all help is greatly appreciated!
**Update:** Thanks for all of the feedback everyone. I really appreciate the help! I picked up a couple of good tips (@David Basarab & @Brian) and a few different ideas on how to structure things. Again, much appreciated! | If I understood what you wanted in the basic sense. Is to have the Tweeter and Woofer fire an event that the Speaker is subscribed too then fire its own.
Here is my code that has this output
**OUTPUT**
***OnSpeak Message = OnSpeakToMeHander Orginal Message: Fired By Tweeter***
***OnSpeak Message = OnSpeakToMeHander Orginal Message: Fired By Woofer***
```
class Program
{
static void Main(string[] args)
{
Console.Clear();
try
{
Speaker speaker = new Speaker();
speaker.speakerEvent += new SpeakToMeHandler(Program.OnSpeak);
// Cause events to be fied
speaker.Tweeter.CauseEvent();
speaker.Woofer.CauseEvent();
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
Console.WriteLine("Stacktrace: {0}", ex.StackTrace);
}
}
public static void OnSpeak(object sendere, SpeakToMeEventArgs e)
{
Console.WriteLine("OnSpeak Message = {0}", e.Message);
}
}
public delegate void SpeakToMeHandler(object sender, SpeakToMeEventArgs e);
public class SpeakToMeEventArgs : EventArgs
{
public string Message { get; set; }
}
public class Speaker
{
public event SpeakToMeHandler speakerEvent;
public Tweeter Tweeter { get; set; }
public Woofer Woofer { get; set; }
public void OnSpeakToMeHander(object sender, SpeakToMeEventArgs e)
{
if (this.speakerEvent != null)
{
SpeakToMeEventArgs args = new SpeakToMeEventArgs
{
Message = string.Format("OnSpeakToMeHander Orginal Message: {0}", e.Message)
};
this.speakerEvent(this, args);
}
}
public Speaker()
{
this.Tweeter = new Tweeter();
this.Woofer = new Woofer();
Tweeter.tweeterEvent += new SpeakToMeHandler(this.OnSpeakToMeHander);
Woofer.wooferEvent += new SpeakToMeHandler(this.OnSpeakToMeHander);
}
}
public class Tweeter
{
public event SpeakToMeHandler tweeterEvent;
public void CauseEvent()
{
SpeakToMeEventArgs args = new SpeakToMeEventArgs()
{
Message = "Fired By Tweeter"
};
if (this.tweeterEvent != null)
{
this.tweeterEvent(this, args);
}
}
}
public class Woofer
{
public event SpeakToMeHandler wooferEvent;
public void CauseEvent()
{
SpeakToMeEventArgs args = new SpeakToMeEventArgs()
{
Message = "Fired By Woofer"
};
if (this.wooferEvent != null)
{
this.wooferEvent(this, args);
}
}
}
``` | [Eric Lippert](https://web.archive.org/web/20100330065821/http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx) warns against `if (SpeakToMe != null)` code. While it might not be an issue in your case (i.e. if you never remove events), you should get into the habit of using this instead:
```
var tmp = SpeakToMe;
if (tmp!=null) tmp(/*arguments*/);
```
In C#6 and higher, consider this terser code instead:
```
SpeakToMe?.Invoke(e)
```
The latter approach is suggested [on the MSDN](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators?redirectedfrom=MSDN#thread-safe-delegate-invocation) | C# Bubbling/Passing Along An Event | [
"",
"c#",
"events",
"message",
""
] |
I am currently reading Albahari's [C# 3.0 in a Nutshell](http://www.albahari.com/nutshell/) book and on [page 292](http://books.google.com.mt/books?id=_Y0rWd-Q2xkC&pg=PA292&lpg=PA292&dq=c%23+3.0+in+a+nutshell+linq+follows+a+demand-driven&source=bl&ots=R7ExT6QEXl&sig=TXfUDHFAJob6iXFimuDm9d6tJio&hl=mt&ei=cJ0wSsjUCtmZjAf3kay5Bw&sa=X&oi=book_result&ct=result&resnum=1) it says this about LINQ:
> LINQ follows a demand-driven *pull*
> model, rather than a supply-driven
> *push* model.
What does the above statement mean?
And what is the difference between a *pull* model and a *push* model ? | I am the client, I need something, **pull** it from the server.
I am the server, I have something, **push** it to the client. | This means that your LINQ queries will pull data from a datasource based on your queries and will only be done when executed. As opposed to a push model, where the server generates the data on its end and then pushes the data to a client. A push model would be like Blackberry Enterprise Server where email is pushed to the Blackberry device instead of the device constantly having to query for it. This also means that any changes since your LINQ query won't be reflected in your dataset. | C# LINQ: What is the difference between a Pull model and a Push model? | [
"",
"c#",
"linq",
"model",
"push",
"pull",
""
] |
I've got a class function that needs to "pass through" a particular keyword argument:
```
def createOrOpenTable(self, tableName, schema, asType=Table):
if self.tableExists(tableName):
return self.openTable(tableName, asType=asType)
else:
return self.createTable(self, tableName, schema, asType=asType)
```
When I call it, I get an error like this:
```
TypeError: createTable() got multiple values for keyword argument 'asType'
```
Is there any way to "pass through" such a keyword argument?
I've thought of several answers, but none of them are optimal. From worst to best:
* I could change the keyword name on one or more of the functions, but I want to use the same keyword for all three functions, since the parameter carries the same meaning.
* I could pass the `asType` parameter by position instead of by keyword, but if I add other keyword parameters to `openTable` or `createTable`, I'd have to remember to change the calls. I'd rather it automatically adapt, as it would if I could use the keyword form.
* I could use the `**args` form here instead, to get a dictionary of keyword parameters rather than using a default parameter, but that seems like using a sledgehammer to swat a fly (because of the extra lines of code needed to properly parse it).
Is there a better solution? | You're doing it right... Just take out the `self` in the second function call :)
```
return self.createTable(self, tableName, schema, asType=asType)
```
should be:
```
return self.createTable(tableName, schema, asType=asType)
``` | I have to say, that I first thought of a more complicated problem. But the answer of David Wolever is absolutely correct. It is just the duplicate self here, that creates the problem. This way, the positional parameters get out of line and asType is given a value as possitional parameter (once) and as keyword-parameter (second time!).
A much more interesting problem is, what to do, when you want to enhance the called routine (createTable in the example) without everytime enhancing the intermediate function. Here, the \*\*args solution makes the trick:
For example:
```
def createOrOpenTable(self, tableName, schema, **args):
if self.tableExists(tableName):
return self.openTable(tableName, **args)
else:
return self.createTable(tableName, schema, **args)
```
By this way, it is possible to enhance the signature of createTable and openTable without having to change createOrOpenTable any more.
When create and openTable can have different keyword-parameters, then of course both routines must be defined as follows:
```
def createTable(self, tableName, schema, asType=None, **others):
...
```
The others parameter eats up any keyword parameters unknown to the method -- it is also not needed to evaluate it. | Pass-through keyword arguments | [
"",
"python",
""
] |
I am using the following to display an amount:
String.Format("{0:C}", item.Amount)
This display £9.99
which is okay, but what if I want the application to be able to control the currency and to be able to change the currency to day
$9.99
How do I change the currency format via code | Specify the culture in the call to `Format`:
```
decimal value = 123.45M;
CultureInfo us = CultureInfo.GetCultureInfo("en-US");
string s = string.Format(us, "{0:C}", value);
``` | The currency symbol is defined by CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol. The property is read/write but you will probably get an exception if you try to change it, because NumberFormatInfo.IsReadOnly will be true...
Alternatively, you could format the number by explicitly using a specific NumberFormatInfo :
```
NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
nfi.CurrencySymbol = "$";
String.Format(nfi, "{0:C}", item.Amount);
``` | Changing the Currency via code in c# | [
"",
"c#",
""
] |
I am looking for some efficient way for building a immutable class, just like Java's String class. | 1. All the fields must be
`private` and preferably `final`
2. Ensure the class cannot be
overridden - make the class final,
or use static factories and keep
constructors private
3. Fields must be populated from the
Constructor/Factory
4. Don't provide any setters for the
fields
5. Watch out for collections. Use
`Collections.unmodifiable*`. Also, collections should contain only immutable Objects
6. All the getters must provide
immutable objects or use [defensive copying](http://www.javapractices.com/topic/TopicAction.do?Id=15)
7. Don't provide any methods that
change the internal state of the
Object.
[Tom Hawtin](https://stackoverflow.com/users/4725/tom-hawtin-tackline) pointed out that `final` can be optional. `String` `class` has a cache `hash` var that is only assigned when the hash function is called. | An object is immutable if none of its fields can be modified, so those fields must be `final`. If you don't want your object to be subclassed, you can make the class itself `final` as well, just like String is.
To easily construct an immutable object with a lot of information, you should look at the [Factory Pattern](http://en.wikipedia.org/wiki/Factory_pattern)
For more information, see [Wikipedia](http://en.wikipedia.org/wiki/Immutable_object) | Possible ways of making an Object immutable | [
"",
"java",
"immutability",
""
] |
Given
```
IList<int> indexes;
ICollection<T> collection;
```
What is the most elegant way to extract all **T** in **collection** based on the the indexes provided in **indexes**?
For example, if **collection** contained
```
"Brian", "Cleveland", "Joe", "Glenn", "Mort"
```
And **indexes** contained
```
1, 3
```
The return would be
```
"Cleveland," "Glenn"
```
Edit: Assume that **indexes** is always sorted ascending. | This assumes that the index sequence is a monotone ascending sequence of non-negative indices. The strategy is straightforward: for each index, bump up an enumerator on the collection to that point and yield the element.
```
public static IEnumerable<T> GetIndexedItems<T>(this IEnumerable<T> collection, IEnumerable<int> indices)
{
int currentIndex = -1;
using (var collectionEnum = collection.GetEnumerator())
{
foreach(int index in indices)
{
while (collectionEnum.MoveNext())
{
currentIndex += 1;
if (currentIndex == index)
{
yield return collectionEnum.Current;
break;
}
}
}
}
}
```
Advantages of this solution over other solutions posted:
* O(1) in extra storage -- some of these solutions are O(n) in space
* O(n) in time -- some of these solutions are quadradic in time
* works on any two sequences; does not require ICollection or IList.
* only iterates the collection once; some solutions iterate the collection multiple times (to build a list out of it, for instance.)
Disadvantages:
* harder to read | Here's a faster version:
```
IEnumerable<T> ByIndices<T>(ICollection<T> data, IList<int> indices)
{
int current = 0;
foreach(var datum in data.Select((x, i) => new { Value = x, Index = i }))
{
if(datum.Index == indices[current])
{
yield return datum.Value;
if(++current == indices.Count)
yield break;
}
}
}
``` | What is the most elegant way to get a set of items by index from a collection? | [
"",
"c#",
""
] |
I am looking to implement database like transactions in C#. I am processing multiple XML files. Any particular XML file can call child XML file during processing. The processor will start processing child XML file. If initialization conditions fail or there is an exception, then I want to resume processing parent XML file. This is the reason I am looking for transaction like implementation so that I can roll back. Is it possible to achieve? Can somebody provide me code snippet or pseudo code?
FYI - I am using .NET Compact Framework. | On the compact framework I think your going to roll your own transaction manager.
On the full framework you could have probably built something using TransactionScope and IEnlistmentNotification. You would have had to do quite a bit of work to get all your actions transactable as there is not support for transcations in xml out of the box. | Without rolling your own custom transaction management component this will be difficult to implement.
Can't you validate/verify all the XML up front before allowing your application to embark on it's processing phase? | Transactions with XML Files | [
"",
"c#",
".net",
"xml",
"compact-framework",
""
] |
I'm running a script to feed an exe file a statement like below:
```
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else:
z = ('288.', '0.', '72.', '144.', '216.')
for k in z:
exepath = os.path.join('\Program Files' , 'BRL-CAD' , 'bin' , 'rtarea.exe')
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = exepath + '-j' + str(el) + '-k' + str(z)
process=Popen('echo ' + cmd, shell=True, stderr=STDOUT )
print process
```
I'm using the command prompt and when I run the exe with these numbers there are times when It doesn't seem to be in order. Like sometimes it will print out 3 statements of the 52.62263 but then before they all are printed it will print out a single 26.5651 and then go back to 52.62263. It's not just those numbers that act like this. Different runs it may be different numbers (A 52.62263 between "two" 90 statements) . All in all, I want it to print it in order top to bottom. Any suggestions and using my code any helpful solutions? thanks! | I think what's happening right now is that you are not waiting for those processes to finish before they're printed. Try something like this in your last 2 lines:
```
from subprocess import Popen, STDOUT
stdout, stderr = Popen('echo ' + cmd, shell=True, stderr=STDOUT).communicate()
print stdout
``` | `z = ('0.')` is not a tuple, therefore your `for k in z` loop will iterate over the characters "0" and ".". Add a comma to tell python you want it to be a tuple:
```
z = ('0.',)
``` | Python and if statement | [
"",
"python",
"if-statement",
""
] |
Whenever I have some records/objects that I want to be in a certain order, I usually create a field called Ordinal.
I often wonder if it would be better to use an integer or a decimal value for the ordinal field.
This is a consideration when moving an object to a different position in the order:
* If you use consecutive integers, you have to do some serious reworking of all of the ordinals (or at least the ordinals that fall before the original position of the object being moved).
* If you use integers but space them out (maybe at 1000 intervals), then you can just change the ordinal to a mid point value between the surrounding objects where you want to move the object. This could fail if somewhere down the line you end up with consecutive integers.
* If you use decimal numbers you could just find the average of the surround object's ordinals and use that for the object to be moved.
* Maybe it would be possible to use a string, but I could see that getting pretty goofy.
I'm sure there are other considerations I haven't thought of.
What do you use and why? | "This could fail if somewhere down the line you end up with consecutive integers."
For this (probably rare and thus not performance important) case, you could implement a renumber method that spaces out again. When I used to program in COMAL (anyone know that language?), you could do this very thing with line numbers. | Decimals seem to solve your problem pretty well. Since Decimals are just base 10 floats, you actually have a lot of digits available. Unless you've seen cases where you've gotten out to quite a few digits and had reason to suspect a reason for an unlimited number of digits being necessary, I'd let it ride.
If you really need an alternative and don't see a need to stick with a basic data bype, you might go with [tumbler arithmetic](http://www.udanax.com/green/febe/tumblers.html). The basic idea is that it's a place notation that is infinitely expandable at each position. Pretty simple conceptually. | Which data type to use for ordinal? | [
"",
"sql",
"sql-server",
"database",
"data-structures",
""
] |
I want to change an audio file format into another. Specifically, I want to convert any audio file into 6khz, 16 bit, mono, PCM wav format.
How can I cope with this problem.
Thanks again in advance. | You can also do this using the open source C# audio library [NAudio](http://www.codeplex.com/naudio). Have a look at the NAudioDemo project for an example of passing WAV files through the ACM codecs installed on your machine to convert to another format. If your input file is not WAV or MP3, you will first need something that converts it to WAV though. | I would use the [BASS Library](http://www.un4seen.com). It has many possibilities to do format conversions using the built in encoding/decoding capabilities. It also has a .NET wrapper availabe. | Change Audio Format in C# | [
"",
"c#",
".net",
"audio",
""
] |
I have a query that `UNION`'s two somewhat similar datasets, but they both have some columns that are not present in the other (i.e., the columns have NULL values in the resulting `UNION`.)
The problem is, I need to `ORDER` the resulting data using those columns that only exist in one or the other set, to get the data in a friendly format for the software-side.
For example: **Table1** has fields `ID, Cat, Price`. **Table2** has fields `ID, Name, Abbrv`. The `ID` field is common between the two tables.
---
My query looks like something like this:
```
SELECT t1.ID, t1.Cat, t1.Price, NULL as Name, NULL as Abbrv FROM t1
UNION
SELECT t2.ID, NULL as Cat, NULL as Price, t2.Name, t2.Abbrv FROM t2
ORDER BY Price DESC, Abbrv ASC
```
The `ORDER BY` is where I'm stuck. The data looks like this:
```
100 Balls 1.53
200 Bubbles 1.24
100 RedBall 101RB
100 BlueBall 102BB
200 RedWand 201RW
200 BlueWand 202BW
```
...but I want it to look like this:
```
100 Balls 1.53
100 RedBall 101RB
100 BlueBall 102BB
200 Bubbles 1.24
200 RedWand 201RW
200 BlueWand 202BW
```
I'm hoping this can be done in T-SQL. | ```
Select ID, Cat, Price, Name, Abbrv
From
(SELECT t1.ID, t1.Cat, t1.Price, t1.Price AS SortPrice, NULL as Name, NULL as Abbrv
FROM t1
UNION
SELECT t2.ID, NULL as Cat, NULL as Price, t1.Price as SortPrice, t2.Name, t2.Abbrv
FROM t2
inner join t1 on t2.id = t1.id
) t3
ORDER BY SortPrice DESC, Abbrv ASC
```
Somehow you have to know the data in table 2 are linked to table 1 and share the price. Since the Null in abbrv will come first, there is no need to create a SortAbbrv column. | You should use UNION ALL instead of UNION to save the cost of duplicate checking.
```
SELECT *
FROM
(
SELECT t1.ID, t1.Cat, t1.Price, NULL as Name, NULL as Abbrv FROM t1
UNION ALL
SELECT t2.ID, NULL as Cat, NULL as Price, t2.Name, t2.Abbrv FROM t2
) as sub
ORDER BY
ID,
CASE WHEN Price is not null THEN 1 ELSE 2 END,
Price DESC,
CASE WHEN Abbrv is not null THEN 1 ELSE 2 END,
Abbrv ASC
``` | ORDER BY with a UNION of disparate datasets (T-SQL) | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"union",
""
] |
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, looping through and another list, and appending one list within another:
```
import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
```
So I either:
* I don't understand JSON Syntax
* I don't understand the Pythons JSON module(s)
* I'm using an inappropriate data type. | Python `lists` translate to JSON `arrays`. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a `dict`:
```
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
``` | I think you are simply exchanging *dumps* and *loads*.
```
>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
```
The first returns as a (JSON encoded) string its data argument:
```
>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
```
The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:
```
>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True
``` | Python JSON encoding | [
"",
"python",
"json",
"encoding",
"types",
"simplejson",
""
] |
How do I include a newline in an HTML tag attribute?
For example:
```
<a href="somepage.html" onclick="javascript: foo('This is a multiline string.
This is the part after the newline.')">some link</a>
```
---
**Edit**: Sorry, bad example, what if the tag happened to not be in javascript, say:
```
<sometag someattr="This is a multiline string.
This is the part after the newline." />
```
---
**Edit 2**: Turns out the newline in the string wasn't my problem, it was the javascript function I was calling. FWIW, "` `" can be used for newline in an HTML attribute. | From what I remember about the HTML standard, character entities work in attributes, so this *might* work:
```
<sometag someattr="This is a multiline string. This is the part after the newline." />
```
I'm not sure if the "newline" you want ought to be (\n) or (\r\n), and I'm not sure if browsers will interpret it the way you want.
Why do you need it? What specific problem are you trying to solve by adding a newline in an HTML tag attribute? | To include a multiline value, just continue the text of the html attribute on the next line in your editor e.g.
```
<input type="submit" value="hallo
hallo">
```
will put the second hallo under the first | How can I use a multiline value for an HTML tag attribute? (i.e. how do I escape newline?) | [
"",
"javascript",
"html",
"syntax",
"newline",
""
] |
Today while inside a client's production system, I found a SQL Server query that contained an unfamiliar syntax. In the below example, what does the `*=` operator do? I could not find any mention of it [on MSDN](http://msdn.microsoft.com/en-us/library/ms188074.aspx). The query does execute and return data. As far as anyone knows, this has been in the system since they were using SQL Server 2000, but they are now running 2005.
```
declare @nProduct int
declare @iPricingType int
declare @nMCC int
set @nProduct = 4
set @iPricingType = 2
set @nMCC = 230
--Build SQL for factor matrix
Select distinct
base.uiBase_Price_ID,
base.nNoteRate,
base.sDeliveryOpt,
IsNull(base.nPrice,0) as nPrice,
IsNull(base.nPrice,0) + Isnull(fact.nFactor,0) as nAdjPrice,
base.iProduct_ID,
fact.iPosition as fiPosition,
base.iPosition,
CONVERT(varchar(20), base.dtDate_Updated, 101) + ' ' + CONVERT(varchar(20), base.dtDate_Updated, 108) as 'dtDate_Updated',
fact.nFactor,
fact.nTreasFactor,
product.sProduct_txt ,
pfi.sPFI_Name,
mccprod.nServicing_Fee,
fact.nNoteRate as fNoteRate,
mcc.nLRA_Charge as nLRA
From
tbl_Base_Prices base, tbl_Factors fact, tbl_Product product, tbl_PFI pfi, tbl_MCC mcc, tbl_MCC_Product mccprod
Where
base.iProduct_ID = @nProduct
And base.iProduct_ID *= fact.iProduct_ID
And base.iPosition *= fact.iPosition
And base.nNoteRate *= fact.nNoteRate
And base.iPricing_Type = @iPricingType
And fact.iMCC_ID = @nMCC
And fact.iProduct_ID = @nProduct
And mcc.iMCC_ID = @nMCC
And mcc.iPFI_ID = pfi.iPFI_ID
And mccprod.iMCC_ID = @nMCC
And mccprod.iProduct_ID = @nProduct
And base.iProduct_ID = product.iProduct_ID
and fact.iPricing_Type= @iPricingType
Order By
base.nNoteRate, base.iPosition
``` | Remove this code immediately and replace with a left join. This code does not always interpret correctly (Sometimes SQL Server decides it is a cross join) even in SQL Server 2000 and thus can give incorrect results! Also it is deprecated for the future ([Using Outer Joins, SQL Server 2000 documentation](https://web.archive.org/web/20130907031446/https://technet.microsoft.com/en-us/library/aa213228(v=sql.80).aspx) archived from [the original](https://technet.microsoft.com/en-us/library/aa213228(v=sql.80).aspx)).
I'm going to add that in adjusting to left joins you should remove all of those other implicit joins as well. The implicit join syntax has been **obsolete** since 1992, there is no excuse for it still being in production code. And mixing implicit and explicit joins can give unexpected results.
--- | It is a left outer join, =\* is a right outer join.
E.g. the following are equal;
```
SELECT * FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = Table2.FK_ID
SELECT * FROM Table1, Table2 WHERE Table1.ID *= Table2.FK_ID
``` | SQL Server *= Operator? | [
"",
"sql",
"sql-server",
"operators",
""
] |
I need a tool which analyzes C++ sources and says what code isn't used. Size of sources is ~500mb | PC-Lint is good. If it needs to be free/open source your choices dwindle. Cppcheck is free, and will check for unused private functions. I don't think that it looks for things like uninstantiated classes like PC-Lint. | Once again, I'll throw [AQTime](http://www.automatedqa.com) into the discussion. Has static code analysis for most, if not all, of the supported languages. I didn't really go into that part though, I mainly used the dynamic profilers (memory, performance and so on). | Tool for analyzing C++ sources (MSVC) | [
"",
"c++",
"code-analysis",
"visual-c++",
""
] |
I am running a simulation with a lot if bunch of initial memory allocations per object. The simulation has to run as quickly as possible, but the speed of allocation is not important. I am not concerned with deallocation.
Ideally, the allocator will place everything in a contiguous block of memory. (I think this is sometimes called an arena?)
I am not able to use a flattened vector because the allocated objects are polymorphic.
What are my options? | Just make your own.
See an old question of mine to see how you can start:
[Improvements for this C++ stack allocator?](https://stackoverflow.com/questions/771458/improvements-for-this-c-stack-allocator) | Since you don't care about de-allocation you can use a linear allocator. Allocate a huge amount of memory up front and store a pointer to the start. malloc(x) moves the allocation pointer forward by x bytes and returns the old value of the pointer, delete(x) is stubbed out. As mentioned here, another poster already has [an implimentation](https://stackoverflow.com/questions/771458/improvements-for-this-c-stack-allocator)
Allocations are packed as closely as possible, allocations are incredibly fast and memory is returned in the order allocated. When your simulation is done, you just reset the allocator's pointer to the start of memory and clear any pointers you have from outside the allocator to objects inside of it.
Pool allocators are a great choice if you want to delete objects, faster than a heap but won't pack your data into memory as close and aren't quite as fast. Use boost:pool for those. This is a great choice for games if you have x bytes to store say - a level - and you are willing to throw the whole lot away at the same time.
As an aside, if you are interested in memory performance, see [What Every Programmer Should Know About Memory-PDF](http://people.redhat.com/drepper/cpumemory.pdf). It covers things like locality of reference and its effect on performance. Specifically, you might want to create a pool for each type of object that is used together, or declare your objects as a struct of arrays rather than a array of structs | Are there any good custom allocators for C++ that maximize locality of reference? | [
"",
"c++",
"stl",
"memory-management",
""
] |
I have the following struct in C++:
```
struct routing_entry {
unsigned long destSeq; // 32 bits
unsigned long nextHop // 32 bits
unsigned char hopCount; // 8 bits
};
```
And I have the following function:
```
routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID ) {
routing_entry route;
if ( routing_table.find(destinationID) != routing_table.end() )
route = routing_table[destinationID];
return route; // will be "empty" if not found
}
```
"routing\_table" is a stl::map defined as follows:
```
map< unsigned long int, routing_entry > routing_table;
```
My question now is, when using the consultTable function, I want to check that the return value is actually initialized, some how like in Java pseudocode (because I come from the Java camp):
```
Route consultTable(int id) {
Route r = table.find(id);
return r;
}
```
then checking if r == null | There are a few problems here. The most urgent may be what happens when the destination ID is not found. Since you have no constructor on the `routing_entry` and you are not default initialising, it will have undefined values.
```
// the data inside route is undefined at this point
routing_entry route;
```
One way to handle this is to default initialise. This works by instructing the compiler to fill the structure with zeros. This is kind of a trick borrowed from C but it works well here.
```
routing_entry route={0};
```
You mention you are coming from Java, unlike in Java, structure and class members are not 0 initialised, so you should really handle that somehow. Another way is to define a constructor:
```
struct routing_entry
{
routing_entry()
: destSeq(0)
, nextHop(0)
, hopCount(0)
{ }
unsigned long destSeq; // 32 bits
unsigned long nextHop; // 32 bits
unsigned char hopCount; // 8 bits
};
```
Also note that in C++, the size of the integer and char members is not defined in bits. The char type is 1 byte (but a byte is a not defined, but usually 8 bits). The longs are usually 4 bytes these days but can be some other value.
Moving on to your `consultTable`, with the initialisation fixed:
```
routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID )
{
routing_entry route={0};
if ( routing_table.find(destinationID) != routing_table.end() )
route = routing_table[destinationID];
return route; // will be "empty" if not found
}
```
One way to tell might be to check if the structure is still zeroed out. I prefer to refactor to have the function return `bool` to indicate success. Additionally, I always typedef STL structures for simplicity, so I'll do that here:
```
typedef map< unsigned long int, routing_entry > RoutingTable;
RoutingTable routing_table;
```
Then we pass in a reference to the routing entry to populate. This can be more efficient for the compiler, but probably that is irrelevant here - anyway this is just one method.
```
bool Cnode_router_aodv::consultTable(unsigned int destinationID, routing_entry &entry)
{
RoutingTable::const_iterator iter=routing_table.find(destinationID);
if (iter==routing_table.end())
return false;
entry=iter->second;
return true;
}
```
You would call it like this:
```
routing_entry entry={0};
if (consultTable(id, entry))
{
// do something with entry
}
``` | The best way I've found for this is to use [boost::optional](http://www.boost.org/doc/libs/1_39_0/libs/optional/doc/html/index.html), which is designed to solve exactly this issue.
Your function would look something like this:-
```
boost::optional<routing_entry> consultTable(unsigned int destinationID )
{
if ( routing_table.find(destinationID) != routing_table.end() )
return routing_table[destinationID];
else
return boost::optional<routing_entry>()
}
```
And your calling code looks like
```
boost::optional<routing_entry> route = consultTable(42);
if (route)
doSomethingWith(route.get())
else
report("consultTable failed to locate 42");
```
Generally, the use of "out" parameters (passing a pointer - or reference - to an object which is then "filled in" by the called function is frowned on in C++. The approach that everything "returned" by a function is contained in the return value, and that no function parameters are modified can make code more readable and maintainable in the long term. | Returning struct from a function, how can I check that it is initialized? | [
"",
"c++",
"null",
""
] |
I am trying select multiple conditional summaries into a single table result on a DB2 based database.
Example:
```
SELECT COUNT(FOO) FROM T1 WHERE T1.A=1 AS A_COUNT,
SELECT COUNT(FOO) FROM T1 WHERE T1.B=2 AS B_COUNT
Ext...
```
Any help is appreciated. | This will count the occurrence of each condition:
```
select sum(case when t1.a = 1 then 1 else 0 end) as A_COUNT
, sum(case when t1.b = 2 then 1 else 0 end) as B_COUNT
from t1
where t1.a = 1
or t1.b = 2
``` | ```
select count(case when t1.a = 1 then foo else null end) as A_COUNT
, count(case when t1.b = 2 then foo else null end) as B_COUNT
from t1
where t1.a = 1
or t1.b = 2
```
Where clause is optional strictly speaking but may assist performance. Also "else null" is implicit when the else clause is omitted so you can safely leave that off as well. | SQL (DB2) Return multiple conditional counts in a single query | [
"",
"sql",
"db2",
""
] |
Is there a way to set the value of a file input (`<input type="file" />`) or is that all blocked for security? I'm trying to use google gears' openFiles to make a simple multi-uploader.
> **Note:**
>
> The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.
>
> See the answer in this question for details as well as a demo:
> [How to set file input value programatically (i.e.: when drag-dropping files)?](https://stackoverflow.com/q/47515232/584192) | It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.
However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.
Perhaps have a look at <http://www.plupload.com/> - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c. | I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image. | Dynamically set value of a file input | [
"",
"javascript",
"html",
"dom",
"google-gears",
""
] |
In our product we have a generic search engine, and trying to optimze the search performance. A lot of the tables used in the queries allow null values. Should we redesign our table to disallow null values for optimization or not?
Our product runs on both `Oracle` and `MS SQL Server`. | In `Oracle`, `NULL` values are not indexed, i. e. this query:
```
SELECT *
FROM table
WHERE column IS NULL
```
will always use full table scan since index doesn't cover the values you need.
More than that, this query:
```
SELECT column
FROM table
ORDER BY
column
```
will also use full table scan and sort for same reason.
If your values don't intrinsically allow `NULL`'s, then mark the column as `NOT NULL`. | Short answer: yes, conditionally!
The main issue with null values and performance is to do with forward lookups.
If you insert a row into a table, with null values, it's placed in the natural page that it belongs to. Any query looking for that record will find it in the appropriate place. Easy so far....
...but let's say the page fills up, and now that row is cuddled in amongst the other rows. Still going well...
...until the row is updated, and the null value now contains something. The row's size has increased beyond the space available to it, so the DB engine has to do something about it.
The fastest thing for the server to do is to move the row *off* that page into another, and to replace the row's entry with a forward pointer. Unfortunately, this requires an extra lookup when a query is performed: one to find the natural location of the row, and one to find its current location.
So, the short answer to your question is yes, making those fields non-nullable will help search performance. This is especially true if it often happens that the null fields in records you search on are updated to non-null.
Of course, there are other penalties (notably I/O, although to a tiny extent index depth) associated with larger datasets, and then you have application issues with disallowing nulls in fields that conceptually require them, but hey, that's another problem :) | How do NULL values affect performance in a database search? | [
"",
"sql",
"database",
"oracle",
"database-performance",
"query-performance",
""
] |
I have a string in JavaScript and it includes an `a` tag with an `href`. I want to remove all links **and** the text. I know how to just remove the link and leave the inner text but I want to remove the link completely.
For example:
```
var s = "check this out <a href='http://www.google.com'>Click me</a>. cool, huh?";
```
I would like to use a regex so I'm left with:
```
s = "check this out. cool, huh?";
``` | This will strip out everything between `<a` and `/a>`:
```
mystr = "check this out <a href='http://www.google.com'>Click me</a>. cool, huh?";
alert(mystr.replace(/<a\b[^>]*>(.*?)<\/a>/i,""));
```
It's not really foolproof, but maybe it'll do the trick for your purpose... | Just to clarify, in order to strip link tags and leave everything between them untouched, it is a two step process - remove the opening tag, then remove the closing tag.
```
txt.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i, "");
```
Working sample:
```
<script>
function stripLink(txt) {
return txt.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i, "");
}
</script>
<p id="strip">
<a href="#">
<em>Here's the text!</em>
</a>
</p>
<p>
<input value="Strip" type="button" onclick="alert(stripLink(document.getElementById('strip').innerHTML))">
</p>
``` | Regex in Javascript to remove links | [
"",
"javascript",
"regex",
""
] |
Is there an [Elmah](https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/logging-error-details-with-elmah-cs) equivalent for PHP in general, Symfony in particular? | Symfony comes with a logging framework that can log to file or any other backend you care to give it. From my understanding of Elmah this is about as close as you can get - there's nothing with all the features available and integrated with frameworks such as Symfony.
Please [see this chapter](http://www.symfony-project.org/book/1_2/16-Application-Management-Tools) in the Symfony book for more information on Symfony's logging capabilities. | For future reference, [elmah.io](https://elmah.io/) can be used for PHP as well. We focus primarily on .NET, but some of our users use it for PHP as well. Take a look at the following example to start logging errors from PHP to elmah.io: <https://github.com/elmahio/other-language-examples/blob/master/PHP/Logger.php>
*To make it clear, I'm the founder of elmah.io and elmah.io isn't affiliated with ELMAH in any way. We share the name, but the services are very different.* | Elmah For other PHP | [
"",
"php",
"symfony1",
"elmah",
"error-logging",
""
] |
I tried this earlier today:
```
public interface IFoo
{
IEnumerable<int> GetItems_A( ref int somethingElse );
IEnumerable<int> GetItems_B( ref int somethingElse );
}
public class Bar : IFoo
{
public IEnumerable<int> GetItems_A( ref int somethingElse )
{
// Ok...
}
public IEnumerable<int> GetItems_B( ref int somethingElse )
{
yield return 7; // CS1623: Iterators cannot have ref or out parameters
}
}
```
What's the rationale behind this? | C# iterators are state machines internally. Every time you `yield return` something, the place where you left off should be saved along with the state of local variables so that you could get back and continue from there.
To hold this state, C# compiler creates a class to hold local variables and the place it should continue from. It's not possible to have a `ref` or `out` value as a field in a class. Consequently, if you were allowed to declare a parameter as `ref` or `out`, there would be no way to keep the complete snapshot of the function at the time we had left off.
**EDIT:** Technically, not all methods that return `IEnumerable<T>` are considered iterators. Just those that use `yield` to produce a sequence directly are considered iterators. Therefore, while the splitting the iterator into two methods is a nice and common workaround, it doesn't contradict with what I just said. The outer method (that doesn't use `yield` directly) is **not** considered an iterator. | If you want to return both an iterator and an int from your method, a workaround is this:
```
public class Bar : IFoo
{
public IEnumerable<int> GetItems( ref int somethingElse )
{
somethingElse = 42;
return GetItemsCore();
}
private IEnumerable<int> GetItemsCore();
{
yield return 7;
}
}
```
You should note that none of the code inside an iterator method (i.e. basically a method that contains `yield return` or `yield break`) is executed until the `MoveNext()` method in the Enumerator is called. So if you were able to use `out` or `ref` in your iterator method, you would get surprising behavior like this:
```
// This will not compile:
public IEnumerable<int> GetItems( ref int somethingElse )
{
somethingElse = 42;
yield return 7;
}
// ...
int somethingElse = 0;
IEnumerable<int> items = GetItems( ref somethingElse );
// at this point somethingElse would still be 0
items.GetEnumerator().MoveNext();
// but now the assignment would be executed and somethingElse would be 42
```
This is a common pitfall, a related issue is this:
```
public IEnumerable<int> GetItems( object mayNotBeNull ){
if( mayNotBeNull == null )
throw new NullPointerException();
yield return 7;
}
// ...
IEnumerable<int> items = GetItems( null ); // <- This does not throw
items.GetEnumerators().MoveNext(); // <- But this does
```
So a good pattern is to separate iterator methods into two parts: one to execute immediately and one that contains the code that should be lazily executed.
```
public IEnumerable<int> GetItems( object mayNotBeNull ){
if( mayNotBeNull == null )
throw new NullPointerException();
// other quick checks
return GetItemsCore( mayNotBeNull );
}
private IEnumerable<int> GetItemsCore( object mayNotBeNull ){
SlowRunningMethod();
CallToDatabase();
// etc
yield return 7;
}
// ...
IEnumerable<int> items = GetItems( null ); // <- Now this will throw
```
**EDIT:**
If you really want the behavior where moving the iterator would modify the `ref`-parameter, you could do something like this:
```
public static IEnumerable<int> GetItems( Action<int> setter, Func<int> getter )
{
setter(42);
yield return 7;
}
//...
int local = 0;
IEnumerable<int> items = GetItems((x)=>{local = x;}, ()=>local);
Console.WriteLine(local); // 0
items.GetEnumerator().MoveNext();
Console.WriteLine(local); // 42
``` | Why can't iterator methods take either 'ref' or 'out' parameters? | [
"",
"c#",
"parameters",
"ref",
"out",
""
] |
In C#, is there any difference between using `System.Object` in code rather than just `object`, or `System.String` rather than `string` and so on? Or is it just a matter of style?
Is there a reason why one form is preferrable to the other? | `string` is an alias for `global::System.String`. It's simply syntactic sugar. The two are *exactly* interchangable in almost all cases, and there'll be no difference in the compiled code.
Personally I use the aliases for variable names etc, but I use the CLR type names for names in APIs, for example:
```
public int ReadInt32() // Good, language-neutral
public int ReadInt() // Bad, assumes C# meaning of "int"
```
(Note that the return type isn't really a name - it's encoded as a type in the metadata, so there's no confusion there.)
The only places I know of where one can be used and the other can't (that I'm aware of) are:
* `nameof` prohibits the use of aliases
* When specifying an enum base underlying type, *only* the aliases can be used | The *object* type is an alias for *System.Object*. The *object* type is used and shown as a keyword. I think it has something to do with legacy, but that's just a wild guess.
Have a look at this [MSDN](http://msdn.microsoft.com/en-us/library/9kkx3h3c.aspx) page for all details.
I prefer the use of the lowercased versions, but for no special reasons. Just because the syntax highlighting is different on these "basic" types and I don't have to use the shift key when typing... | c#: difference between "System.Object" and "object" | [
"",
"c#",
"coding-style",
""
] |
I have written regexes for recognizing float and int but they don't seem to work (code below).
```
{
string sumstring = "12.098";
Regex flt = new Regex(@" ^[0-9]*(\.[0-9]*)");
Regex ent = new Regex("^[0-9]+");
if (d_type.IsMatch(sumstring))
{
Console.WriteLine(sumstring + " " + "dtype");
}
Match m = ent.Match(sumstring);
if (m.Success)
{
Console.WriteLine("int");
}
else if (flt.IsMatch(sumstring))
{
Console.WriteLine("float");
}
}
```
Where is the mistake? | First, I don't think regular expressions are really the best tool for this job. I would simply use the `Double.TryParse()` and `Int32.TryParse()` functions.
Second, you're missing a **whole lot** of test cases with your regular expressions:
* Integer
+ 5 (covered)
+ +5 (not covered)
+ -5 (not covered)
* Double
+ 5.0 (covered)
+ +5.0 (not covered)
+ -5.0 (not covered)
+ 5.0E5 (not covered)
+ 5.0E+5 (not covered)
+ 5.0E-5 (not covered)
+ +5.0E5 (not covered)
+ +5.0E+5 (not covered)
+ +5.0E-5 (not covered)
+ -5.0E5 (not covered)
+ -5.0E+5 (not covered)
+ -5.0E-5 (not covered)
* Edge Cases
+ 2^32 + 1 (should be recognized as Double even though it looks like Integer)
All of these (except maybe the edge case) would be immediately covered by using the library instead of hand-rolling a regex. | You're trying your tests in the wrong order -- switch them, or (\*) put a $ at the end of your RE patterns, to ensure they match all the way to the end.
(\*) depends on what you're trying to do, exactly: match strings that *start* with the representation of an integer or float, or, only strings that are *entirely* composed of such a representation? | Regex can't differentiate between float and int types | [
"",
"c#",
".net",
"regex",
""
] |
There exist other ways of linking to JS, apart from this (the usual)..
```
<script src="myscript.js" type="text/javascript"></script>
```
...that utilize other quote types:
```
<script src="myscript.js" type="text/javascript"></script>
```
Are these widely supported in modern browsers, and older browsers in use, such as IE6? Basically is it safe to use this method, just as you would use the regular double-quote method?
---
**Edit:** The [HTML4 spec](http://www.w3.org/TR/html4/intro/sgmltut.html) seems to allow it, but is it well supported in practical reality?
```
3.2.2 Attributes
Authors may also use numeric character references to represent
double quotes (") and single quotes (').
For double quotes authors can also use the
character entity reference ".
``` | Using " instead of " is simply **wrong**, it doesn't have the same meaning within the SGML and XML specifications. Argument values of elements should use either single (') or double quotes ("). In the old SGML specification this element
```
<foo bar="quux" />
```
could be read as an element with the name *foo*, and attribute named *bar* with the value *"quux"*. However, the standard defines that unquoted attribute values should not include escaped characters. And this element
```
<foo bar="quux" />
```
should be read as an element with the name *foo*, and attribute named *bar* with the value *quux* without the quotes. This is because in SGML the quotes are optional, and everything up to the next space will be used as the value for the attribute.
XML requires quotes. | There is a difference between an attribute value delimiter and a quote or double quote character.
You have to use a literal " or ' to delimit attribute values (except where [delimiters are optional](http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2)). In this case, the squence of bytes means "attribute value delimited" not "(double) quote mark"
The character references can be used to represent a (double) quote mark but is a more complicated and inefficient way compared to using a literal so should only be used when the literal is not available (i.e. when it would be an attribute value delimiter because you are inside an an attribute value where the opening delimiter was that character). | Do browsers widely support numeric quotes in attributes? | [
"",
"javascript",
"html",
"tags",
""
] |
I have the following situation.
I programmatically create a temporary workspace using TFS. I then map it to a spot on my local machine so that I can be able to checkin/checkout files. Since the mapping to the local drive through the workspace is what creates the file structure. What is the way to delete the mapping through the workspace object that I created?
Ive tried the following.
```
WorkingFolder tempFolder = workspace.getWorkingFolderForServerItem(serverItem);
workspace.DeleteMapping(tempFolder);
```
Stepping through in debug mode, the tempFolder Object I make holds the correct local mapping as well as the correct server mapping. I cant seem to get it to delete the local content though. Is this mostly correct or do you suggest something completely different? | In TFS, the trick to deleting files locally and telling the server that you do not have them anymore is to get the files at Changeset 1 (i.e. before they existed). In code that would be something like:
```
workspace.Get(
new string[] {"C:\\LocalPath"},
new ChangesetVersionSpec(1),
RecursionType.Full,
GetOptions.None);
```
See the following blog post where I explain this concept some more:
* [TFS Top Tip #11 - Removing source control files from your local file system](http://www.woodwardweb.com/tfs_top_tip/tfs_top_tip_11.html)
That said, if the workspace is just temporary and you do not need it anymore then doing a workspace.Delete() followed by a traditional file delete is a perfectly good way of doing things. If you were trying to keep the workspace around you could get into trouble though (because TFS thinks those files are still in your local workspace unless you tell it that they are not) | > Since the mapping to the local drive through the workspace is what creates the file structure.
I think you have this wrong. The local folders (and files) are created only when you perform the get after the mapping is created (whether from the Team Explorer GUI, "`tf.exe get`", or otherwise).
After deleting the workspace mapping, you will need to create code to delete the files and folders yourself. | How to remove local tfs content programmatically? | [
"",
"c#",
"tfs",
""
] |
Is there any web content editor (like FCKEditor or WMD editor) that allows page layouts (images, tables etc.) like MS Word? | Both FCK and TinyMCE allow for tables and other layout elements (overall FCK having the better implementation of added elements), and both will allow images that you have a url for.
There is a plug-in for Tiny that allows image uploading, but it is heavy and I think proprietary.
Neither of the above is an inline editor, if that's what you want. Probably the best in that direction currently is TiddlyWiki.
I have been working on my own Mootools based implementation that will allow any webpage to be edited, and has image uploading et al built in. It is currently in Beta, but I can send you a link if that's your goal. | Not quite sure what exactly you ask for regarding page layouts, but telerik has a very feature rich html editor. It's a commercial product though.
Take a look at <http://demos.telerik.com/aspnet-ajax/editor/examples/default/defaultcs.aspx> | Web Content Editor | [
"",
"c#",
"asp.net",
"web-content",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.