qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
356,294 | <p>Say you have a class who's job it is to connect to a remote server. I want to abstract this class to provide two versions, one that connects through UDP and the other through TCP. I want to build the leanest runtime code possible and instead of using polymorphism I am considering templates. Here is what I'm envisioning but I'm not sure it's the best way of doing this:</p>
<pre><code>class udp {};
class tcp {};
template<class T,typename X>
class service
{
private:
// Make this private so this non specialized version can't be used
service();
};
template<typename X>
class service<udp, X>
{
private:
udp _udp;
X _x;
};
template<typename X>
class service<tcp, X>
{
private:
tcp _tcp;
X _x;
};
</code></pre>
<p>So the end benefit is that the genericness of T is still available, but the very different code required to setup a UDP or TCP connection has been specialized. I suppose you could put it both into one class, or provide another class that adheres to some pure virtual interface for setting up the network connection, like IConnectionManager.</p>
<p>But this does leave the problem of the code for the generic T now having to be written in and maintained in both specialized versions, where they are ultimately the same. How best to address this? I have a feeling I am going about this all wrong.</p>
| [
{
"answer_id": 356318,
"author": "Edouard A.",
"author_id": 41363,
"author_profile": "https://Stackoverflow.com/users/41363",
"pm_score": 2,
"selected": false,
"text": "template <typename Underlying>\nclass Transmit\n{\npublic:\n void send(...)\n {\n _U.send(...)\n };\n\nprivate:\n Underlying _U;\n};\n\nclass Tcp\n{\npublic:\n void send(...) {};\n};\n\nclass Udp\n{\npublic:\n void send(...) {};\n};\n"
},
{
"answer_id": 356576,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "template<typename Transport>\nclass service : Transport {\npublic:\n typedef Transport transport_type;\n\n // common code\n void do_something() { \n this->send(....);\n }\n};\n\nclass tcp {\npublic:\n void send(....) {\n\n }\n};\n\nclass udp {\npublic:\n void send(....) {\n\n }\n};\n\ntypedef service<tcp> service_tcp;\ntypedef service<udp> service_udp;\n template<template<typename Service> class Transport>\nclass service : Transport<service> {\n\n // since we derive privately, make the transport layer a friend of us, \n // so that it can cast its this pointer down to us. \n friend class Transport<service>;\n\npublic:\n typedef Transport<service> transport_type;\n\n // common code\n void do_something() { \n this->send(....);\n }\n};\n\ntemplate<typename Service>\nclass tcp {\npublic:\n void send(....) {\n\n }\n};\n\ntemplate<typename Service>\nclass udp {\npublic:\n void send(....) {\n\n }\n};\n\ntypedef service<tcp> service_tcp;\ntypedef service<udp> service_udp;\n template class service<tcp>;\ntemplate class service<udp>;\n"
},
{
"answer_id": 356930,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "class udp {/*Interface Plop*/static void plop(Message&);};\nclass tcp {/*Interface Plop*/static void plop(Message&);};\ntemplate<typename T>\nclass Service\n{\n public:\n void doPlop(Message& m) { T::plop(m);}\n // Do not actually need to store an object if you make the methods static.\n // Alternatively:\n public:\n void doPlop(Message& m) { protocol.plop(m);}\n private:\n T protocol;\n};\n class Plop{virtual void plop(Message&) = 0;} // Destruct or omitted for brevity\nclass upd:public Plop {/*Interface Plop*/void plop(Message&);};\nclass tcp:public Plop {/*Interface Plop*/void plop(Message&);};\nclass Service\n{\n public:\n Service(Plop& p):protocol(p) {};\n void doPlop(Message& m) { protocol.plop(m);}\n private:\n Plop& protocol;\n};\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44996/"
] |
356,297 | <p>I've read a lot of comments mention in passing that the BlackBerry threading model deviates from the Java standard and can cause issues, but no amount of googling has enlightened me on what this means exactly.</p>
<p>I've been developing a fairly large business application for the BlackBerry and, although I don't really have any previous experience with Java multi-threaded applications, haven't come across any issue that we've been able to blame on threading, other than what we caused ourselves.</p>
<p>Can someone describe exactly how the BlackBerry threading model is different, and how I as a developer should take that into account? Obviously any links on the topic would also be great.</p>
| [
{
"answer_id": 807729,
"author": "kozen",
"author_id": 98649,
"author_profile": "https://Stackoverflow.com/users/98649",
"pm_score": 4,
"selected": false,
"text": "LabelField.setText(\"foo\"); UiApplication.getUiApplication().invokeLater(new Runnable(){\n public void run(){\n myLabelField.setText(\"foo\");\n myLabelField.setDirty(true);\n }\n});\n new Thread(){\n public void run(){\n HttpConnection hc = \n (HttpConnection)Connector.open(\"http://www.stackoverflow.com\");\n }\n}.start();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
] |
356,298 | <p>I am using GWT (Google Web Toolkit) 1.5.3 et GXT (ExtJS) 1.2
I just want to create a simple form with some radio buttons generated after a RPC call, to get some values</p>
<p>Code:</p>
<pre><code>final FormPanel simple = new FormPanel();
simple.setFrame(true);
simple.setWidth(350);
simple.setHeaderVisible(false);
DateField date = new DateField();
date.setFieldLabel("Date");
simple.add(date);
ListFluxServiceAsync service = (ListFluxServiceAsync)
GWT.create(ListFluxService.class);
ServiceDefTarget target = (ServiceDefTarget)service;
String url = GWT.getModuleBaseURL() + "flux.rpc";
target.setServiceEntryPoint(url);
final RadioGroup radioGroup = new RadioGroup("RadioGroup");
radioGroup.setFieldLabel("Flux");
radioGroup.setOrientation(Orientation.VERTICAL);
service.getAllFlux(new AsyncCallback<List<FluxModelData>>(){
public void onFailure(Throwable caught) {
GWT.log("flux.rpx::onFailure", caught);
MessageBox.alert("what?", "onFailure :" + caught.getMessage(), null);
}
public void onSuccess(List<FluxModelData> result) {
Iterator<FluxModelData> it = result.iterator();
while ( it.hasNext() ){
FluxModelData fmd = it.next();
Radio radio = new Radio();
radio.setName("flux");
radio.setValue(true);
//radio.setRawValue("my very long value");
radio.setBoxLabel(fmd.getDescription());
radioGroup.add(radio);
}
simple.add(radioGroup);
simple.layout(); //we need it to show the radio button
}
});
simple.setButtonAlign(HorizontalAlignment.CENTER);
Button button = new Button("Récupérer");
button.addSelectionListener(new SelectionListener<ButtonEvent>(){
@Override
public void componentSelected(ButtonEvent ce) {
MessageBox.alert("what?", radioGroup.getValue().getRawValue() , null);
}});
simple.addButton(button);
RootPanel.get().add(simple);
</code></pre>
<p>My problem is I can't set/get radio button value.
If I try the setRawValue("xxxxxxx"), I will get some null errors, while setting setValue(boolean) is working but I was expecting getting the radio value and not the label value.</p>
<p>Any Idea?</p>
| [
{
"answer_id": 1687944,
"author": "user204877",
"author_id": 204877,
"author_profile": "https://Stackoverflow.com/users/204877",
"pm_score": 0,
"selected": false,
"text": "radio.setAttributeValue()"
},
{
"answer_id": 5900218,
"author": "juanm",
"author_id": 740231,
"author_profile": "https://Stackoverflow.com/users/740231",
"pm_score": 2,
"selected": false,
"text": "Radio radio = new Radio(); \nradio.setBoxLabel(\"Si\"); \nradio.setValue(true);\nradio.setValueAttribute(\"true\");\n\nRadio radio2 = new Radio(); \nradio2.setBoxLabel(\"No\");\nradio2.setValueAttribute(\"false\");\n\nRadioGroup radioGroup = new RadioGroup(); \nradioGroup.setFieldLabel(\"Afecto\"); \nradioGroup.add(radio); \nradioGroup.add(radio2);\n Boolean b = Boolean.parseBoolean(radioGroup.getValue().getValueAttribute());\n"
},
{
"answer_id": 5987214,
"author": "kiran vennampelli",
"author_id": 751760,
"author_profile": "https://Stackoverflow.com/users/751760",
"pm_score": 1,
"selected": false,
"text": "public class ExtRadioButton extends RadioButton {\n public ExtRadioButton(String name, String label) {\n super(name, label);\n // TODO Auto-generated constructor stub\n }\n\n public void setValue(String value)\n {\n Element span = getElement();\n Element input = DOM.getChild(span,0);\n DOM.setElementAttribute(input,\"value\",value);\n }\n\n}\n"
},
{
"answer_id": 6276372,
"author": "brakebg",
"author_id": 767929,
"author_profile": "https://Stackoverflow.com/users/767929",
"pm_score": 0,
"selected": false,
"text": " Radio radio1 = new Radio();\n.............\n Radio radio2 = new Radio();\n.............\n\nin order to get value you can do as follow\n\nString value = (radio1.getValue()) ? radio1.getText() : radio2.getText(); \n"
},
{
"answer_id": 10652726,
"author": "Adam Davies",
"author_id": 1082500,
"author_profile": "https://Stackoverflow.com/users/1082500",
"pm_score": 0,
"selected": false,
"text": "radio.setValueAttribute(String) radioGroup.addListener(Events.Change, new Listener<BaseEvent>() {\n @Override\n public void handleEvent(BaseEvent be) \n {\n final RadioGroup radioGroup = (RadioGroup)be.getSource();\n\n final Radio clickedRadioBtn = radioGroup.getValue();\n\n final String valueAttribute = clickedRadioBtn.getValueAttribute(); // Correct !!!\n\n }\n});\n"
},
{
"answer_id": 11502889,
"author": "swamy",
"author_id": 1211000,
"author_profile": "https://Stackoverflow.com/users/1211000",
"pm_score": 0,
"selected": false,
"text": " Radio includeButton = new Radio();\n Radio excludeButton = new Radio();\n RadioGroup radioGroup = new RadioGroup();\n\n\n\n\n radioGroup.add(includeButton);\n radioGroup.add(excludeButton);\n\n includeButton.setvalue(true)//false\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18714/"
] |
356,321 | <p>I'm about to be forced to write a script to download some number of files under Windows XP. The machines the script will be run at are all behind a proxy, and the proxy settings are entered into the IE configuration.</p>
<p>What came to my mind was either to somehow call IE from the command line, and using its configuration download files I'd need. Is it even possible using some shell-techniques? </p>
<p>Other option would be to use <code>wget</code> under Win, but I'd need to pass the proxy-settings to it. How to recover those settings from IE configuration?</p>
| [
{
"answer_id": 1687944,
"author": "user204877",
"author_id": 204877,
"author_profile": "https://Stackoverflow.com/users/204877",
"pm_score": 0,
"selected": false,
"text": "radio.setAttributeValue()"
},
{
"answer_id": 5900218,
"author": "juanm",
"author_id": 740231,
"author_profile": "https://Stackoverflow.com/users/740231",
"pm_score": 2,
"selected": false,
"text": "Radio radio = new Radio(); \nradio.setBoxLabel(\"Si\"); \nradio.setValue(true);\nradio.setValueAttribute(\"true\");\n\nRadio radio2 = new Radio(); \nradio2.setBoxLabel(\"No\");\nradio2.setValueAttribute(\"false\");\n\nRadioGroup radioGroup = new RadioGroup(); \nradioGroup.setFieldLabel(\"Afecto\"); \nradioGroup.add(radio); \nradioGroup.add(radio2);\n Boolean b = Boolean.parseBoolean(radioGroup.getValue().getValueAttribute());\n"
},
{
"answer_id": 5987214,
"author": "kiran vennampelli",
"author_id": 751760,
"author_profile": "https://Stackoverflow.com/users/751760",
"pm_score": 1,
"selected": false,
"text": "public class ExtRadioButton extends RadioButton {\n public ExtRadioButton(String name, String label) {\n super(name, label);\n // TODO Auto-generated constructor stub\n }\n\n public void setValue(String value)\n {\n Element span = getElement();\n Element input = DOM.getChild(span,0);\n DOM.setElementAttribute(input,\"value\",value);\n }\n\n}\n"
},
{
"answer_id": 6276372,
"author": "brakebg",
"author_id": 767929,
"author_profile": "https://Stackoverflow.com/users/767929",
"pm_score": 0,
"selected": false,
"text": " Radio radio1 = new Radio();\n.............\n Radio radio2 = new Radio();\n.............\n\nin order to get value you can do as follow\n\nString value = (radio1.getValue()) ? radio1.getText() : radio2.getText(); \n"
},
{
"answer_id": 10652726,
"author": "Adam Davies",
"author_id": 1082500,
"author_profile": "https://Stackoverflow.com/users/1082500",
"pm_score": 0,
"selected": false,
"text": "radio.setValueAttribute(String) radioGroup.addListener(Events.Change, new Listener<BaseEvent>() {\n @Override\n public void handleEvent(BaseEvent be) \n {\n final RadioGroup radioGroup = (RadioGroup)be.getSource();\n\n final Radio clickedRadioBtn = radioGroup.getValue();\n\n final String valueAttribute = clickedRadioBtn.getValueAttribute(); // Correct !!!\n\n }\n});\n"
},
{
"answer_id": 11502889,
"author": "swamy",
"author_id": 1211000,
"author_profile": "https://Stackoverflow.com/users/1211000",
"pm_score": 0,
"selected": false,
"text": " Radio includeButton = new Radio();\n Radio excludeButton = new Radio();\n RadioGroup radioGroup = new RadioGroup();\n\n\n\n\n radioGroup.add(includeButton);\n radioGroup.add(excludeButton);\n\n includeButton.setvalue(true)//false\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
356,323 | <p>I want to add all the files in the current directory to git:</p>
<pre><code>git add .
error: open(".mysql_history"): Permission denied
fatal: unable to index file .mysql_history
</code></pre>
<p>That's fine. That file happens to be in this directory and owned by root. I want to add all <em>other</em> files. Is there a way to do that without having to manually add each file by hand?</p>
<p>I know that I could add the file to exclude or .gitignore, but I'd like to have it just ignore things based on permissions (there's a good chance other files like this will end up in the directory, and adding them to .gitignore all the time is a pain).</p>
| [
{
"answer_id": 356333,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 2,
"selected": false,
"text": ".mysql_history .gitignore .git/info/exclude .gitignore .gitignore .git/info/exclude .mysql_history git-add"
},
{
"answer_id": 359696,
"author": "matli",
"author_id": 23896,
"author_profile": "https://Stackoverflow.com/users/23896",
"pm_score": 7,
"selected": true,
"text": "git add --ignore-errors ."
},
{
"answer_id": 10802253,
"author": "Alexx Roche",
"author_id": 1153645,
"author_profile": "https://Stackoverflow.com/users/1153645",
"pm_score": 2,
"selected": false,
"text": "sudo chown $(whoami): .git/objects/ -R; git add --ignore-errors .\n"
},
{
"answer_id": 47272125,
"author": "InsParbo",
"author_id": 2724286,
"author_profile": "https://Stackoverflow.com/users/2724286",
"pm_score": 2,
"selected": false,
"text": "git add --ignore-errors --force .\n"
},
{
"answer_id": 51949846,
"author": "Benjamin Lucidarme",
"author_id": 6365968,
"author_profile": "https://Stackoverflow.com/users/6365968",
"pm_score": 3,
"selected": false,
"text": "git add ."
},
{
"answer_id": 59606710,
"author": "shaza",
"author_id": 8140922,
"author_profile": "https://Stackoverflow.com/users/8140922",
"pm_score": -1,
"selected": false,
"text": "git add index.html\n"
},
{
"answer_id": 67536881,
"author": "qjpdzjcb",
"author_id": 1670713,
"author_profile": "https://Stackoverflow.com/users/1670713",
"pm_score": 0,
"selected": false,
"text": "chmod 755 file.xxx\n"
},
{
"answer_id": 73051836,
"author": "Daniel Adenew",
"author_id": 2281472,
"author_profile": "https://Stackoverflow.com/users/2281472",
"pm_score": 0,
"selected": false,
"text": "> sudo git add .\n git add --ignore-errors -force .\n chmod 755 /direcroty/file.html \n"
},
{
"answer_id": 73175639,
"author": "14 14",
"author_id": 16624144,
"author_profile": "https://Stackoverflow.com/users/16624144",
"pm_score": 0,
"selected": false,
"text": "sudo chmod -R 777 directory"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8611/"
] |
356,330 | <p>I'm currently using msbuild for a solution of over 600 projects. </p>
<p>Imagine I change the code for 1 library that is used by 10 projects. Instead of providing all 600 projects to msbuild and let it compile all of them and figure out the dependencys. I was wondering if there was a program or library I could use that would analyse the dependencys of all 600 projects, and allow me to only compile the 11 that are necessary.</p>
<p>In other words given the input of all 600 projects to scan, and BaseLibrary.csproj as a project that has been modified parameter, provide me only the 11 projects I need to compile as output.</p>
<p>I'm experienced in writing custom tasks, I'd just rather use a third party library to do the dependency analysis if there is already one out there.</p>
<p>My company does incremental releases to production every 3-4 months. As an experiment I wrote a custom task that looks at the previous releases "Subversion tag" and evaluates all the compiled files that have changed since then and maps them to a project. </p>
<p>The only use case I can think of that doesn't work is the one I mentioned where a base library is changed and the system doesn't know about all the projects that depend on it.</p>
| [
{
"answer_id": 356513,
"author": "Alberto Sciessere",
"author_id": 43500,
"author_profile": "https://Stackoverflow.com/users/43500",
"pm_score": 4,
"selected": true,
"text": "digraph G { \n size=\"100,69\"\n center=\"\"\n ratio=All\n node[width=.25,hight=.375,fontsize=12,color=lightblue2,style=filled]\n 1 -> 9;\n 1 -> 11;\n 9 -> 10;\n 11 -> 10;\n 1 [label=\"Drew.Controls.Map\"];\n 9 [label=\"Drew.Types\"];\n 10 [label=\"nunit.framework\"];\n 11 [label=\"Drew.Util\"];\n } \n"
},
{
"answer_id": 356572,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "depends"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45005/"
] |
356,336 | <p>A few years ago I worked on a system where a numeric primary key was stored in a [SQL Server] varchar column, so I quickly came unstuck when querying with a BETWEEN operator:</p>
<pre><code>SELECT ID FROM MyTable WHERE ID BETWEEN 100 AND 110;
</code></pre>
<p>Results:</p>
<pre><code>100
102
103
109
110
11
</code></pre>
<p>This was simply bad design. However, I'm working on an 3rd-party ERP system, which as you can imagine needs to be generic and flexible; thus we have various tables where alphanumeric fields are provided where the business only uses numerics - so similar problems can occur.</p>
<p>I'm guessing that this is a common enough issue; I have a simple enough solution, but I'm curious as to how others approach such problems.</p>
<p>My simple solution is:</p>
<pre><code>SELECT ID FROM MyTable
WHERE ID BETWEEN iStartValue AND iEndValue
AND (LENGTH(ID) = LENGTH(iStartValue)
OR LENGTH(ID) = LENGTH(iEndValue));
</code></pre>
<p>As you can possibly tell, this is an Oracle system, but I'm usually working in SQL Server - so perhaps database-agnostic solutions are preferable.</p>
<p>Edit 1: Scratch that - I don't see why proprietary solutions aren't welcomed as well.</p>
<p>Edit 2: Thanks for all the responses. I'm not sure whether I'm disappointed there is not an obvious, sophisticated solution, but I'm correspondingly glad that it doesn't appear that I've missed anything obvious!</p>
<p>I think I still prefer my own solution; it's simple and it works - is there any reason why I shouldn't use it? I can't believe it is much, if any, less efficient that the other solutions offered.</p>
<p>I realise that in an ideal world, this problem wouldn't exist; but unfortunately, I don't work in an ideal world, and often it's a case of making the best of a bad situation.</p>
| [
{
"answer_id": 356349,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 3,
"selected": false,
"text": "WHERE CAST(ID as int) BETWEEN iStartValue AND iEndValue\n SELECT ID \nFROM (\n SELECT ID\n FROM MyTable \n WHERE ISNUMERIC(ID) = 1\n AND CHARINDEX ('.', ID) = 0\n AND CHARINDEX ('-', ID) = 0\n ) a\nWHERE CONVERT(bigint, ID) BETWEEN 0 AND 12000\nORDER BY LENGTH(ID) ASC, ID\n"
},
{
"answer_id": 356359,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "SELECT ID FROM MyTable \nWHERE cast(ID as signed) BETWEEN cast(iStartValue as signed) AND cast(iEndValue as signed)\n"
},
{
"answer_id": 356443,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 1,
"selected": false,
"text": "SELECT ID FROM MyTable \nWHERE ID BETWEEN iStartValue AND iEndValue \n And Right('0000000000' + ID, 10) Between iStartValue and iEndValue \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898/"
] |
356,337 | <p>I have a Perl script that sets up variables near the top for directories and files that it will use. It also requires a few variables to be set as command-line arguments.
Example:</p>
<pre><code>use Getopt::Long;
my ($mount_point, $sub_dir, $database_name, $database_schema);
# Populate variables from the command line:
GetOptions(
'mount_point=s' => \$mount_point,
'sub_dir=s' => \$sub_dir,
'database_name=s' => \$database_name,
'database_schema=s' => \$database_schema
);
# ... validation of required arguments here
################################################################################
# Directory variables
################################################################################
my $input_directory = "/${mount_point}/${sub_dir}/input";
my $output_directory = "/${mount_point}/${sub_dir}/output";
my $log_directory = "/${mount_point}/${sub_dir}/log";
my $database_directory = "/db/${database_name}";
my $database_scripts = "${database_directory}/scripts";
################################################################################
# File variables
################################################################################
my $input_file = "${input_dir}/input_file.dat";
my $output_file = "${output_dir}/output_file.dat";
# ... etc
</code></pre>
<p>This works fine in my dev, test, and production environments. However, I was trying to make it easier to override certain variables (without going into the debugger) for development and testing. (For example, if I want to set my input_file = "/tmp/my_input_file.dat"). My thought was to use the GetOptions function to handle this, something like this:</p>
<pre><code>GetOptions(
'input_directory=s' => \$input_directory,
'output_directory=s' => \$output_directory,
'database_directory=s' => \$database_directory,
'log_directory=s' => \$log_directory,
'database_scripts=s' => \$database_scripts,
'input_file=s' => \$input_file,
'output_file=s' => \$output_file
);
</code></pre>
<p>GetOptions can only be called once (as far as I know). The first 4 arguments in my first snippit are required, the last 7 directly above are optional. I think an ideal situation would be to setup the defaults as in my first code snippit, and then somehow override any of them that have been set if arguments were passed at the command line. I thought about storing all my options in a hash and then using that hash when setting up each variable with the default value unless an entry exists in the hash, but that seems to add a lot of additional logic. Is there a way to call GetOptions in two different places in the script?</p>
<p>Not sure if that makes any sense.</p>
<p>Thanks!</p>
| [
{
"answer_id": 356442,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "input_directory $mount_point/$sub_dir"
},
{
"answer_id": 356592,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 4,
"selected": true,
"text": "use Getopt::Long;\n\nmy @required_opts = qw(\n mount_point\n sub_dir\n database_name\n database_schema\n);\n\nmy @internal_opts = qw(\n input_directory\n output_directory\n log_directory\n database_directory\n database_scripts\n input_file\n output_file\n);\n\nmy @opt_spec = (\"debug\", map { \"$_:s\" } @required_opts, @internal_opts);\n\n# Populate variables from the command line:\nGetOptions( \\(my %opts), @opt_spec );\n\n# check required options unless \nmy @errors = grep { ! exists $opts{$_} } @required_options;\nif ( @errors && ! $opts{debug} ) {\n die \"$0: missing required option(s): @errors\\n\";\n}\n\n################################################################################\n# Directory variables\n###############################################################################\nmy $opts{input_directory} ||= \"/$opts{mount_point}/$opts{sub_dir}/input\";\nmy $opts{output_directory} ||= \"/$opts{mount_point}/$opts{sub_dir}/output\";\nmy $opts{log_directory} ||= \"/$opts{mount_point}/$opts{sub_dir}/log\";\nmy $opts{database_directory} ||= \"/db/$opts{database_name}\";\nmy $opts{database_scripts} ||= \"$opts{database_directory}/scripts\";\n\n################################################################################\n# File variables\n################################################################################\nmy $opts{input_file} ||= \"$opts{input_directory}/input_file.dat\";\nmy $opts{output_file} ||= \"$opts{output_directory}/output_file.dat\";\n# ... etc\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40619/"
] |
356,340 | <p>I am looking for a regex statement that will let me extract the HTML content from just between the body tags from a XHTML document.</p>
<p>The XHTML that I need to parse will be very simple files, I do not have to worry about JavaScript content or <code><![CDATA[</code> tags, for example.</p>
<p>Below is the expected structure of the HTML file is that I have to parse. Since I know exactly all of the content of the HTML files that I am going to have to work with, this HTML snippet pretty much covers my entire use case. If I can get a regex to extract the body of this example, I'll be happy.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
</head>
<body contenteditable="true">
<p>
Example paragraph content
</p>
<p>
&nbsp;
</p>
<p>
<br />
&nbsp;
</p>
<h1>Header 1</h1>
</body>
</html>
</code></pre>
<p>Conceptually, I've been trying to build a regex string that matches everything BUT the inner body content. With this, I would use the C# <code>Regex.Split()</code> method to obtain the body content. I thought this regex:</p>
<pre class="lang-none prettyprint-override"><code>((.|\n)*<body (.)*>)|((</body>(*|\n)*)
</code></pre>
<p>...would do the trick, but it doesn't seem to work at all with my test content in RegexBuddy.</p>
| [
{
"answer_id": 356376,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "((?:.(?!<body[^>]*>))+.<body[^>]*>)|(</body\\>.+)\n \\s < body ...> ((?:.(?!<\\s*body[^>]*>))+.<\\s*body[^>]*>)|(<\\s*/\\s*body\\s*\\>.+)\n (.*<\\s*body[^>]*>)|(<\\s*/\\s*body\\s*\\>.+)\n"
},
{
"answer_id": 356380,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 2,
"selected": false,
"text": "/<body[^>]*>(.*)</body>/s\n \\1\n"
},
{
"answer_id": 356384,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 2,
"selected": false,
"text": "</{0,1}body[^>]*> \n"
},
{
"answer_id": 6650686,
"author": "avinash",
"author_id": 838956,
"author_profile": "https://Stackoverflow.com/users/838956",
"pm_score": 3,
"selected": false,
"text": "String toMatch=\"aaaaaaaaaaabcxx sldjfkvnlkfd <body>i m avinash</body>\";\nPattern pattern=Pattern.compile(\".*?<body.*?>(.*?)</body>.*?\");\nMatcher matcher=pattern.matcher(toMatch);\nif(matcher.matches()) {\n System.out.println(matcher.group(1));\n}\n"
},
{
"answer_id": 39482013,
"author": "CrazyTim",
"author_id": 737393,
"author_profile": "https://Stackoverflow.com/users/737393",
"pm_score": 1,
"selected": false,
"text": "<\\s*body.*?> <\\s*/\\s*body.*?> <\\s*body.*?>.*?<\\s*/\\s*body.*?> Singleline"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506/"
] |
356,347 | <p>I'm writing a Greasemonkey script to connect two company-internal webpages. One is SSL, and the other is insecure and can only be accessed via a POST request. If I create a hidden form on the secure page and submit it via an <code>onclick()</code> in an <code><a></code>, it works fine, but FF gives a warning:</p>
<blockquote>
<p>Although this page is encrypted, the information you have entered is to be sent over an unencrypted connection and could easily be read by a third party.</p>
<p>Are you sure you want to continue sending this information?"</p>
</blockquote>
<p>The insecure page can't be accessed via SSL and the other one can't be accessed w/o it, and I can't modify either server =\ Is there any way to avoid this warning by doing some kind of JavaScript/Greasemonkey redirect magic? Thanks!</p>
<p>EDIT: The warning can't be disabled (for rather good reasons, since it's hard to tell if what you're about to send is secure, otherwise). I'm mostly wondering if there's a way to POST in JavaScript without looking like you're submitting a form.</p>
| [
{
"answer_id": 358751,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 2,
"selected": false,
"text": "GM_xmlhttpRequest({\n method: 'POST',\n url: 'http://your.insecure.site.here',\n onload: function(details) {\n\n // look in the JavaScript console \n GM_log(details.responseText);\n\n /* This function will be called when the page (url) \n has been loaded. Do whatever you need to do with the remote page here.*/\n }\n});\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,371 | <p>I was wondering what I could do to improve the performance of Excel automation, as it can be quite slow if you have a lot going on in the worksheet...</p>
<p>Here's a few I found myself:</p>
<ul>
<li><p><code>ExcelApp.ScreenUpdating = false</code> -- turn off the redrawing of the screen</p></li>
<li><p><code>ExcelApp.Calculation = Excel.XlCalculation.xlCalculationManual</code> -- turning off the calculation engine so Excel doesn't automatically recalculate when a cell value changes (turn it back on after you're done)</p></li>
<li><p>Reduce calls to <code>Worksheet.Cells.Item(row, col)</code> and <code>Worksheet.Range</code> -- I had to poll hundreds of cells to find the cell I needed. Implementing some caching of cell locations, reduced the execution time from ~40 to ~5 seconds.</p></li>
</ul>
<p>What kind of interop calls take a heavy toll on performance and should be avoided? What else can you do to avoid unnecessary processing being done?</p>
| [
{
"answer_id": 356399,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": false,
"text": "find Set Found = Cells.Find(What:=SearchString, LookIn:=xlValues, _\n SearchOrder:=xlByRows, SearchDirection:=xlNext, _\n MatchCase:=False, SearchFormat:=False)\n\nIf Not Found Is Nothing Then\n Found.Activate\n (...)\nEndIf\n sort Selection.Sort Key1:=Range(\"A1\"), Order1:=xlAscending, Header:=xlGuess, _\n OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _\n DataOption1:=xlSortNormal\n"
},
{
"answer_id": 369283,
"author": "Jon Fournier",
"author_id": 5106,
"author_profile": "https://Stackoverflow.com/users/5106",
"pm_score": 3,
"selected": false,
"text": "Dim CellVals() as Variant\nCellVals = Range(\"A1:B1000\").Value\n"
},
{
"answer_id": 2294087,
"author": "Anonymous Type",
"author_id": 141720,
"author_profile": "https://Stackoverflow.com/users/141720",
"pm_score": 6,
"selected": false,
"text": "//get values\nobject[,] objectArray = shtName.get_Range(\"A1:Z100\").Value2;\niFace = Convert.ToInt32(objectArray[1,1]);\n\n//set values\nobject[,] objectArray = new object[3,1] {{\"A\"}{\"B\"}{\"C\"}};\nrngName.Value2 = objectArray;\n"
},
{
"answer_id": 31466269,
"author": "JamesFaix",
"author_id": 4415493,
"author_profile": "https://Stackoverflow.com/users/4415493",
"pm_score": 0,
"selected": false,
"text": " app.ScreenUpdates = false //and\n app.Calculation = xlCalculationManual\n app.EnableEvents = false //Prevent Excel events\n app.Interactive = false //Prevent user clicks and keystrokes\n app.ReferenceStyle = xlR1C1\napp.ActiveSheet.Columns(2) = \"=SUBSTITUTE(C[-1],\"foo\",\"bar\")\"\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39259/"
] |
356,373 | <p>Assuming following definition:</p>
<pre><code>/// <summary>
/// Replaces each occurrence of sPattern in sInput with sReplace. This is done
/// with the CLR:
/// new RegEx(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace).
/// The result of the replacement is the return value.
/// </summary>
[SqlFunction(IsDeterministic = true)]
public static SqlString FRegexReplace(string sInput, string sPattern,
string sReplace)
{
return new Regex(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace);
}
</code></pre>
<p>Passing in a <code>nvarchar(max)</code> value for <code>sInput</code> with a length > 4000 will result in the value being truncated (i.e. the result of calling this UDF is <code>nvarchar(4000)</code> as opposed to <code>nvarchar(max)</code>.</p>
| [
{
"answer_id": 356383,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 6,
"selected": true,
"text": "/// <summary>\n/// Replaces each occurrence of sPattern in sInput with sReplace. This is done \n/// with the CLR: \n/// new RegEx(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace). \n/// The result of the replacement is the return value.\n/// </summary>\n[SqlFunction(IsDeterministic = true)]\n[return: SqlFacet(MaxSize = -1)]\npublic static SqlString FRegexReplace([SqlFacet(MaxSize = -1)]string sInput, \n string sPattern, string sReplace)\n{\n return new Regex(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace);\n}\n nvarchar(4000) [return: AttributeName(Parameter=Value, ...)]"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
356,382 | <p>Example: an Order object (aggregate root) has a collection of OrderLine objects (child entities). What's the URL add an OrderLine to an Order? Take into consideration the difference between using the aggregate roots' controller and having a separate controller for the child entity.</p>
<p>1: <a href="http://example.com/orders/details/42/add-orderline?product-id=12&quantity=2" rel="nofollow noreferrer">http://example.com/orders/add-orderline?order-id=42&product-id=12&quantity=2</a></p>
<p>or</p>
<p>2: <a href="http://example.com/order-lines/add?order-id=42&product-id=12&quantity=2" rel="nofollow noreferrer">http://example.com/order-lines/add?order-id=42&product-id=12&quantity=2</a></p>
<p>Thanks!</p>
| [
{
"answer_id": 356383,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 6,
"selected": true,
"text": "/// <summary>\n/// Replaces each occurrence of sPattern in sInput with sReplace. This is done \n/// with the CLR: \n/// new RegEx(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace). \n/// The result of the replacement is the return value.\n/// </summary>\n[SqlFunction(IsDeterministic = true)]\n[return: SqlFacet(MaxSize = -1)]\npublic static SqlString FRegexReplace([SqlFacet(MaxSize = -1)]string sInput, \n string sPattern, string sReplace)\n{\n return new Regex(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace);\n}\n nvarchar(4000) [return: AttributeName(Parameter=Value, ...)]"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830/"
] |
356,390 | <p>I have a div with two nested divs inside, the (float:left) one is the menu bar, and the right (float:right) should display whatever content the page has, it works fine when the window is at a maximum, but when i resize it the content is collapsed until it can no longer has any space, at which it is forced to be displayed BELOW the left menu bar, how can I make the width fixed so that the user may scroll when resized?
(css width didn't work, i alternated between floating the right content and not), here is the code: </p>
<pre><code><div style="width:100%">
<div style="float:left; background:#f5f5f5; border-right:1px solid black; height:170%; width:120px;"></div>
<div style="margin-right:2px;margin-top:15px; margin-bottom:5px; width:100%; border:1px solid #f5f5f5"></div>
</div>
</code></pre>
<p>I only need to have this working on Interner Explorer for now. </p>
| [
{
"answer_id": 356400,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 1,
"selected": false,
"text": "width min-width"
},
{
"answer_id": 356425,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 3,
"selected": true,
"text": ".container {\n width: 1024px;\n display: block;\n}\n"
},
{
"answer_id": 356458,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 0,
"selected": false,
"text": "<div id=\"container\" style=\"width:100%\">\n <div id=\"primaryNav\" style=\"float:left; width:150px; background-color: Orange\">someNav</div>\n <div id=\"content\" style=\"margin-left: 10px; background-color: Red; overflow: auto;\">\n loadsOfSuperInterestingContentI'mSuperSerious<br/>\n <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>\n <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>\n <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>\n Seriously\n </div>\n</div>\n"
},
{
"answer_id": 356474,
"author": "Astra",
"author_id": 5862,
"author_profile": "https://Stackoverflow.com/users/5862",
"pm_score": 2,
"selected": false,
"text": "#containing_div {\n width: 200px;\n overflow: auto;\n}\n #container {\n min-width: 1000px;\n _width: 1000px; /* This property is only read by IE6, which gives a fixed width */\n} \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45016/"
] |
356,411 | <p>I have a stack panel inside of an expander panel that I programaticaly adds check boxes to. Currently the exanpander stops at the bottom of the form, but the stack panel keeps growing. I would like the stack panel to be bounded by the expander and scroll to display the check boxes. Do I need house the check boxes in a list box to get the scroll functionality?</p>
<pre><code><Grid>
<Expander Header="Expander1" Margin="0,0,0,2" Name="Expander1" VerticalAlignment="Top" Background="Coral">
<StackPanel Name="StackScroll" Margin="0,0,0,2" Background="Aqua"></StackPanel>
</Expander>
</Grid>
</code></pre>
<p>");</p>
| [
{
"answer_id": 356457,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 5,
"selected": true,
"text": " <Grid> \n <Expander Header=\"Expander1\" Margin=\"0,0,0,2\" Name=\"Expander1\" VerticalAlignment=\"Top\" Background=\"Coral\">\n <ScrollViewer VerticalScrollBarVisibility=\"Auto\">\n <StackPanel Name=\"StackScroll\" Margin=\"0,0,0,2\" Background=\"Aqua\">\n </StackPanel>\n </ScrollViewer>\n </Expander>\n </Grid>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
356,418 | <p>With SMO objects using Server.JobServer.jobs to get a list of jobs, I can find the status of each job. For those that are currently executing I would like to find the SPID it is executing on. I can also get a list of the server's processes using Server.EnumProcesses(). This gives me a list of currently active SPIDs. I want to match the two. </p>
<p>The best I've been able to come up with is to convert the jobid to a string and substring the jobId out of the program string in the EnumProcesses table (which, at least on my system, embeds the jobId in this description). It's really ugly for a couple of reasons not the least of which is that the Guid in the program description and the guid for jobID have their bytes switched in the first 3 pieces of the string representation. Yuck.</p>
<p>Is there a better way to do that using SMO?</p>
| [
{
"answer_id": 356457,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 5,
"selected": true,
"text": " <Grid> \n <Expander Header=\"Expander1\" Margin=\"0,0,0,2\" Name=\"Expander1\" VerticalAlignment=\"Top\" Background=\"Coral\">\n <ScrollViewer VerticalScrollBarVisibility=\"Auto\">\n <StackPanel Name=\"StackScroll\" Margin=\"0,0,0,2\" Background=\"Aqua\">\n </StackPanel>\n </ScrollViewer>\n </Expander>\n </Grid>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854/"
] |
356,437 | <p>I'm trying to create a jsp tag file but it fails to compile when I try to use <code>pageContext.getServletConfig().getInitParameter("myInitParam")</code></p>
<p>I'm using tomcat and when I try to view a page including the file I get a jasper compile error pageContext cannot be resolved. I've also tried just using <code>getInitParameter</code> but it fails also. I can use the request object so I know everything else is fine.</p>
<p>Does anyone know a way to access init parameters set in the web.xml from a jsp tag file, preferably from within a scriptlet?</p>
| [
{
"answer_id": 356472,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "getInitParameter(\"myInitParam\");\n"
},
{
"answer_id": 356479,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "pageContext setPageContext(PageContext pc) this.pageContext"
},
{
"answer_id": 2681205,
"author": "Vivek Mantri",
"author_id": 322062,
"author_profile": "https://Stackoverflow.com/users/322062",
"pm_score": 0,
"selected": false,
"text": "application.getInitParameter(\"<Name>\");\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45023/"
] |
356,460 | <p>I'm trying to create a LINQ to SQL class that represents the "latest" version of itself.</p>
<p>Right now, the table that this entity represents has a single auto-incrementing ID, and I was thinking that I would add a version number to the primary key. I've never done anything like this, so I'm not sure how to proceed. I would like to be able to abstract the idea of the object's version away from whoever is using it. In other words, you have an instance of this entity that represents the most current version, and whenever any changes are submitted, a new copy of the object is stored with an incremented version number.</p>
<p>How should I proceed with this?</p>
| [
{
"answer_id": 356917,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 4,
"selected": true,
"text": "CREATE TRIGGER tr_TheTrigger\nON [YourTable]\nFOR INSERT, UPDATE, DELETE \nAS\n IF EXISTS(SELECT * FROM inserted)\n BEGIN\n --this is an insert or update\n --your actual action will vary but something like this\n INSERT INTO [YourTable_Audit]\n SELECT * FROM inserted\n END\n IF EXISTS(SELECT * FROM deleted)\n BEGIN\n --this is a delete, mark [YourTable_Audit] as required\n END\nGO\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
356,464 | <p>I am looking for a way to localize properties names displayed in a PropertyGrid. The property's name may be "overriden" using the DisplayNameAttribute attribute. Unfortunately attributes can not have non constant expressions. So I can not use strongly typed resources such as: </p>
<pre><code>class Foo
{
[DisplayAttribute(Resources.MyPropertyNameLocalized)] // do not compile
string MyProperty {get; set;}
}
</code></pre>
<p>I had a look around and found some suggestion to inherit from DisplayNameAttribute to be able to use resource. I would end up up with code like: </p>
<pre><code>class Foo
{
[MyLocalizedDisplayAttribute("MyPropertyNameLocalized")] // not strongly typed
string MyProperty {get; set;}
}
</code></pre>
<p>However I lose strongly typed resource benefits which is definitely not a good thing. Then I came across <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.modeling.design.displaynameresourceattribute.aspx" rel="noreferrer">DisplayNameResourceAttribute</a> which may be what I'm looking for. But it's supposed to be in Microsoft.VisualStudio.Modeling.Design namespace and I can't find what reference I am supposed to add for this namespace.</p>
<p>Anybody know if there's a easier way to achieve DisplayName localization in a good way ? or if there is as way to use what Microsoft seems to be using for Visual Studio ?</p>
| [
{
"answer_id": 356493,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 1,
"selected": false,
"text": "Microsoft.VisualStudio.Modeling.Sdk.dll"
},
{
"answer_id": 356525,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nclass Foo {\n [MyDisplayName(\"bar\")] // perhaps use a constant: SomeType.SomeResName\n public string Bar {get; set; }\n}\n\npublic class MyDisplayNameAttribute : DisplayNameAttribute {\n public MyDisplayNameAttribute(string key) : base(Lookup(key)) {}\n\n static string Lookup(string key) {\n try {\n // get from your resx or whatever\n return \"le bar\";\n } catch {\n return key; // fallback\n }\n }\n}\n\nclass Program {\n [STAThread]\n static void Main() {\n Application.Run(new Form { Controls = {\n new PropertyGrid { SelectedObject =\n new Foo { Bar = \"abc\" } } } });\n }\n}\n"
},
{
"answer_id": 356527,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 0,
"selected": false,
"text": "LocalizedPropertyDescriptor PropertyDescriptor DisplayName Public Overrides ReadOnly Property DisplayName() As String\n Get\n Dim BaseValue As String = MyBase.DisplayName\n Dim Translated As String = Some.ResourceManager.GetString(BaseValue)\n If String.IsNullOrEmpty(Translated) Then\n Return MyBase.DisplayName\n Else\n Return Translated\n End If\n End Get\nEnd Property\n Some.ResourceManager ICustomTypeDescriptor GetProperties Public Function GetProperties() As PropertyDescriptorCollection Implements System.ComponentModel.ICustomTypeDescriptor.GetProperties\n Dim baseProps As PropertyDescriptorCollection = TypeDescriptor.GetProperties(Me, True)\n Dim LocalizedProps As PropertyDescriptorCollection = New PropertyDescriptorCollection(Nothing)\n\n Dim oProp As PropertyDescriptor\n For Each oProp In baseProps\n LocalizedProps.Add(New LocalizedPropertyDescriptor(oProp))\n Next\n Return LocalizedProps\nEnd Function\n <DisplayName(\"prop_description\")> _\nPublic Property Description() As String\n prop_description"
},
{
"answer_id": 357008,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 6,
"selected": false,
"text": "class LocalizedDisplayNameAttribute : DisplayNameAttribute\n{\n private readonly string resourceName;\n public LocalizedDisplayNameAttribute(string resourceName)\n : base()\n {\n this.resourceName = resourceName;\n }\n\n public override string DisplayName\n {\n get\n {\n return Resources.ResourceManager.GetString(this.resourceName);\n }\n }\n}\n [LocalizedDisplayName(ResourceStrings.MyPropertyName)]\npublic string MyProperty\n{\n get\n {\n ...\n }\n}\n ResourceStrings public static class ResourceStrings\n{\n public const string ForegroundColorDisplayName=\"ForegroundColorDisplayName\";\n public const string FontSizeDisplayName=\"FontSizeDisplayName\";\n}\n"
},
{
"answer_id": 359360,
"author": "PowerKiKi",
"author_id": 37706,
"author_profile": "https://Stackoverflow.com/users/37706",
"pm_score": 6,
"selected": true,
"text": " [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]\n public class DisplayNameLocalizedAttribute : DisplayNameAttribute\n {\n public DisplayNameLocalizedAttribute(Type resourceManagerProvider, string resourceKey)\n : base(Utils.LookupResource(resourceManagerProvider, resourceKey))\n {\n }\n }\n internal static string LookupResource(Type resourceManagerProvider, string resourceKey)\n {\n foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic))\n {\n if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))\n {\n System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);\n return resourceManager.GetString(resourceKey);\n }\n }\n\n return resourceKey; // Fallback with the key name\n }\n class Foo\n{\n [Common.DisplayNameLocalized(typeof(Resources.Resource), \"CreationDateDisplayName\"),\n Common.DescriptionLocalized(typeof(Resources.Resource), \"CreationDateDescription\")]\n public DateTime CreationDate\n {\n get;\n set;\n }\n}\n"
},
{
"answer_id": 3311128,
"author": "zielu1",
"author_id": 66621,
"author_profile": "https://Stackoverflow.com/users/66621",
"pm_score": 4,
"selected": false,
"text": "<#@ template debug=\"false\" hostspecific=\"true\" language=\"C#\" #>\n<#@ output extension=\".cs\" #>\n<#@ assembly name=\"System.Xml.dll\" #>\n<#@ import namespace=\"System.Xml\" #>\n<#@ import namespace=\"System.Xml.XPath\" #>\nusing System;\nusing System.ComponentModel;\n\n\nnamespace Bear.Client\n{\n /// <summary>\n /// Localized display name attribute\n /// </summary>\n public class LocalizedDisplayNameAttribute : DisplayNameAttribute\n {\n readonly string _resourceName;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"LocalizedDisplayNameAttribute\"/> class.\n /// </summary>\n /// <param name=\"resourceName\">Name of the resource.</param>\n public LocalizedDisplayNameAttribute(string resourceName)\n : base()\n {\n _resourceName = resourceName;\n }\n\n /// <summary>\n /// Gets the display name for a property, event, or public void method that takes no arguments stored in this attribute.\n /// </summary>\n /// <value></value>\n /// <returns>\n /// The display name.\n /// </returns>\n public override String DisplayName\n {\n get\n {\n return Resources.ResourceManager.GetString(this._resourceName);\n }\n }\n }\n\n partial class Constants\n {\n public partial class Resources\n {\n <# \n var reader = XmlReader.Create(Host.ResolvePath(\"resources.resx\"));\n var document = new XPathDocument(reader);\n var navigator = document.CreateNavigator();\n var dataNav = navigator.Select(\"/root/data\");\n foreach (XPathNavigator item in dataNav)\n {\n var name = item.GetAttribute(\"name\", String.Empty);\n #>\n public const String <#= name#> = \"<#= name#>\";\n <# } #>\n }\n }\n}\n"
},
{
"answer_id": 3877154,
"author": "RandomEngy",
"author_id": 92371,
"author_profile": "https://Stackoverflow.com/users/92371",
"pm_score": 7,
"selected": false,
"text": "PropertyGrid [Display(ResourceType = typeof(MyResources), Name = \"UserName\")]\npublic string UserName { get; set; }\n UserName MyResources.resx"
},
{
"answer_id": 6944233,
"author": "YYFish",
"author_id": 324063,
"author_profile": "https://Stackoverflow.com/users/324063",
"pm_score": 3,
"selected": false,
"text": "<#@ template debug=\"True\" hostspecific=\"True\" language=\"C#\" #>\n<#@ output extension=\".cs\" #>\n<#@ Assembly Name=\"C:\\Project\\trunk\\Resources\\bin\\Development\\Resources.dll\" #>\n<#@ import namespace=\"System.Collections.Generic\" #>\n<#@ import namespace=\"System.Collections\" #>\n<#@ import namespace=\"System.Globalization\" #>\n<#@ import namespace=\"System\" #>\n<#@ import namespace=\"System.Resources\" #>\n<#\n var resourceStrings = new List<string>();\n var manager = Resources.Labels.ResourceManager;\n\n IDictionaryEnumerator enumerator = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true)\n .GetEnumerator();\n while (enumerator.MoveNext())\n {\n resourceStrings.Add(enumerator.Key.ToString());\n }\n#> \n\n// This file is generated automatically. Do NOT modify any content inside.\n\nnamespace Lib.Const{\n public static class LabelNames{\n<#\n foreach (String label in resourceStrings){\n#> \n public const string <#=label#> = \"<#=label#>\"; \n<#\n } \n#>\n }\n}\n using System.ComponentModel.DataAnnotations;\nusing Resources;\n\nnamespace Web.Extensions.ValidationAttributes\n{\n public static class ValidationAttributeHelper\n {\n public static ValidationContext LocalizeDisplayName(this ValidationContext context)\n {\n context.DisplayName = Labels.ResourceManager.GetString(context.DisplayName) ?? context.DisplayName;\n return context;\n }\n }\n}\n namespace Web.Extensions.ValidationAttributes\n{\n\n public class DisplayLabelAttribute :System.ComponentModel.DisplayNameAttribute\n {\n private readonly string _propertyLabel;\n\n public DisplayLabelAttribute(string propertyLabel)\n {\n _propertyLabel = propertyLabel;\n }\n\n public override string DisplayName\n {\n get\n {\n return _propertyLabel;\n }\n }\n }\n}\n using System.ComponentModel.DataAnnotations;\nusing Resources;\n\nnamespace Web.Extensions.ValidationAttributes\n{\n public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute\n {\n public RequiredAttribute()\n {\n ErrorMessageResourceType = typeof (Errors);\n ErrorMessageResourceName = \"Required\";\n }\n\n protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n {\n return base.IsValid(value, validationContext.LocalizeDisplayName());\n }\n\n }\n}\n using Web.Extensions.ValidationAttributes;\n\nnamespace Web.Areas.Foo.Models\n{\n public class Person\n {\n [DisplayLabel(Lib.Const.LabelNames.HowOldAreYou)]\n public int Age { get; set; }\n\n [Required]\n public string Name { get; set; }\n }\n}\n"
},
{
"answer_id": 27904949,
"author": "HaikMnatsakanyan",
"author_id": 1199714,
"author_profile": "https://Stackoverflow.com/users/1199714",
"pm_score": 2,
"selected": false,
"text": "[LocalizedDisplayName(\"Age\", NameResourceType = typeof(RegistrationResources))]\n public bool Age { get; set; }\n public sealed class LocalizedDisplayNameAttribute : DisplayNameAttribute\n{\n private PropertyInfo _nameProperty;\n private Type _resourceType;\n\n\n public LocalizedDisplayNameAttribute(string displayNameKey)\n : base(displayNameKey)\n {\n\n }\n\n public Type NameResourceType\n {\n get\n {\n return _resourceType;\n }\n set\n {\n _resourceType = value;\n _nameProperty = _resourceType.GetProperty(base.DisplayName, BindingFlags.Static | BindingFlags.Public);\n }\n }\n\n public override string DisplayName\n {\n get\n {\n if (_nameProperty == null)\n {\n return base.DisplayName;\n }\n\n return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);\n }\n }\n\n}\n"
},
{
"answer_id": 39680228,
"author": "dionoid",
"author_id": 1982846,
"author_profile": "https://Stackoverflow.com/users/1982846",
"pm_score": 5,
"selected": false,
"text": "[Display(ResourceType = typeof(MyResources), Name = nameof(MyResources.UserName))]\npublic string UserName { get; set; }\n"
},
{
"answer_id": 65370146,
"author": "Martin.Martinsson",
"author_id": 434209,
"author_profile": "https://Stackoverflow.com/users/434209",
"pm_score": 1,
"selected": false,
"text": " public sealed class LocalizedDisplayNameAttribute : DisplayNameAttribute\n{\n public string ResourceKey { get; }\n public string BaseName { get; set; }\n public Type ResourceType { get; set; }\n\n public LocalizedDisplayNameAttribute(string resourceKey)\n {\n ResourceKey = resourceKey;\n }\n\n public override string DisplayName\n {\n get\n {\n var baseName = BaseName;\n var assembly = ResourceType?.Assembly ?? Assembly.GetEntryAssembly();\n\n if (baseName.IsNullOrEmpty())\n {\n // ReSharper disable once PossibleNullReferenceException\n baseName = $\"{(ResourceType != null ? ResourceType.Namespace : assembly.GetName().Name)}.Resources\";\n }\n\n // ReSharper disable once AssignNullToNotNullAttribute\n var res = new ResourceManager(baseName, assembly);\n\n var str = res.GetString(ResourceKey);\n\n return string.IsNullOrEmpty(str)\n ? $\"[[{ResourceKey}]]\"\n : str;\n }\n }\n}\n public sealed class LocalizedDescriptionAttribute : DescriptionAttribute\n{\n public string ResourceKey { get; }\n public string BaseName { get; set; }\n public Type ResourceType { get; set; }\n\n public LocalizedDescriptionAttribute(string resourceKey)\n {\n ResourceKey = resourceKey;\n }\n\n public override string Description\n {\n get\n {\n var baseName = BaseName;\n var assembly = ResourceType?.Assembly ?? Assembly.GetEntryAssembly();\n\n if (baseName.IsNullOrEmpty())\n {\n // ReSharper disable once PossibleNullReferenceException\n baseName = $\"{(ResourceType != null ? ResourceType.Namespace : assembly.GetName().Name)}.Resources\";\n }\n\n // ReSharper disable once AssignNullToNotNullAttribute\n var res = new ResourceManager(baseName, assembly);\n var str = res.GetString(ResourceKey);\n \n return string.IsNullOrEmpty(str)\n ? $\"[[{ResourceKey}]]\"\n : str;\n }\n }\n}\n public sealed class LocalizedCategoryAttribute : CategoryAttribute\n{\n public string ResourceKey { get; }\n public string BaseName { get; set; }\n public Type ResourceType { get; set; }\n\n public LocalizedCategoryAttribute(string resourceKey) \n : base(resourceKey)\n {\n ResourceKey = resourceKey;\n }\n\n protected override string GetLocalizedString(string resourceKey)\n {\n var baseName = BaseName;\n var assembly = ResourceType?.Assembly ?? Assembly.GetEntryAssembly();\n\n if (baseName.IsNullOrEmpty())\n {\n // ReSharper disable once PossibleNullReferenceException\n baseName = $\"{(ResourceType != null ? ResourceType.Namespace : assembly.GetName().Name)}.Resources\";\n }\n\n // ReSharper disable once AssignNullToNotNullAttribute\n var res = new ResourceManager(baseName, assembly);\n var str = res.GetString(resourceKey);\n\n return string.IsNullOrEmpty(str)\n ? $\"[[{ResourceKey}]]\"\n : str;\n }\n}\n [LocalizedDisplayName(\"ResourceKey\", ResourceType = typeof(RE))]"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37706/"
] |
356,465 | <p>Each month I get new CMYK and RGB images that shall be used on the web.</p>
<p>I had a script using a patched up ImageMagick doing this, but it got deleted. So I need to do it again, but it was hard last time.</p>
<p>How do you <em>easily</em> and quickly convert CMYK image files to RGB?</p>
| [
{
"answer_id": 660407,
"author": "davethegr8",
"author_id": 12930,
"author_profile": "https://Stackoverflow.com/users/12930",
"pm_score": 1,
"selected": false,
"text": "convert CMYK.tiff -profile \"RGB.icc\" RGB.tiff\n"
},
{
"answer_id": 11482147,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 0,
"selected": false,
"text": "-type truecolor convert cmyk.jpg -colorspace rgb -type truecolor rgb.jpg\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,480 | <p>I want to extract 'James\, Brown' from the string below but I don't always know what the name will be. The comma is causing me some difficuly so what would you suggest to extract James\, Brown?</p>
<p>OU=James\, Brown,OU=Test,DC=Internal,DC=Net</p>
<p>Thanks</p>
| [
{
"answer_id": 356491,
"author": "xan",
"author_id": 15667,
"author_profile": "https://Stackoverflow.com/users/15667",
"pm_score": 0,
"selected": false,
"text": "string line = GetStringFromWherever();\n\nint start = line.IndexOf(\"=\") + 1;//+1 to get start of name\nint end = line.IndexOf(\"OU=\",start) -1; //-1 to remove comma\n\nstring name = line.Substring(start, end - start);\n"
},
{
"answer_id": 356497,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 2,
"selected": false,
"text": "string name = @\"OU=James\\, Brown,OU=Test,DC=Internal,DC=Net\";\nstring[] splitUp = name.Split(\"=\".ToCharArray(),3);\nstring namePart = splitUp[1].Replace(\",OU\",\"\");\nConsole.WriteLine(namePart);\n"
},
{
"answer_id": 356518,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "static string ParseName(string arg) {\n var regex = new Regex(@\"^OU=([a-zA-Z\\\\]+\\,\\s+[a-zA-Z\\\\]+)\\,.*$\");\n var match = regex.Match(arg);\n return match.Groups[1].Value;\n}\n"
},
{
"answer_id": 356541,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "string input = @\"OU=James\\, Brown,OU=Test,DC=Internal,DC=Net\";\nMatch m = Regex.Match(input, \"^OU=(.*?),OU=.*$\");\nConsole.WriteLine(m.Groups[1].Value); \n"
},
{
"answer_id": 356588,
"author": "Dan Monego",
"author_id": 32771,
"author_profile": "https://Stackoverflow.com/users/32771",
"pm_score": 1,
"selected": false,
"text": " Regex rx = new Regex(@\"(?<!\\\\),\");\n String test = \"OU=James\\\\, Brown,OU=Test,DC=Internal,DC=Net\";\n String[] segments = rx.Split(test);\n String name = segments[0].Split('=', 2)[1];\n"
},
{
"answer_id": 356660,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 0,
"selected": false,
"text": "string originalStr = @\"OU=James\\, Brown,OU=Test,DC=Internal,DC=Net\";\nstring replacedStr = originalStr.Replace(\"\\,\", \",\");\n\nstring name = replacedStr.Substring(0, replacedStr.IndexOf(\",\"));\nConsole.WriteLine(name.Replace(\",\", \",\"));\n"
},
{
"answer_id": 13494728,
"author": "Sean Hall",
"author_id": 628981,
"author_profile": "https://Stackoverflow.com/users/628981",
"pm_score": 0,
"selected": false,
"text": "DsUnquoteRdnValueW"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,484 | <p>How do you even look at the web.config file? I don't know where to go to turn custom errors off...help! </p>
<p>I tried command prompt and java script....can any one help me?</p>
| [
{
"answer_id": 356529,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "Off"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,502 | <p>I often get a PDF from our designer (built in Adobe InDesign) which is supposed to be sent out to thousands of people.</p>
<p>I've got the list with all the people, and it's easy doing a mail merge in OpenOffice.org. However, OpenOffice.org doesn't support the advanced PDF. I just want to output some text onto each page and print it out.</p>
<p>Here's how I do it now: print out 6.000 copies of the PDF, then put all of them into the printer again and just print out name, address and other information on top of it. But that's expensive.</p>
<p>Sadly, I can't make the PDF to an image and use that in OpenOffice.org because it grinds the computer to a halt. It also takes extremely long time to send this job to the printer.</p>
<p>So, is there an easy way to do this mail merge (preferably in Python) without paying for third party closed solutions?</p>
| [
{
"answer_id": 356833,
"author": "rhanekom",
"author_id": 37605,
"author_profile": "https://Stackoverflow.com/users/37605",
"pm_score": 1,
"selected": false,
"text": "PdfContentByte cb= ...;\ncb.BeginText();\ncb.SetFontAndSize(font, fontSize);\nfloat x = ...;\nfloat y = ...;\ncb.SetTextMatrix(x, y);\ncb.ShowText(fieldValue);\ncb.EndText(); \n %FDF-1.2\n%âãÏÓ\n1 0 obj\n<<<\n /F(Example PDF Form.pdf)\n /Fields[\n <<\n /T(myTextField)\n /V(myTextField default value)\n >>\n ]\n >>\n>> endobj trailer\n<>\n%%EOF\n PdfAcroForm acroForm = writer.AcroForm;\nacroForm.Put(new PdfName(fieldInfo.Name), new PdfString(fieldInfo.Value));\n"
},
{
"answer_id": 1485027,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 3,
"selected": false,
"text": "pdftk names.pdf background boat_background.pdf output out.pdf\n names.pdf"
},
{
"answer_id": 57115533,
"author": "Stephen Price",
"author_id": 11808947,
"author_profile": "https://Stackoverflow.com/users/11808947",
"pm_score": 1,
"selected": false,
"text": "pip install fdfgen import csv\nimport subprocess\n\nfrom fdfgen import forge_fdf\n\nPDF_FORM = 'path/to/form.pdf'\nCSV_DATA = 'path/to/data.csv'\n\ninfile = open(CSV_DATA, 'rb')\nreader = csv.DictReader(infile)\nrows = [row for row in reader]\ninfile.close()\n\nfor row in rows:\n # Create fdf\n filename = row['filename'] # Construct filename\n fdf_data = [(k,v) for k, v in row.items()]\n fdf = forge_fdf(fdf_data_strings=fdf_data)\n fdf_file = open(filename+'.fdf', 'wb')\n fdf_file.write(fdf)\n fdf_file.close()\n\n # Use PDFTK to create filled, flattened, pdf file\n cmds = ['pdftk', PDF_FORM, 'fill_form', filename+'.fdf',\n 'output', filename+'.pdf', 'flatten', 'dont_ask']\n process = subprocess.Popen(cmds, stdout=subprocess.PIPE)\n stdout, stderr = process.communicate()\n returncode = process.poll()\n os.remove(filename+'.fdf')\n"
},
{
"answer_id": 57295681,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 1,
"selected": false,
"text": "csv_to_pdf.py #!/usr/bin/python\n# This makes one PDF page per name in the CSV file\n# csv_to_pdf.py <CSV_FILE>\n\nimport csv\nimport sys\nfrom reportlab.pdfgen.canvas import Canvas\nfrom reportlab.lib.units import cm, mm\n\nin_db = csv.reader(open(sys.argv[1], \"rb\"));\noutname = sys.argv[1].replace(\"csv\", \"pdf\")\npdf = Canvas(outname)\nin_db.next()\n\ni = 0\nfor rad in in_db:\n pdf.setFontSize(11)\n adr = rad[1]\n\n tekst = pdf.beginText(2*cm, 26*cm)\n\n for a in adr.split('\\n'):\n if not a.strip():\n continue\n if a[-1] == ',':\n a = a[:-1]\n tekst.textLine(a)\n pdf.drawText(tekst)\n pdf.showPage()\n\n i += 1\n if i % 1000 == 0:\n print i\npdf.save()\n pdftk <YOUR_NEW_PDF_FILE.pdf> background <DESIGNED_FILE.pdf> <MERGED.pdf>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,506 | <p>I have created a windows service that uses Windows Messaging System. When I test the app from the debugger the Messages go through nicely but when I install it my messag … asked 14 mins ago</p>
<p>vladimir
1tuga </p>
| [
{
"answer_id": 356702,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 3,
"selected": false,
"text": "while(GetMessage(&Msg, NULL, 0, 0) > 0)\n{\n TranslateMessage(&Msg);\n DispatchMessage(&Msg);\n}\n"
},
{
"answer_id": 356727,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 3,
"selected": false,
"text": "writeln"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,543 | <p>I was just wondering how I could <em>automatically</em> increment the build (and version?) of my files using Visual Studio (2005). </p>
<p>If I look up the properties of say <code>C:\Windows\notepad.exe</code>, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not version 1.0.0.0, which let's face it is a bit dull.</p>
<p>I tried a few things, but it doesn't seem to be out-of-box functionality, or maybe I'm just looking in the wrong place (as usual).</p>
<p>I work with mainly web projects....</p>
<p>I looked at both:</p>
<ol>
<li><a href="http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx</a></li>
<li><a href="http://www.codeproject.com/KB/dotnet/build_versioning.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/build_versioning.aspx</a></li>
</ol>
<p>and I couldn't believe it so much effort to do something is standard practice.</p>
<p>EDIT:
<strong>It does not work in VS2005 as far I can tell (<a href="http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx</a>)</strong></p>
| [
{
"answer_id": 356555,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 4,
"selected": false,
"text": " System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\n System.Reflection.AssemblyName assemblyName = assembly.GetName();\n Version version = assemblyName.Version;\n [assembly: AssemblyVersion(\"1.0.*\")]\n [assembly: AssemblyFileVersion(\"1.0.*\")]\n"
},
{
"answer_id": 356556,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 7,
"selected": false,
"text": "// You can specify all the values or you can default the Build and Revision Numbers \n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n [assembly: AssemblyVersion(\"1.0.*\")]\n//[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n"
},
{
"answer_id": 356694,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 10,
"selected": true,
"text": "[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyFileVersion(\"1.0.*\")]\n [assembly: AssemblyVersion(\"1.0.*\")]\n"
},
{
"answer_id": 360764,
"author": "SeaDrive",
"author_id": 19267,
"author_profile": "https://Stackoverflow.com/users/19267",
"pm_score": 2,
"selected": false,
"text": "string ver = Application.ProductVersion;\n ver = 1.0.3251.27860"
},
{
"answer_id": 2070500,
"author": "Christian",
"author_id": 54193,
"author_profile": "https://Stackoverflow.com/users/54193",
"pm_score": 6,
"selected": false,
"text": "<Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" /> .csproj <Import Project=\"$(MSBuildExtensionsPath)\\MSBuildCommunityTasks\\MSBuild.Community.Tasks.Targets\" />\n<Target Name=\"BeforeBuild\">\n <Version VersionFile=\"Properties\\version.txt\" Major=\"1\" Minor=\"0\" BuildType=\"Automatic\" StartDate=\"12/31/2009\" RevisionType=\"BuildIncrement\">\n <Output TaskParameter=\"Major\" PropertyName=\"Major\" />\n <Output TaskParameter=\"Minor\" PropertyName=\"Minor\" />\n <Output TaskParameter=\"Build\" PropertyName=\"Build\" />\n <Output TaskParameter=\"Revision\" PropertyName=\"Revision\" />\n </Version>\n <AssemblyInfo CodeLanguage=\"CS\"\n OutputFile=\"Properties\\VersionInfo.cs\"\n AssemblyVersion=\"$(Major).$(Minor)\"\n AssemblyFileVersion=\"$(Major).$(Minor).$(Build).$(Revision)\" />\n</Target>\n VersionInfo.cs [assembly: AssemblyVersion(\"1.0\")]\n[assembly: AssemblyFileVersion(\"1.0.14.2\")]\n AssemblyVersion AssemblyFileVersion AssemblyInfo.cs $(MSBuildExtensionsPath)\\MSBuildCommunityTasks\\MSBuild.Community.Tasks.chm"
},
{
"answer_id": 6472195,
"author": "Boog",
"author_id": 16492,
"author_profile": "https://Stackoverflow.com/users/16492",
"pm_score": 5,
"selected": false,
"text": " <PropertyGroup>\n <Year>$([System.DateTime]::Now.ToString(\"yy\"))</Year>\n <Month>$([System.DateTime]::Now.ToString(\"MM\"))</Month>\n <Date>$([System.DateTime]::Now.ToString(\"dd\"))</Date>\n <Time>$([System.DateTime]::Now.ToString(\"HHmm\"))</Time>\n <AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion(\"$(Year).$(Month).$(Date).$(Time)\")]</AssemblyFileVersionAttribute>\n </PropertyGroup>\n <Target Name=\"BeforeBuild\">\n <WriteLinesToFile File=\"Properties\\VersionInfo.cs\" Lines=\"$(AssemblyFileVersionAttribute)\" Overwrite=\"true\">\n </WriteLinesToFile>\n </Target>\n"
},
{
"answer_id": 11419717,
"author": "Andreas Reiff",
"author_id": 586754,
"author_profile": "https://Stackoverflow.com/users/586754",
"pm_score": 3,
"selected": false,
"text": "echo [assembly:System.Reflection.AssemblyFileVersion(\"%date:~-4,4%.%date:~-7,2%%date:~-10,2%.%time:~0,2%%time:~3,2%.%time:~-5,2%\")] > $(ProjectDir)Properties\\VersionInfo.cs\n var version = assembly.GetName().Version;\nvar fileVersionString = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;\nVersion fileVersion = new Version(fileVersionString);\nvar buildDateTime = new DateTime(fileVersion.Major, fileVersion.Minor/100, fileVersion.Minor%100, fileVersion.Build/100, fileVersion.Build%100, fileVersion.Revision);\n"
},
{
"answer_id": 16532168,
"author": "Atiris",
"author_id": 659223,
"author_profile": "https://Stackoverflow.com/users/659223",
"pm_score": 2,
"selected": false,
"text": " private bool IncreaseFileVersionBuild()\n {\n if (System.Diagnostics.Debugger.IsAttached)\n {\n try\n {\n var fi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.GetDirectories(\"Properties\")[0].GetFiles(\"AssemblyInfo.cs\")[0];\n var ve = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);\n string ol = ve.FileMajorPart.ToString() + \".\" + ve.FileMinorPart.ToString() + \".\" + ve.FileBuildPart.ToString() + \".\" + ve.FilePrivatePart.ToString();\n string ne = ve.FileMajorPart.ToString() + \".\" + ve.FileMinorPart.ToString() + \".\" + (ve.FileBuildPart + 1).ToString() + \".\" + ve.FilePrivatePart.ToString();\n System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace(\"[assembly: AssemblyFileVersion(\\\"\" + ol + \"\\\")]\", \"[assembly: AssemblyFileVersion(\\\"\" + ne + \"\\\")]\"));\n return true;\n }\n catch\n {\n return false;\n }\n }\n return false;\n }\n"
},
{
"answer_id": 35781252,
"author": "hal",
"author_id": 1191799,
"author_profile": "https://Stackoverflow.com/users/1191799",
"pm_score": 2,
"selected": false,
"text": "Setup(() =>\n{\n // Executed BEFORE the first task.\n var datetimeNow = DateTime.Now;\n var daysPart = (datetimeNow - new DateTime(2000, 1, 1)).Days;\n var secondsPart = (long)datetimeNow.TimeOfDay.TotalSeconds/2;\n var assemblyInfo = new AssemblyInfoSettings\n {\n Version = \"3.0.0.0\",\n FileVersion = string.Format(\"3.0.{0}.{1}\", daysPart, secondsPart)\n };\n CreateAssemblyInfo(\"MyProject/Properties/AssemblyInfo.cs\", assemblyInfo);\n});\n"
},
{
"answer_id": 38282539,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "{major}.{year}.1{date}.1{time} 1.2016.10709.11641 1 CustomVersionNumber AssemblyVersion AssemblyFileVersion Properties/AssemblyInfo.cs .cs .tt <#@ template language=\"C#\" #>\n<#@ assembly name=\"System.Core\" #>\n<#@ import namespace=\"System.Linq\" #>\n\n//\n// This code was generated by a tool. Any changes made manually will be lost\n// the next time this code is regenerated.\n//\n\nusing System.Reflection;\n\n<#\n var date = DateTime.Now;\n int major = 1;\n int minor = date.Year;\n int build = 10000 + int.Parse(date.ToString(\"MMdd\"));\n int revision = 10000 + int.Parse(date.ToString(\"HHmm\"));\n#>\n\n[assembly: AssemblyVersion(\"<#= $\"{major}.{minor}.{build}.{revision}\" #>\")]\n[assembly: AssemblyFileVersion(\"<#= $\"{major}.{minor}.{build}.{revision}\" #>\")]\n"
},
{
"answer_id": 56296398,
"author": "Madacol",
"author_id": 3163120,
"author_profile": "https://Stackoverflow.com/users/3163120",
"pm_score": 3,
"selected": false,
"text": "[assembly: AssemblyVersion(\"1.0.*\")]\n Deterministic False project.csproj <Deterministic>false</Deterministic>\n Deterministic False autoincrement_version.ps1 AssemblyInfo.cs if $(ConfigurationName) == Release (\nPowerShell -ExecutionPolicy RemoteSigned $(ProjectDir)autoincrement_version.ps1 '$(ProjectDir)My Project\\AssemblyInfo.cs'\n)\n param( [string]$file );\n $regex_revision = '(?<=Version\\(\"(?:\\d+\\.)+)(\\d+)(?=\"\\))'\n $found = (Get-Content $file) | Select-String -Pattern $regex_revision\n $revision = $found.matches[0].value\n $new_revision = [int]$revision + 1\n (Get-Content $file) -replace $regex_revision, $new_revision | Set-Content $file -Encoding UTF8\n"
},
{
"answer_id": 60812302,
"author": "John Denniston",
"author_id": 6816685,
"author_profile": "https://Stackoverflow.com/users/6816685",
"pm_score": 0,
"selected": false,
"text": "\"C:\\Program Files\\TortoiseSVN\\bin\\SubWCRev.exe\" \"$(ProjectDir).\" \"$(ProjectDir)Properties\\AssemblyInfo.wcrev\" \"$(ProjectDir)Properties\\AssemblyInfo.cs\"\n [assembly: AssemblyFileVersion(\"1.0.0.$WCREV$\")]\n"
},
{
"answer_id": 73797629,
"author": "Abtzero",
"author_id": 6559616,
"author_profile": "https://Stackoverflow.com/users/6559616",
"pm_score": 1,
"selected": false,
"text": "<Deterministic>false</Deterministic> \"Path-to-this-script\\UpdateVersion.vbs\" \"$(ProjectDir)\"\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31765/"
] |
356,547 | <p>MS SQL Server 2000</p>
<p>I have a column in Table A called Name. I wish to sort the Name field. Many but not all of the records for Name start will KL and are followed by a number (KL 1234, KL 2, KL 323, etc).</p>
<h2>Table A</h2>
<h2>Name</h2>
<p>Able<br>
Bravo<br>
KL 2<br>
KL 323<br>
KL 1234<br>
Zebra</p>
<p>If I use</p>
<pre><code>Select Name from A
Order by Name
</code></pre>
<p>I get</p>
<p>Able<br>
Bravo<br>
KL 1234<br>
KL 2<br>
KL 323<br>
Zebra </p>
<p>I want</p>
<p>Able<br>
Bravo<br>
KL 2<br>
KL 323<br>
KL 1234<br>
Zebra </p>
<p>If they all started with KL I could use</p>
<pre><code>Select Name from A
Order by cast(replace(name, 'KL', '') as big int)
</code></pre>
<p>but this generates an "unble to cast name as big int" error for values that do not start with KL</p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 356625,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": true,
"text": "Order By \n Case When Left(name, 2) = 'KL' \n Then 'KL' + Replace(Str(Cast(replace(name, 'KL', '') as BigInt), 12), ' ', '0')\n Else name End\n"
},
{
"answer_id": 356644,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "ORDER BY \n CASE WHEN CHARINDEX(' ', name)=0 THEN name \n ELSE LEFT(name, CHARINDEX(' ', name)) END,\n CASE WHEN CHARINDEX(' ', name)=0 THEN 0\n ELSE CONVERT(BIGINT, \n SUBSTRING(name, CHARINDEX(' ', name)+1, LEN(name))) END\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45042/"
] |
356,548 | <p>I am trying to respond back to a client with a PDF stored in a MSSQL varbinary(MAX) field. The response works on my localhost and a test server over http connection, but does not work on the production server over https connection. I am using just a simple BinaryWrite (code below).</p>
<pre><code> byte[] displayFile = DatabaseFiles.getPdfById(id);
Response.ContentType = "application/pdf";
Response.BinaryWrite(displayFile);
</code></pre>
<p>Nothing fancy here. Just grab the binary data, set the content type, and write back to client. Is there anything special that needs to be done in order to respond back over https in this way?</p>
<p><strong>Edit:</strong> By doesn't work, I mean that I get a blank document in the browser. Acrobat does not load in browser.</p>
<p><strong>Edit:</strong> I just noticed that this problem is only occurring in IE 7. The PDF loads correctly in Firefox 3. Our client uses IE 7 exclusively (better than IE 6 which I persuaded them upgrade from...lol).</p>
<p><strong>Edit:</strong> Tried to add the header "content-disposition" to make the file act as an attachment. Browser failed to loaded under SSL with the IE error "Internet Explorer cannot download displayFile.aspx from ProductionServer.net." (Code Below)</p>
<pre><code> byte[] displayFile = DatabaseFiles.getPdfById(id);
Response.Clear();
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName));
Response.ContentType = "application/pdf";
Response.BinaryWrite(displayFile);
</code></pre>
<p><strong>Edit:</strong> If the file is viewed over http on the Production Server, the browser displays the code for the PDF like it was being viewed through NotePad. (e.g. %PDF-1.4 %âãÏÓ 6 0 obj <> endobj xref 6 33 ...etc)</p>
| [
{
"answer_id": 357031,
"author": "Eddie",
"author_id": 576,
"author_profile": "https://Stackoverflow.com/users/576",
"pm_score": 0,
"selected": false,
"text": "GET /displayFile.aspx?id=128 HTTP/1.1\nAccept: */*\nAccept-Language: en-us\nUA-CPU: x86\nAccept-Encoding: gzip, deflate\nUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)\nHost: ProductionServer.net\nConnection: Keep-Alive\n HTTP/1.1 200 OK\nDate: Wed, 10 Dec 2008 18:39:54 GMT\nServer: Microsoft-IIS/6.0\nX-Powered-By: ASP.NET\nX-AspNet-Version: 2.0.50727\nCache-Control: no-cache\nPragma: no-cache\nExpires: -1\nContent-Type: application/pdf; charset=utf-8\nContent-Length: 102076\n"
},
{
"answer_id": 561882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "Response.Clear();\n Response.ClearContent();\nResponse.ClearHeaders();\n byte[] downloadBytes = doc.GetData();\nResponse.ClearContent();\nResponse.ClearHeaders();\n\nResponse.Buffer = true;\nResponse.ContentType = \"application/pdf\";\nResponse.AddHeader(\"Content-Length\", downloadBytes.Length.ToString());\nResponse.AddHeader(\"Content-Disposition\", \"attachment; filename=myFile.pdf\");\nResponse.BinaryWrite(downloadBytes);\nResponse.Flush();\nResponse.End();\n"
},
{
"answer_id": 5047402,
"author": "KyleH",
"author_id": 623901,
"author_profile": "https://Stackoverflow.com/users/623901",
"pm_score": 1,
"selected": false,
"text": "<%@ OutputCache Location=\"None\" %> Response.ClearHeaders"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
] |
356,550 | <p>I need a Java library to convert PDFs to TIFF images. The PDFs are faxes, and I will be converting to TIFF so that I can then do barcode recognition on the image. Can anyone recommend a good free open source library for conversion from PDF to TIFF? </p>
| [
{
"answer_id": 356582,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\n\n/opt/local/bin/gs -q -dLastPage=1 -dNOPAUSE -dBATCH -dSAFER -r300 \\\n -sDEVICE=pnmraw -sOutputFile=- $* |\n pnmcrop |\n pnmscale -width 240 |\n cjpeg\n -sDEVICE=tiff..."
},
{
"answer_id": 1790376,
"author": "serge_gubenko",
"author_id": 205596,
"author_profile": "https://Stackoverflow.com/users/205596",
"pm_score": 2,
"selected": false,
"text": "gswin32c -dNOPAUSE -dBATCH -dMaxStripSize=8192 -sDEVICE=tiffg3 -r204x196 -dDITHERPPI=200 -sOutputFile=test.tif prefix.ps test.pdf\n << currentpagedevice /InputAttributes get\n0 1 2 index length 1 sub {1 index exch undef } for\n/InputAttributes exch dup 0 <</PageSize [0 0 612 1728]>> put\n/Policies << /PageSize 3 >> >> setpagedevice\n"
},
{
"answer_id": 5486123,
"author": "Andrea Redshot",
"author_id": 682180,
"author_profile": "https://Stackoverflow.com/users/682180",
"pm_score": -1,
"selected": false,
"text": "private static String convertTiff2Pdf(String tiff) {\n\n // target path PDF\n String pdf = null;\n\n try {\n\n pdf = tiff.substring(0, tiff.lastIndexOf('.') + 1) + \"pdf\";\n\n // New document A4 standard (LETTER)\n Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);\n\n PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));\n int pages = 0;\n document.open();\n PdfContentByte cb = writer.getDirectContent();\n RandomAccessFileOrArray ra = null;\n int comps = 0;\n ra = new RandomAccessFileOrArray(tiff);\n comps = TiffImage.getNumberOfPages(ra);\n\n // Convertion statement\n for (int c = 0; c < comps; ++c) {\n Image img = TiffImage.getTiffImage(ra, c + 1);\n if (img != null) {\n System.out.println(\"page \" + (c + 1));\n img.scalePercent(7200f / img.getDpiX(), 7200f / img.getDpiY());\n document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));\n img.setAbsolutePosition(0, 0);\n cb.addImage(img);\n document.newPage();\n ++pages;\n }\n }\n\n ra.close();\n document.close();\n\n } catch (Exception e) {\n logger.error(\"Convert fail\");\n logger.debug(\"\", e);\n pdf = null;\n }\n\n logger.debug(\"[\" + tiff + \"] -> [\" + pdf + \"] OK\");\n return pdf;\n\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39430/"
] |
356,551 | <p>I'm researching this for a project and I'm wondering what other people are doing to prevent stale CSS and JavaScript files from being served with each new release. I don't want to append a timestamp or something similar which may prevent caching on every request. </p>
<p>I'm working with the Spring 2.5 MVC framework and I'm already using the google api's to serve prototype and scriptaculous. I'm also considering using Amazon S3 and the new Cloudfront offering to minimize network latency.</p>
| [
{
"answer_id": 356574,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 1,
"selected": false,
"text": "conditional get If-Modified-Since"
},
{
"answer_id": 356622,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 5,
"selected": true,
"text": "<script type=\"text/javascript\" src=\"/path/to/script.js?ver=456\"></script>\n"
},
{
"answer_id": 357030,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "touch"
},
{
"answer_id": 12397061,
"author": "Ethan T",
"author_id": 31707,
"author_profile": "https://Stackoverflow.com/users/31707",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"/path/to/script.js?1347486578\"></script>\n function cachePreventCode($filename) {\n if (!file_exists($filename))\n return \"\";\n $mtime = filemtime($filename);\n return $mtime;\n}\n <link rel=\"stylesheet\" type=\"text/css\" href=\"main.css?<?= cachePreventCode(\"main.css\") ?>\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"main.css?1347489244\" />\n"
},
{
"answer_id": 32016795,
"author": "Fernando Nogueira",
"author_id": 4062292,
"author_profile": "https://Stackoverflow.com/users/4062292",
"pm_score": 0,
"selected": false,
"text": "<properties>\n <maven.build.timestamp.format>yyyyMMddHHmm</maven.build.timestamp.format>\n <timestamp>${maven.build.timestamp}</timestamp>\n</properties>\n <script type=\"text/javascript\" src=\"/js/myScript.js?t=${timestamp}\"></script>\n"
},
{
"answer_id": 72131377,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 0,
"selected": false,
"text": "/media/js/v12/my.js /media/js/my.js /media/js/v*/my.js /media/js/my.js"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22436/"
] |
356,557 | <p>I have created a class library in VB .NET. Some code in the library connects to the database. I want to create a config file that would hold the connection string.
<br /><br />
I have created a "Settings.settings" file and stored the connection string in there.
<br /><br />
When a class library having a settings file is built, it generates a ".dll.config" file which has the key value pairs defined in the settings file.
<br /><br />
Problem with this is when i change the connection string in the ".dll.config" file, the library does not references these changes. I would still need to recompile the class library which would then overwrite my changes in the .dll.config file.
<br /><br />
I need to be able to change the connection strings on the fly without having to recompile the library.
<br /><br />
Is there a mechanism in VB.NET class library (.NET 2.0) that would let me do this?
<br /><br />
Passing the connection string to the class library from the web page that uses its method is not a option.
<br /> <br>
I have listed a sample below, this is how i would access the string.</p>
<pre>
Public Function getsettings(ByVal Setting As String) As String
If Setting = "Demo" Then
Return My.Settings.Demo
Else
Return My.Settings.Live
End If
End Function
</pre>
| [
{
"answer_id": 356571,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 3,
"selected": true,
"text": "If GetApplicationSetting(\"connectionString\") Is Nothing Then\n Throw New Exception(\"Could not retrieve connection string from .config file\")\nElse\n Return ConfigurationManager.AppSettings.Item(\"connectionString\")\nEnd If\n ConfigurationManager.ConnectionStrings(\"MyConnectionString\")\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443363/"
] |
356,570 | <p>We have a query that selects rows depending on the value of another, ie. the max. I don't think that really makes much sense, so here is the query:</p>
<pre><code>var deatched = DetachedCriteria.For<Enquiry>("e2")
.SetProjection(Projections.Alias(Projections.Max("Property"), "maxProperty"))
.Add(Restrictions.EqProperty("e2.EnquiryCode", "e.EnquiryCode"));
session.CreateCriteria(typeof(Enquiry), "e")
.Add(Subqueries.PropertyEq("Property", deatched))
.AddOrder(Order.Asc("EnquiryCode"));
</code></pre>
<p>My question is, is this the best way? Can anyone suggest a better way?</p>
| [
{
"answer_id": 11565591,
"author": "Tony Wolfango",
"author_id": 1535227,
"author_profile": "https://Stackoverflow.com/users/1535227",
"pm_score": 0,
"selected": false,
"text": "(from e in NHibernateSession().Query<Enquiry>()\n where e.Property == (\n (\n from e2 NHibernateSession().Query<Enquiry>()\n where e2.EnqueryCode == e.EnquiryCode\n select e2.Property).Max()\n )\n select e\n).ToList<Enquiry>()\n"
},
{
"answer_id": 12151651,
"author": "eepzable",
"author_id": 550652,
"author_profile": "https://Stackoverflow.com/users/550652",
"pm_score": 1,
"selected": false,
"text": "session.CreateCriteria(typeof(Customer))\n .SetProjection( Projections.Max(\"Id\") )\n .UniqueResult();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
356,578 | <p>Is there an easy way to run a MySQL query from the Linux command line and output the results in <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="noreferrer">CSV</a> format?</p>
<p>Here's what I'm doing now:</p>
<pre class="lang-none prettyprint-override"><code>mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/ /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ
</code></pre>
<p>It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.</p>
| [
{
"answer_id": 356605,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 12,
"selected": true,
"text": "SELECT order_id,product_name,qty\nFROM orders\nWHERE foo = 'bar'\nINTO OUTFILE '/var/lib/mysql-files/orders.csv'\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n';\n SELECT order_id,product_name,qty\nINTO OUTFILE '/var/lib/mysql-files/orders.csv'\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n'\nFROM orders\nWHERE foo = 'bar';\n /var/lib/mysql-files/orders.csv"
},
{
"answer_id": 2601837,
"author": "Stan",
"author_id": 113036,
"author_profile": "https://Stackoverflow.com/users/113036",
"pm_score": 9,
"selected": false,
"text": "mysql your_database --password=foo < my_requests.sql > out.tsv\n ... .sql | sed 's/\\t/,/g' > out.csv\n"
},
{
"answer_id": 3093708,
"author": "Leland Woodbury",
"author_id": 373137,
"author_profile": "https://Stackoverflow.com/users/373137",
"pm_score": 5,
"selected": false,
"text": "mysql --batch --raw"
},
{
"answer_id": 5395421,
"author": "Tim Harding",
"author_id": 38021,
"author_profile": "https://Stackoverflow.com/users/38021",
"pm_score": 8,
"selected": false,
"text": "mysql --user=wibble --password mydatabasename -B -e \"select * from vehicle_categories;\" | sed \"s/'/\\'/;s/\\t/\\\",\\\"/g;s/^/\\\"/;s/$/\\\"/;s/\\n//g\" > vehicle_categories.csv\n s/'/\\'/ Replace ' with \\'\ns/\\t/\\\",\\\"/g Replace all \\t (tab) with \",\"\ns/^/\\\"/ at the beginning of the line place a \"\ns/$/\\\"/ At the end of the line, place a \"\ns/\\n//g Replace all \\n (newline) with nothing\n"
},
{
"answer_id": 6614691,
"author": "extraplanetary",
"author_id": 453255,
"author_profile": "https://Stackoverflow.com/users/453255",
"pm_score": 3,
"selected": false,
"text": "echo $QUERY | \\\n mysql -B $MYSQL_OPTS | \\\n perl -F\"\\t\" -lane 'print join \",\", map {s/\"/\"\"/g; /^[\\d.]+$/ ? $_ : qq(\"$_\")} @F ' | \\\n mail -s 'report' person@address\n"
},
{
"answer_id": 8084621,
"author": "Steve",
"author_id": 1040384,
"author_profile": "https://Stackoverflow.com/users/1040384",
"pm_score": 5,
"selected": false,
"text": "mysql your_database -p < my_requests.sql | awk '{print $1\",\"$2}' > out.csv\n"
},
{
"answer_id": 8405141,
"author": "Marty Hirsch",
"author_id": 1084155,
"author_profile": "https://Stackoverflow.com/users/1084155",
"pm_score": 4,
"selected": false,
"text": "select concat_ws(',',\n concat('\"', replace(field1, '\"', '\"\"'), '\"'),\n concat('\"', replace(field2, '\"', '\"\"'), '\"'),\n concat('\"', replace(field3, '\"', '\"\"'), '\"'))\n\nfrom your_table where etc;\n \" \"\" replace(field1, '\"', '\"\"') concat('\"', result1, '\"') concat_ws(',', quoted1, quoted2, ...)"
},
{
"answer_id": 9748559,
"author": "user7610",
"author_id": 1047788,
"author_profile": "https://Stackoverflow.com/users/1047788",
"pm_score": 0,
"selected": false,
"text": "php --php-ini path/to/php.ini your-script.php\n --php-ini <?php\n #mysql_connect(\"localhost\", \"username\", \"password\") or die(mysql_error());\n mysql_select_db(\"mydb\") or die(mysql_error());\n\n $result = mysql_query(\"SELECT * FROM table_with_the_data p WHERE p.type = $typeiwant\");\n\n $result || die(mysql_error());\n\n while($row = mysql_fetch_row($result)) {\n $comma = false;\n foreach ($row as $item) {\n\n # Make it comma separated\n if ($comma) {\n echo ',';\n } else {\n $comma = true;\n }\n\n # Quote the quotes\n $quoted = str_replace(\"\\\"\", \"\\\"\\\"\", $item);\n\n # Quote the string\n echo \"\\\"$quoted\\\"\";\n }\n echo \"\\n\";\n }\n?>\n"
},
{
"answer_id": 12843017,
"author": "strickli",
"author_id": 1612703,
"author_profile": "https://Stackoverflow.com/users/1612703",
"pm_score": 7,
"selected": false,
"text": "mysql <database> -e \"<query here>\" | tr '\\t' ',' > data.csv\n"
},
{
"answer_id": 16582045,
"author": "lepe",
"author_id": 196507,
"author_profile": "https://Stackoverflow.com/users/196507",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nif [ \"$1\" == \"\" ];then\n echo \"Usage: $0 DATABASE TABLE [MYSQL EXTRA COMMANDS]\"\n exit\nfi\n\nDBNAME=$1\nTABLE=$2\nFNAME=$1.$2.csv\nMCOMM=$3\n\necho \"MySQL password: \"\nstty -echo\nread PASS\nstty echo\n\nmysql -uroot -p$PASS $MCOMM $DBNAME -B -e \"SELECT * FROM $TABLE;\" | sed \"s/'/\\'/;s/\\t/\\\",\\\"/g;s/^/\\\"/;s/$/\\\"/;s/\\n//g\" > $FNAME\n"
},
{
"answer_id": 19310588,
"author": "mc0e",
"author_id": 2109800,
"author_profile": "https://Stackoverflow.com/users/2109800",
"pm_score": 5,
"selected": false,
"text": "mysql -B -e 'SELECT ...' mysql"
},
{
"answer_id": 23940122,
"author": "Denilson Sá Maia",
"author_id": 124946,
"author_profile": "https://Stackoverflow.com/users/124946",
"pm_score": 3,
"selected": false,
"text": "tee tee foobar.txt\nSELECT foo FROM bar;\n notee SELECT … INTO OUTFILE …;"
},
{
"answer_id": 25723906,
"author": "Indrajeet Singh",
"author_id": 2655396,
"author_profile": "https://Stackoverflow.com/users/2655396",
"pm_score": 0,
"selected": false,
"text": "SELECT 'Column1', 'Column2', 'Column3', 'Column4', 'Column5'\nUNION ALL\nSELECT column1, column2,\ncolumn3 , column4, column5 FROM demo\nINTO OUTFILE '/tmp/demo.csv'\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n';\n"
},
{
"answer_id": 26532440,
"author": "johntellsall",
"author_id": 143880,
"author_profile": "https://Stackoverflow.com/users/143880",
"pm_score": 3,
"selected": false,
"text": "mysql -B -D mydatabase -e 'select * from mytable'\n mysql -B -D mydatabase -e 'show tables'\n\nmysql -B -D mydatabase -e 'desc users'\n\nField Type Null Key Default Extra\nid int(11) NO PRI NULL auto_increment\nemail varchar(128) NO UNI NULL \nlastName varchar(100) YES NULL \ntitle varchar(128) YES UNI NULL \nuserName varchar(128) YES UNI NULL \nfirstName varchar(100) YES NULL \n"
},
{
"answer_id": 30536756,
"author": "Michael Cole",
"author_id": 1483977,
"author_profile": "https://Stackoverflow.com/users/1483977",
"pm_score": 3,
"selected": false,
"text": "mysql outfile php csvdump.php localhost root password database tablename > whatever-you-like.csv <?php\n\n$server = $argv[1];\n$user = $argv[2];\n$password = $argv[3];\n$db = $argv[4];\n$table = $argv[5];\n\nmysql_connect($server, $user, $password) or die(mysql_error());\nmysql_select_db($db) or die(mysql_error());\n\n// fetch the data\n$rows = mysql_query('SELECT * FROM ' . $table);\n$rows || die(mysql_error());\n\n\n// create a file pointer connected to the output stream\n$output = fopen('php://output', 'w');\n\n// output the column headings\n\n$fields = [];\nfor($i = 0; $i < mysql_num_fields($rows); $i++) {\n $field_info = mysql_fetch_field($rows, $i);\n $fields[] = $field_info->name;\n}\nfputcsv($output, $fields);\n\n// loop over the rows, outputting them\nwhile ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);\n\n?>\n"
},
{
"answer_id": 31043155,
"author": "Sri Murthy Upadhyayula",
"author_id": 1531606,
"author_profile": "https://Stackoverflow.com/users/1531606",
"pm_score": 5,
"selected": false,
"text": "mysql -h *hostname* -P *port number* --database=*database_name* -u *username* -p -e *your SQL query* | sed 's/\\t/\",\"/g;s/^/\"/;s/$/\"/;s/\\n//g' > *output_file_name.csv*\n"
},
{
"answer_id": 35086235,
"author": "hrvoj3e",
"author_id": 2450431,
"author_profile": "https://Stackoverflow.com/users/2450431",
"pm_score": 6,
"selected": false,
"text": "mysql -udemo_user -p -h127.0.0.1 --port=3306 \\\n --default-character-set=utf8mb4 --database=demo_database \\\n --batch --raw < /tmp/demo_sql_query.sql > /tmp/demo_csv_export.tsv\n tr '\\t' ',' < file.tsv > file.csv"
},
{
"answer_id": 35123787,
"author": "Chris Johnson",
"author_id": 763269,
"author_profile": "https://Stackoverflow.com/users/763269",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env python\n\nimport csv\nimport sys\n\ntab_in = csv.reader(sys.stdin, dialect=csv.excel_tab)\ncomma_out = csv.writer(sys.stdout, dialect=csv.excel)\n\nfor row in tab_in:\n comma_out.writerow(row)\n tab2csv mysql OTHER_OPTIONS --batch --execute='select * from whatever;' | tab2csv > outfile.csv\n"
},
{
"answer_id": 41840534,
"author": "Ben",
"author_id": 2958070,
"author_profile": "https://Stackoverflow.com/users/2958070",
"pm_score": 4,
"selected": false,
"text": ".csv import contextlib\nimport csv\nimport datetime\nimport os\n\n# https://github.com/PyMySQL/PyMySQL\nimport pymysql\n\nSQL_QUERY = \"\"\"\nSELECT * FROM my_table WHERE my_attribute = 'my_attribute';\n\"\"\"\n\n# embedding passwords in code gets nasty when you use version control\n# the environment is not much better, but this is an example\n# https://stackoverflow.com/questions/12461484\nSQL_USER = os.environ['SQL_USER']\nSQL_PASS = os.environ['SQL_PASS']\n\nconnection = pymysql.connect(host='localhost',\n user=SQL_USER,\n password=SQL_PASS,\n db='dbname')\n\nwith contextlib.closing(connection):\n with connection.cursor() as cursor:\n cursor.execute(SQL_QUERY)\n # Hope you have enough memory :)\n results = cursor.fetchall()\n\noutput_file = 'my_query-{}.csv'.format(datetime.datetime.today().strftime('%Y-%m-%d'))\nwith open(output_file, 'w', newline='') as csvfile:\n # http://stackoverflow.com/a/17725590/2958070 about lineterminator\n csv_writer = csv.writer(csvfile, lineterminator='\\n')\n csv_writer.writerows(results)\n"
},
{
"answer_id": 48241218,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "tr $ echo \"SELECT * FROM Table123\" | mysql Database456 | tr \"\\t\" ,\n"
},
{
"answer_id": 49049672,
"author": "minitauros",
"author_id": 2841607,
"author_profile": "https://Stackoverflow.com/users/2841607",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\n# $1 = query to execute\n# $2 = outfile\n# $3 = mysql database name\n# $4 = mysql username\n\nif [ -z \"$1\" ]; then\n echo \"Query not given\"\n exit 1\nfi\n\nif [ -z \"$2\" ]; then\n echo \"Outfile not given\"\n exit 1\nfi\n\nMYSQL_DB=\"\"\nMYSQL_USER=\"root\"\n\nif [ ! -z \"$3\" ]; then\n MYSQL_DB=$3\nfi\n\nif [ ! -z \"$4\" ]; then\n MYSQL_USER=$4\nfi\n\nif [ -z \"$MYSQL_DB\" ]; then\n echo \"Database name not given\"\n exit 1\nfi\n\nif [ -z \"$MYSQL_USER\" ]; then\n echo \"Database user not given\"\n exit 1\nfi\n\nmysql -u $MYSQL_USER -p -D $MYSQL_DB -B -s -e \"$1\" | sed \"s/'/\\'/;s/\\t/\\\",\\\"/g;s/^/\\\"/;s/$/\\\"/;s/\\n//g\" > $2\necho \"Written to $2\"\n"
},
{
"answer_id": 50333818,
"author": "Wolfgang Fahl",
"author_id": 1497139,
"author_profile": "https://Stackoverflow.com/users/1497139",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n#\n# Export MySQL data to CSV\n#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format\n#\n\n# ANSI colors\n#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html\nblue='\\033[0;34m'\nred='\\033[0;31m'\ngreen='\\033[0;32m' # '\\e[1;32m' is too bright for white bg.\nendColor='\\033[0m'\n\n#\n# A colored message\n# params:\n# 1: l_color - the color of the message\n# 2: l_msg - the message to display\n#\ncolor_msg() {\n local l_color=\"$1\"\n local l_msg=\"$2\"\n echo -e \"${l_color}$l_msg${endColor}\"\n}\n\n\n#\n# Error\n#\n# Show the given error message on standard error and exit\n#\n# Parameters:\n# 1: l_msg - the error message to display\n#\nerror() {\n local l_msg=\"$1\"\n # Use ANSI red for error\n color_msg $red \"Error:\" 1>&2\n color_msg $red \"\\t$l_msg\" 1>&2\n usage\n}\n\n#\n# Display usage\n#\nusage() {\n echo \"usage: $0 [-h|--help]\" 1>&2\n echo \" -o | --output csvdirectory\" 1>&2\n echo \" -d | --database database\" 1>&2\n echo \" -t | --tables tables\" 1>&2\n echo \" -p | --password password\" 1>&2\n echo \" -u | --user user\" 1>&2\n echo \" -hs | --host host\" 1>&2\n echo \" -gs | --get-schema\" 1>&2\n echo \"\" 1>&2\n echo \" output: output CSV directory to export MySQL data into\" 1>&2\n echo \"\" 1>&2\n echo \" user: MySQL user\" 1>&2\n echo \" password: MySQL password\" 1>&2\n echo \"\" 1>&2\n echo \" database: target database\" 1>&2\n echo \" tables: tables to export\" 1>&2\n echo \" host: host of target database\" 1>&2\n echo \"\" 1>&2\n echo \" -h|--help: show help\" 1>&2\n exit 1\n}\n\n#\n# show help\n#\nhelp() {\n echo \"$0 Help\" 1>&2\n echo \"===========\" 1>&2\n echo \"$0 exports a CSV file from a MySQL database optionally limiting to a list of tables\" 1>&2\n echo \" example: $0 --database=cms --user=scott --password=tiger --tables=person --output person.csv\" 1>&2\n echo \"\" 1>&2\n usage\n}\n\ndomysql() {\n mysql --host $host -u$user --password=$password $database\n}\n\ngetcolumns() {\n local l_table=\"$1\"\n echo \"describe $l_table\" | domysql | cut -f1 | grep -v \"Field\" | grep -v \"Warning\" | paste -sd \",\" - 2>/dev/null\n}\n\nhost=\"localhost\"\nmysqlfiles=\"/var/lib/mysql-files/\"\n\n# Parse command line options\nwhile true; do\n #echo \"option $1\"\n case \"$1\" in\n # Options without arguments\n -h|--help) usage;;\n -d|--database) database=\"$2\" ; shift ;;\n -t|--tables) tables=\"$2\" ; shift ;;\n -o|--output) csvoutput=\"$2\" ; shift ;;\n -u|--user) user=\"$2\" ; shift ;;\n -hs|--host) host=\"$2\" ; shift ;;\n -p|--password) password=\"$2\" ; shift ;;\n -gs|--get-schema) option=\"getschema\";;\n (--) shift; break;;\n (-*) echo \"$0: error - unrecognized option $1\" 1>&2; usage;;\n (*) break;;\n esac\n shift\ndone\n\n# Checks\nif [ \"$csvoutput\" == \"\" ]\nthen\n error \"output CSV directory is not set\"\nfi\nif [ \"$database\" == \"\" ]\nthen\n error \"MySQL database is not set\"\nfi\nif [ \"$user\" == \"\" ]\nthen\n error \"MySQL user is not set\"\nfi\nif [ \"$password\" == \"\" ]\nthen\n error \"MySQL password is not set\"\nfi\n\ncolor_msg $blue \"exporting tables of database $database\"\nif [ \"$tables\" = \"\" ]\nthen\ntables=$(echo \"show tables\" | domysql)\nfi\n\ncase $option in\n getschema)\n rm $csvoutput$database.schema\n for table in $tables\n do\n color_msg $blue \"getting schema for $table\"\n echo -n \"$table:\" >> $csvoutput$database.schema\n getcolumns $table >> $csvoutput$database.schema\n done\n ;;\n *)\nfor table in $tables\ndo\n color_msg $blue \"exporting table $table\"\n cols=$(grep \"$table:\" $csvoutput$database.schema | cut -f2 -d:)\n if [ \"$cols\" = \"\" ]\n then\n cols=$(getcolumns $table)\n fi\n ssh $host rm $mysqlfiles/$table.csv\ncat <<EOF | mysql --host $host -u$user --password=$password $database\nSELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n';\nEOF\n scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw\n (echo \"$cols\"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv\n rm $csvoutput$table.csv.raw\ndone\n ;;\nesac\n"
},
{
"answer_id": 50368244,
"author": "Hirnhamster",
"author_id": 413531,
"author_profile": "https://Stackoverflow.com/users/413531",
"pm_score": 2,
"selected": false,
"text": "mysql --file --query ./mysql2csv --file=\"/tmp/result.csv\" --query='SELECT 1 as foo, 2 as bar;' --user=\"username\" --password=\"password\"\n mysql2csv wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo \"b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65 mysql2csv\") || (echo \"ERROR comparing hash, Found:\" ;sha256sum mysql2csv) ) && chmod +x mysql2csv\n"
},
{
"answer_id": 52479705,
"author": "Ripudaman Singh",
"author_id": 4668446,
"author_profile": "https://Stackoverflow.com/users/4668446",
"pm_score": -1,
"selected": false,
"text": "mysql -h(hostname/IP>) -u(username) -p(password) databasename <(query.sql) > outputFILE(.txt/.xls)\n"
},
{
"answer_id": 53184408,
"author": "Rohit Chemburkar",
"author_id": 1268234,
"author_profile": "https://Stackoverflow.com/users/1268234",
"pm_score": 3,
"selected": false,
"text": "SELECT *\nFROM students\nWHERE foo = 'bar'\nLIMIT 0,1200000\nINTO OUTFILE './students-1200000.csv'\nFIELDS TERMINATED BY ',' ESCAPED BY '\"'\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\r\\n';\n SELECT id,name,CHAR_LENGTH(json_student_description) AS 'character length'\nFROM students\nWHERE CHAR_LENGTH(json_student_description)>32767;\n"
},
{
"answer_id": 57064471,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 2,
"selected": false,
"text": "mysql -B -C --raw -u 'username' --password='password' --host='hostname' 'databasename'\n-e 'SELECT\n CONCAT('\\''\"'\\'',REPLACE(`id`,'\\''\"'\\'', '\\''\"\"'\\''),'\\''\"'\\'') AS '\\''id'\\'',\n CONCAT('\\''\"'\\'',REPLACE(`value`,'\\''\"'\\'', '\\''\"\"'\\''),'\\''\"'\\'') AS '\\''value'\\''\n FROM sampledata'\n2>/dev/null | sqlite3 -csv -separator $'\\t' mydb.db '.import /dev/stdin mycsvtable'\n 2>/dev/null"
},
{
"answer_id": 58723076,
"author": "saran3h",
"author_id": 3520404,
"author_profile": "https://Stackoverflow.com/users/3520404",
"pm_score": -1,
"selected": false,
"text": "CONCAT as CSVFormat SELECT\n CONCAT(u.id,\n ',',\n given,\n ',',\n family,\n ',',\n email,\n ',',\n phone,\n ',',\n ua.street_number,\n ',',\n ua.route,\n ',',\n ua.locality,\n ',',\n ua.state,\n ',',\n ua.country,\n ',',\n ua.latitude,\n ',',\n ua.longitude) AS CSVFormat\nFROM\n table1 u\n LEFT JOIN\n table2 ua ON u.address_id = ua.id\nWHERE\n role_policy = 31 and is_active = 1;\n"
},
{
"answer_id": 59427693,
"author": "AAYUSH SHAH",
"author_id": 9082644,
"author_profile": "https://Stackoverflow.com/users/9082644",
"pm_score": 2,
"selected": false,
"text": "secure-file-priv C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads SELECT * FROM attendance INTO OUTFILE 'C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\FileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n'; \\ /"
},
{
"answer_id": 60030686,
"author": "Alex Ryan",
"author_id": 2341218,
"author_profile": "https://Stackoverflow.com/users/2341218",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nmysql --defaults-group-suffix=[DATABASE_NAME] --batch << EOF | python query.py\nSELECT [FIELDS]\nFROM [TABLE]\nEOF\n csv import sys\n\nfor line in sys.stdin:\n print(','.join([\"\\\"\" + str(element) + \"\\\"\" for element in line.rstrip('\\n').split('\\t')]))\n import csv, sys\n\ncsv_reader = csv.reader(sys.stdin, delimiter='\\t')\ncsv_writer = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC)\n\nfor line in csv_reader:\n csv_writer.writerow(line)\n import csv, sys\nimport pandas as pd\n\ndf = pd.read_csv(sys.stdin, sep='\\t')\ndf.to_csv(sys.stdout, index=False, quoting=csv.QUOTE_NONNUMERIC)\n"
},
{
"answer_id": 60247624,
"author": "Shenal Silva",
"author_id": 1318648,
"author_profile": "https://Stackoverflow.com/users/1318648",
"pm_score": 4,
"selected": false,
"text": "--csv mycli db_name --csv -e \"select * from flowers\" > flowers.csv\n"
},
{
"answer_id": 60842251,
"author": "Sudarshan",
"author_id": 4728918,
"author_profile": "https://Stackoverflow.com/users/4728918",
"pm_score": 0,
"selected": false,
"text": "Create VIEW v as (Select * from user where status = 0) view CSV Export method: Custom - display all possible options Put columns names in the first row"
},
{
"answer_id": 61029719,
"author": "Pranav",
"author_id": 11324471,
"author_profile": "https://Stackoverflow.com/users/11324471",
"pm_score": 0,
"selected": false,
"text": "import mysql.connector\nimport csv\n\ncon = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"Your Password\"\n)\n\ncur = con.cursor()\n\ncur.execute(\"USE DbName\")\ncur.execute(\"\"\"\nselect col1,col2 from table\nwhere <cond>\n\"\"\")\n\nwith open('Filename.csv',mode='w') as data:\n fieldnames=[\"Field1\",\"Field2\"]\n writer=csv.DictWriter(data,fieldnames=fieldnames)\n writer.writeheader()\n for i in cur:\n writer.writerow({'Field1':i[0],'Field2':i[1]})\n"
},
{
"answer_id": 63831142,
"author": "chrisinmtown",
"author_id": 1630244,
"author_profile": "https://Stackoverflow.com/users/1630244",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env python\nimport csv\nimport sys\n\n# fields are separated by tabs; double-quotes may occur anywhere\ncsv.register_dialect(\"mysql\", delimiter=\"\\t\", quoting=csv.QUOTE_NONE)\ntab_in = csv.reader(sys.stdin, dialect=\"mysql\")\ncomma_out = csv.writer(sys.stdout, dialect=csv.excel)\nfor row in tab_in:\n # print(\"row: {}\".format(row))\n comma_out.writerow(row)\n new-line character seen in unquoted field -\ndo you need to open the file in universal-newline mode?\n The reader is hard-coded to recognise either '\\r' or '\\n' as end-of-line,\nand ignores lineterminator.\n sed mysql -u user db --execute=\"select * from table where id=12345\" \\\n | sed -e 's/\\r/\\\\n/g' \\\n | mysqlTsvToCsv.py\n"
},
{
"answer_id": 63990228,
"author": "Md. Robi Ullah",
"author_id": 9877424,
"author_profile": "https://Stackoverflow.com/users/9877424",
"pm_score": 3,
"selected": false,
"text": "from table_name ..... INTO OUTFILE ..... SELECT *\nINTO OUTFILE '/Volumes/Development/sql/sql/enabled_contacts.csv'\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n'\nFROM table_name\nWHERE column_name = 'value'\n"
},
{
"answer_id": 67007702,
"author": "Archie",
"author_id": 263801,
"author_profile": "https://Stackoverflow.com/users/263801",
"pm_score": 0,
"selected": false,
"text": "expat NULL --xml \n// mysql-xml-to-csv.c\n\n#include <assert.h>\n#include <ctype.h>\n#include <err.h>\n#include <expat.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n/*\n Example of MySQL XML output:\n\n <?xml version=\"1.0\"?>\n\n <resultset xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" statement=\"SELECT id as IdNum, lastName, firstName FROM User\">\n <row>\n <field name=\"IdNum\">100040</field>\n <field name=\"lastName\" xsi:nil=\"true\"/>\n <field name=\"firsttName\">Cher</field>\n </row>\n </resultset>\n*/\n\n#define BUFFER_SIZE (1 << 16)\n\n// These accumulate the first row column names and values until first row is entirely read (unless the \"-N\" flag is given)\nstatic XML_Char **column_names;\nstatic size_t num_column_names;\nstatic XML_Char **first_row_values;\nstatic size_t num_first_row_values;\n\n// This accumulates one column's value\nstatic XML_Char *elem_text; // note: not nul-terminated\nstatic size_t elem_text_len;\n\n// Flags\nstatic int first_column;\nstatic int reading_value;\n\n// Expat callback functions\nstatic void handle_elem_start(void *data, const XML_Char *el, const XML_Char **attr);\nstatic void handle_elem_text(void *userData, const XML_Char *s, int len);\nstatic void handle_elem_end(void *data, const XML_Char *el);\n\n// Helper functions\nstatic void output_csv_row(XML_Char **values, size_t num);\nstatic void output_csv_text(const char *s, size_t len);\nstatic void add_string(XML_Char ***arrayp, size_t *lengthp, const XML_Char *string, size_t len);\nstatic void add_chars(XML_Char **strp, size_t *lenp, const XML_Char *string, size_t nchars);\nstatic size_t xml_strlen(const XML_Char *string);\nstatic void free_strings(XML_Char ***arrayp, size_t *lengthp);\nstatic void usage(void);\n\nint\nmain(int argc, char **argv)\n{\n char buf[BUFFER_SIZE];\n int want_column_names = 1;\n XML_Parser p;\n FILE *fp;\n size_t r;\n int i;\n\n // Parse command line\n while ((i = getopt(argc, argv, \"hN\")) != -1) {\n switch (i) {\n case 'N':\n want_column_names = 0;\n break;\n case 'h':\n usage();\n exit(0);\n case '?':\n default:\n usage();\n exit(1);\n }\n }\n argv += optind;\n argc -= optind;\n switch (argc) {\n case 0:\n fp = stdin;\n break;\n case 1:\n if ((fp = fopen(argv[0], \"r\")) == NULL)\n err(1, \"%s\", argv[0]);\n break;\n default:\n usage();\n exit(1);\n }\n\n // Initialize arrays for column names and first row values\n if (want_column_names) {\n if ((column_names = malloc(10 * sizeof(*column_names))) == NULL)\n err(1, \"malloc\");\n if ((first_row_values = malloc(10 * sizeof(*first_row_values))) == NULL)\n err(1, \"malloc\");\n }\n\n // Initialize parser\n if ((p = XML_ParserCreate(NULL)) == NULL)\n errx(1, \"can't initialize parser\");\n XML_SetElementHandler(p, handle_elem_start, handle_elem_end);\n XML_SetCharacterDataHandler(p, handle_elem_text);\n\n // Process file\n while (1) {\n if ((r = fread(buf, 1, sizeof(buf), fp)) == 0 && ferror(fp))\n errx(1, \"error reading input\");\n if (XML_Parse(p, buf, r, r == 0) == XML_STATUS_ERROR)\n errx(1, \"line %u: %s\", (unsigned int)XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p)));\n if (r == 0)\n break;\n }\n\n // Clean up\n XML_ParserFree(p);\n fclose(fp);\n\n // Done\n return 0;\n}\n\nstatic void\nhandle_elem_start(void *data, const XML_Char *name, const XML_Char **attr)\n{\n if (strcmp(name, \"row\") == 0)\n first_column = 1;\n else if (strcmp(name, \"field\") == 0) {\n if (column_names != NULL) {\n while (*attr != NULL && strcmp(*attr, \"name\") != 0)\n attr += 2;\n if (*attr == NULL)\n errx(1, \"\\\"field\\\" element is missing \\\"name\\\" attribute\");\n add_string(&column_names, &num_column_names, attr[1], xml_strlen(attr[1]));\n } else {\n if (!first_column)\n putchar(',');\n putchar('\"');\n }\n reading_value = 1;\n }\n}\n\nstatic void\nhandle_elem_text(void *userData, const XML_Char *s, int len)\n{\n if (!reading_value)\n return;\n if (column_names != NULL)\n add_chars(&elem_text, &elem_text_len, s, len);\n else\n output_csv_text(s, len);\n}\n\nstatic void\nhandle_elem_end(void *data, const XML_Char *name)\n{\n if (strcmp(name, \"row\") == 0) {\n if (column_names != NULL) {\n output_csv_row(column_names, num_column_names);\n output_csv_row(first_row_values, num_first_row_values);\n free_strings(&column_names, &num_column_names);\n free_strings(&first_row_values, &num_first_row_values);\n } else\n putchar('\\n');\n } else if (strcmp(name, \"field\") == 0) {\n if (column_names != NULL) {\n add_string(&first_row_values, &num_first_row_values, elem_text, elem_text_len);\n free(elem_text);\n elem_text = NULL;\n elem_text_len = 0;\n } else\n putchar('\"');\n first_column = 0;\n reading_value = 0;\n }\n}\n\nstatic void\noutput_csv_row(XML_Char **values, size_t num_columns)\n{\n int i;\n\n for (i = 0; i < num_columns; i++) {\n if (i > 0)\n putchar(',');\n putchar('\"');\n output_csv_text(values[i], xml_strlen(values[i]));\n putchar('\"');\n }\n putchar('\\n');\n}\n\nstatic void\noutput_csv_text(const XML_Char *s, size_t len)\n{\n while (len-- > 0) {\n if (*s == '\"')\n putchar('\"');\n putchar(*s);\n s++;\n }\n}\n\nstatic void\nadd_string(XML_Char ***arrayp, size_t *lengthp, const XML_Char *string, size_t nchars)\n{\n char **new_array;\n\n if ((new_array = realloc(*arrayp, (*lengthp + 1) * sizeof(**arrayp))) == NULL)\n err(1, \"malloc\");\n *arrayp = new_array;\n if (((*arrayp)[*lengthp] = malloc((nchars + 1) * sizeof(XML_Char))) == NULL)\n err(1, \"malloc\");\n memcpy((*arrayp)[*lengthp], string, nchars * sizeof(XML_Char));\n (*arrayp)[*lengthp][nchars] = (XML_Char)0;\n (*lengthp)++;\n}\n\nstatic void\nadd_chars(XML_Char **strp, size_t *lenp, const XML_Char *string, size_t nchars)\n{\n XML_Char *new_array;\n\n if ((new_array = realloc(*strp, (*lenp + nchars) * sizeof(XML_Char))) == NULL)\n err(1, \"malloc\");\n *strp = new_array;\n memcpy(*strp + *lenp, string, nchars * sizeof(XML_Char));\n *lenp += nchars;\n}\n\nstatic size_t\nxml_strlen(const XML_Char *string)\n{\n size_t len;\n\n len = 0;\n while (string[len] != (XML_Char)0)\n len++;\n return len;\n}\n\nstatic void\nfree_strings(char ***arrayp, size_t *lengthp)\n{\n while (*lengthp > 0)\n free((*arrayp)[--*lengthp]);\n free(*arrayp);\n *arrayp = NULL;\n}\n\nstatic void\nusage(void)\n{\n fprintf(stderr, \"Usage: mysql-xml-to-csv [options] [file.xml]\\n\");\n fprintf(stderr, \"Options:\\n\");\n fprintf(stderr, \" -N\\tDo not output column names as the first row\\n\");\n fprintf(stderr, \" -h\\tShow this usage info\\n\");\n}\n gcc mysql-xml-to-csv.c -lexpat -o mysql-xml-to-csv\n Update:"
},
{
"answer_id": 68639416,
"author": "Ken Arnold",
"author_id": 69707,
"author_profile": "https://Stackoverflow.com/users/69707",
"pm_score": 2,
"selected": false,
"text": "import csv\n\ndef export_table(connection, table_name, output_filename):\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM \" + table_name)\n\n # thanks to https://gist.github.com/madan712/f27ac3b703a541abbcd63871a4a56636 for this hint\n header = [descriptor[0] for descriptor in cursor.description]\n\n with open(output_filename, 'w') as csvfile:\n csv_writer = csv.writer(csvfile, dialect='excel')\n csv_writer.writerow(header)\n for row in cursor:\n csv_writer.writerow(row)\n import mysql.connector as mysql\n# (or https://github.com/PyMySQL/PyMySQL should work but I haven't tested it)\n\ndb = mysql.connect(\n host=\"localhost\",\n user=\"USERNAME\",\n db=\"DATABASE_NAME\",\n port=9999)\n\nfor table_name in ['table1', 'table2']:\n export_table(db, table_name, table_name + '.csv')\n\ndb.close()\n contextlib"
},
{
"answer_id": 70409179,
"author": "Majid Fouladpour",
"author_id": 66580,
"author_profile": "https://Stackoverflow.com/users/66580",
"pm_score": 0,
"selected": false,
"text": "--secure-file-priv INTO OUTFILE '/path/to/export.csv' CONCAT SELECT CONCAT(\n\"('\",\n`username`, \"', '\",\n`password`, \"', '\",\n`first_name`, \"', '\",\n`last_name`, \"', '\",\n`gender`, \"'),\"\n) AS `row` \nFROM `users`\nWHERE `role` != 'Not set'\nAND `user_status` = 'Active'\nORDER BY `role`, `gender`, `user_id`\nLIMIT 200\n ('jane', '3d7ff...', 'Jane', 'Doe', 'Female'), \n('john', 'd2a33...', 'John', 'Doe', 'Male'),\n...\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094969/"
] |
356,583 | <p>Is it possible to reflectively instantiate a generic type in Java? Using the technique described <a href="http://www.velocityreviews.com/forums/t149816-generics-and-forname.html" rel="noreferrer">here</a> I get an error because class tokens cannot be generic. Take the example below. I want to instantiate some subclass of Creator that implements Creator. The actual class name is passed in as a command line argument. The idea is to be able to specify an implementation of Creator at runtime. Is there another way to accomplish what I'm trying to do here?</p>
<pre><code>public interface Creator<T> {
T create();
}
public class StringCreator implements Creator<String> {
public String create() { return new String(); }
}
public class FancyStringCreator implements Creator<String> {
public String create() { return new StringBuffer().toString(); }
}
public static void main(String[] args) throws Exception {
Class<?> someClass = Class.forName(args[0]);
/*ERROR*/Class<? extends Creator<String>> creatorClass = someClass.asSubclass(Creator.class);
Constructor<? extends Creator<String>> creatorCtor = creatorClass.getConstructor((Class<?>[]) null);
Creator<String> creator = creatorCtor.newInstance((Object[]) null);
}
</code></pre>
<p>Edit: I like Marcus' approach as being the most simple and pragmatic without circumventing the whole generics thing. I can use it in my situation because I can specify that the class passed must be a subclass of StringCreator. But as Ericson pointed out the generic information is still there at the type level, just not at the runtime level so it is still possible to reflectively examine whether a given class implements the correct generic type.</p>
| [
{
"answer_id": 356596,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "public static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Creator<String> creator = (Creator<String>) someClass.newInstance();\n}\n public static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Class<? extends Creator> creatorClass = someClass.asSubclass(Creator.class);\n Constructor<? extends Creator> creatorCtor = creatorClass.getConstructor((Class<?>[]) null);\n Creator<String> creator = (Creator<String>) creatorCtor.newInstance((Object[]) null);\n}\n"
},
{
"answer_id": 356677,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": -1,
"selected": false,
"text": "create String public class IntegerCreator implements Creator<Integer> \n{\n public Integer create() \n { \n ...\n }\n}\n create"
},
{
"answer_id": 356910,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": " public static void main(String[] args)\n throws Exception\n {\n Class<? extends Creator<String>> clz = load(argv[0], String.class);\n Constructor<? extends Creator<String>> ctor = clz.getConstructor();\n Creator<String> creator = ctor.newInstance();\n System.out.println(creator.create());\n }\n\n public static <T> Class<? extends Creator<T>> load(String fqcn, Class<T> type)\n throws ClassNotFoundException\n {\n Class<?> any = Class.forName(fqcn);\n for (Class<?> clz = any; clz != null; clz = clz.getSuperclass()) {\n for (Object ifc : clz.getGenericInterfaces()) {\n if (ifc instanceof ParameterizedType) {\n ParameterizedType pType = (ParameterizedType) ifc;\n if (Creator.class.equals(pType.getRawType())) {\n if (!pType.getActualTypeArguments()[0].equals(type))\n throw new ClassCastException(\"Class implements \" + pType);\n /* We've done the necessary checks to show that this is safe. */\n @SuppressWarnings(\"unchecked\")\n Class<? extends Creator<T>> creator = (Class<? extends Creator<T>>) any;\n return creator;\n }\n }\n }\n }\n throw new ClassCastException(fqcn + \" does not implement Creator<String>\");\n }\n class MyCreator implements Creator<String> class GenericCreator<T> implements Creator<T> interface StringCreatorIfc extends Creator<String>"
},
{
"answer_id": 356932,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 5,
"selected": true,
"text": "public interface Creator<T> {\n T create();\n}\npublic interface StringCreator extends Creator<String> { }\npublic class StringCreatorImpl implements StringCreator {\n public String create() { return new String(); }\n}\npublic class FancyStringCreator implements StringCreator {\n public String create() { return new StringBuffer().toString(); }\n}\npublic static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Class<? extends StringCreator> creatorClass = someClass.asSubclass(StringCreator.class);\n Constructor<? extends StringCreator> creatorCtor = creatorClass.getConstructor((Class<?>[]) null);\n Creator<String> creator = creatorCtor.newInstance((Object[]) null);\n}\n public class AnotherCreator implements Creator<String> {\n public String create() { return \"\"; }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16399/"
] |
356,585 | <p>I have a program that needs to run as a separate NT user to connect to a SQL Server databases. For running a program itself, this isn't a big deal as I can just right click on it in windows explorer and select run as. Is there any way to run my tests as a different user as well? (it would be nice if I could do so in Visual Studio)</p>
<p><strong>Update</strong>: As of right now, I'm just unit testing using the integrated unit testing framework in Visual Studio 2008 Pro. I'm running them just using the "run all tests in current solution" menu option.</p>
| [
{
"answer_id": 356596,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "public static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Creator<String> creator = (Creator<String>) someClass.newInstance();\n}\n public static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Class<? extends Creator> creatorClass = someClass.asSubclass(Creator.class);\n Constructor<? extends Creator> creatorCtor = creatorClass.getConstructor((Class<?>[]) null);\n Creator<String> creator = (Creator<String>) creatorCtor.newInstance((Object[]) null);\n}\n"
},
{
"answer_id": 356677,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": -1,
"selected": false,
"text": "create String public class IntegerCreator implements Creator<Integer> \n{\n public Integer create() \n { \n ...\n }\n}\n create"
},
{
"answer_id": 356910,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": " public static void main(String[] args)\n throws Exception\n {\n Class<? extends Creator<String>> clz = load(argv[0], String.class);\n Constructor<? extends Creator<String>> ctor = clz.getConstructor();\n Creator<String> creator = ctor.newInstance();\n System.out.println(creator.create());\n }\n\n public static <T> Class<? extends Creator<T>> load(String fqcn, Class<T> type)\n throws ClassNotFoundException\n {\n Class<?> any = Class.forName(fqcn);\n for (Class<?> clz = any; clz != null; clz = clz.getSuperclass()) {\n for (Object ifc : clz.getGenericInterfaces()) {\n if (ifc instanceof ParameterizedType) {\n ParameterizedType pType = (ParameterizedType) ifc;\n if (Creator.class.equals(pType.getRawType())) {\n if (!pType.getActualTypeArguments()[0].equals(type))\n throw new ClassCastException(\"Class implements \" + pType);\n /* We've done the necessary checks to show that this is safe. */\n @SuppressWarnings(\"unchecked\")\n Class<? extends Creator<T>> creator = (Class<? extends Creator<T>>) any;\n return creator;\n }\n }\n }\n }\n throw new ClassCastException(fqcn + \" does not implement Creator<String>\");\n }\n class MyCreator implements Creator<String> class GenericCreator<T> implements Creator<T> interface StringCreatorIfc extends Creator<String>"
},
{
"answer_id": 356932,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 5,
"selected": true,
"text": "public interface Creator<T> {\n T create();\n}\npublic interface StringCreator extends Creator<String> { }\npublic class StringCreatorImpl implements StringCreator {\n public String create() { return new String(); }\n}\npublic class FancyStringCreator implements StringCreator {\n public String create() { return new StringBuffer().toString(); }\n}\npublic static void main(String[] args) throws Exception {\n Class<?> someClass = Class.forName(args[0]);\n Class<? extends StringCreator> creatorClass = someClass.asSubclass(StringCreator.class);\n Constructor<? extends StringCreator> creatorCtor = creatorClass.getConstructor((Class<?>[]) null);\n Creator<String> creator = creatorCtor.newInstance((Object[]) null);\n}\n public class AnotherCreator implements Creator<String> {\n public String create() { return \"\"; }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
356,598 | <p>Is there a way for me to delete items from calendar by using iCalendar import?</p>
<p>I know that there is a METHOD:CANCEL, however when I tried it, it didn't do anything to the calendar event.</p>
<p>Here is what is in my iCalendar file. When I try to import it to Outlook, it just adds these events.</p>
<pre><code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//DDay.iCal//NONSGML ddaysoftware.com//EN
METHOD:CANCEL
BEGIN:VEVENT
CREATED:20081210T155315Z
DESCRIPTION:
DTEND:20081213T093000
DTSTAMP:20081210T155315Z
DTSTART:20081213T093000
LOCATION:
ORGANIZER:MAILTO:user@domain.com
SEQUENCE:1
SUMMARY:From FCS 13th
UID:20367b86-2123-4930-87ef-5c2a6626bd9f
BEGIN:VALARM
ACTION:DISPLAY
SUMMARY: Event 13th
TRIGGER:-PT30M
END:VALARM
END:VEVENT
BEGIN:VEVENT
CREATED:20081210T155315Z
DESCRIPTION:
DTEND:20081211T093000
DTSTAMP:20081210T155315Z
DTSTART:20081211T093000
LOCATION:7 West
ORGANIZER:MAILTO:user@domain.com
SEQUENCE:1
SUMMARY:Event 11th
UID:f212ab15-86c3-46c8-8592-af0716a40ea2
BEGIN:VALARM
ACTION:DISPLAY
SUMMARY:Event on 11th
TRIGGER:-PT30M
END:VALARM
END:VEVENT
END:VCALENDAR
</code></pre>
| [
{
"answer_id": 357641,
"author": "dev.e.loper",
"author_id": 37759,
"author_profile": "https://Stackoverflow.com/users/37759",
"pm_score": 5,
"selected": true,
"text": "STATUS:CANCELLED BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//DDay.iCal//NONSGML ddaysoftware.com//EN\nX-WR-RELCALID:928C8448-048A-4aa2-BE27-A920773AF3DC\nMETHOD:CANCEL\nBEGIN:VEVENT\nCREATED:20081210T210344Z\nDESCRIPTION:\nDTEND:20081213T093000\nDTSTAMP:20081210T210344Z\nDTSTART:20081213T093000\nLOCATION:\nORGANIZER:MAILTO:user@domain.com\nSEQUENCE:1\nSTATUS:CANCELLED\nSUMMARY:Event to export 1\nUID:20367b86-2123-4930-87ef-5c2a6626bd9f\nBEGIN:VALARM\nACTION:DISPLAY\nSUMMARY:Event to export 1\nTRIGGER:-PT30M\nEND:VALARM\nEND:VEVENT\nBEGIN:VEVENT\nCREATED:20081210T210344Z\nDESCRIPTION:\nDTEND:20081211T093000\nDTSTAMP:20081210T210344Z\nDTSTART:20081211T093000\nLOCATION:7 West\nORGANIZER:MAILTO:user@domain.com\nSEQUENCE:1\nSTATUS:CANCELLED\nSUMMARY:Event to export 2\nUID:f212ab15-86c3-46c8-8592-af0716a40ea2\nBEGIN:VALARM\nACTION:DISPLAY\nSUMMARY:Event to export 2\nTRIGGER:-PT30M\nEND:VALARM\nEND:VEVENT\nEND:VCALENDAR\n"
},
{
"answer_id": 6941023,
"author": "Marc",
"author_id": 878534,
"author_profile": "https://Stackoverflow.com/users/878534",
"pm_score": 1,
"selected": false,
"text": "X-WR-RELCALID"
},
{
"answer_id": 24391112,
"author": "bbsimonbb",
"author_id": 1585345,
"author_profile": "https://Stackoverflow.com/users/1585345",
"pm_score": 2,
"selected": false,
"text": "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//www.notilus.com//Dimo Gestion Notilus//FR\nCALSCALE:GREGORIAN\nMETHOD:CANCEL\nBEGIN:VEVENT\nDTSTART:20140625T123000Z\nSEQUENCE:1\nSTATUS:CANCELLED\nUID:Kerry\nEND:VEVENT\nEND:VCALENDAR\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37759/"
] |
356,616 | <p>In my Java application I would like to download a JPEG, transfer it to a PNG and do something with the resulting bytes.</p>
<p>I am almost certain I remember a library to do this exists, I cannot remember its name.</p>
| [
{
"answer_id": 356635,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 4,
"selected": false,
"text": "File file = new File(\"newimage.png\");\nImageIO.write(myJpegImage, \"png\", file);\n"
},
{
"answer_id": 356637,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 5,
"selected": true,
"text": "ByteArrayOutputStream"
},
{
"answer_id": 356650,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 5,
"selected": false,
"text": "// these are the imports needed\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport javax.imageio.ImageIO;\nimport java.io.ByteArrayOutputStream;\n\n// read a jpeg from a inputFile\nBufferedImage bufferedImage = ImageIO.read(new File(inputFile));\n\n// write the bufferedImage back to outputFile\nImageIO.write(bufferedImage, \"png\", new File(outputFile));\n\n// this writes the bufferedImage into a byte array called resultingBytes\nByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();\nImageIO.write(bufferedImage, \"png\", byteArrayOut);\nbyte[] resultingBytes = byteArrayOut.toByteArray();\n"
},
{
"answer_id": 26311908,
"author": "waviq",
"author_id": 4131691,
"author_profile": "https://Stackoverflow.com/users/4131691",
"pm_score": 0,
"selected": false,
"text": "BufferedImage bufferGambar;\ntry {\n\n bufferGambar = ImageIO.read(new File(\"ImagePNG.png\"));\n // pkai type INT karna bertipe integer RGB bufferimage\n BufferedImage newBufferGambar = new BufferedImage(bufferGambar.getWidth(), bufferGambar.getHeight(), BufferedImage.TYPE_INT_RGB);\n\n newBufferGambar.createGraphics().drawImage(bufferGambar, 0, 0, Color.white, null);\n ImageIO.write(newBufferGambar, \"jpg\", new File(\"Create file JPEG.jpg\"));\n\n JOptionPane.showMessageDialog(null, \"Convert to JPG succes YES\");\n\n} catch(Exception e) {\n JOptionPane.showMessageDialog(null, e);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
356,645 | <p>I have a dynamic query that returns around 590,000 records. It runs successfully the first time, but if I run it again, I keep getting a <code>System.OutOfMemoryException</code>. What are some reasons this could be happening?</p>
<p>The error is happening here:</p>
<pre><code> public static DataSet GetDataSet(string databaseName,string
storedProcedureName,params object[] parameters)
{
//Creates blank dataset
DataSet ds = null;
try
{
//Creates database
Database db = DatabaseFactory.CreateDatabase(databaseName);
//Creates command to execute
DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName);
dbCommand.CommandTimeout = COMMAND_TIMEOUT;
//Returns the list of SQL parameters associated with that stored proecdure
db.DiscoverParameters(dbCommand);
int i = 1;
//Loop through the list of parameters and set the values
foreach (object parameter in parameters)
{
dbCommand.Parameters[i++].Value = parameter;
}
//Retrieve dataset and set to ds
ds = db.ExecuteDataSet(dbCommand);
}
//Check for exceptions
catch (SqlException sqle)
{
throw sqle;
}
catch (Exception e)
{
throw e; // Error is thrown here.
}
//Returns dataset
return ds;
}
</code></pre>
<p>Here is the code the runs on the button click:</p>
<pre><code>protected void btnSearchSBIDatabase_Click(object sender, EventArgs e)
{
LicenseSearch ls = new LicenseSearch();
DataTable dtSearchResults = new DataTable();
dtSearchResults = ls.Search();
Session["dtSearchResults"] = dtSearchResults;
Response.Redirect("~/FCCSearch/SearchResults.aspx");
}
else
lblResults.Visible = true;
}
</code></pre>
| [
{
"answer_id": 356798,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 6,
"selected": true,
"text": "GC.Collect() GC.Collect()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
356,666 | <p>Is there a "win64" identifier in Qmake project files? <a href="http://doc.trolltech.com/4.4/qmake-advanced-usage.html" rel="noreferrer">Qt Qmake advanced</a> documentation does not mention other than unix / macx / win32.</p>
<p>So far I've tried using:</p>
<pre><code>win32:message("using win32")
win64:message("using win64")
amd64:message("using amd64")
</code></pre>
<p>The result is always "using win32".</p>
<p>Must I use a separate project-file for x32 and x64 projects, so they would compile against correct libraries? Is there any other way to identify between 32-bit and 64-bit environments?</p>
| [
{
"answer_id": 404803,
"author": "Tuminoid",
"author_id": 40657,
"author_profile": "https://Stackoverflow.com/users/40657",
"pm_score": 2,
"selected": false,
"text": "CONFIG(myX64, myX64|myX32) {\n LIBPATH += C:\\Coding\\MSSDK60A\\Lib\\x64\n} else {\n LIBPATH += C:\\Coding\\MSSDK60A\\Lib\n}\n qmake qmake CONFIG+=myX64\n"
},
{
"answer_id": 2658176,
"author": "did",
"author_id": 319184,
"author_profile": "https://Stackoverflow.com/users/319184",
"pm_score": 6,
"selected": true,
"text": "win32 {\n\n ## Windows common build here\n\n !contains(QMAKE_TARGET.arch, x86_64) {\n message(\"x86 build\")\n\n ## Windows x86 (32bit) specific build here\n\n } else {\n message(\"x86_64 build\")\n\n ## Windows x64 (64bit) specific build here\n\n }\n}\n"
},
{
"answer_id": 2704073,
"author": "rubenvb",
"author_id": 256138,
"author_profile": "https://Stackoverflow.com/users/256138",
"pm_score": 4,
"selected": false,
"text": "win32-g++:contains(QMAKE_HOST.arch, x86_64):{\n do something\n}\n"
},
{
"answer_id": 30723860,
"author": "Nejat",
"author_id": 3049264,
"author_profile": "https://Stackoverflow.com/users/3049264",
"pm_score": 5,
"selected": false,
"text": "QT_ARCH i386 x86_64 contains(QT_ARCH, i386) {\n message(\"32-bit\")\n} else {\n message(\"64-bit\")\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40657/"
] |
356,671 | <p>The <code>JFileChooser</code> seems to be missing a feature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get replaced when the user starts typing).</p>
<p>Is there a way around this?</p>
| [
{
"answer_id": 356706,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 8,
"selected": true,
"text": "setSelectedFile JFileChooser jFileChooser = new JFileChooser();\njFileChooser.setSelectedFile(new File(\"fileToSave.txt\"));\njFileChooser.showSaveDialog(parent);\n JFileChooser"
},
{
"answer_id": 6652416,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 1,
"selected": false,
"text": "dialog.getUI().setFileName( name )\n FILES_ONLY FILES_AND_DIRECTORIES DIRECTORIES_ONLY setSelectedFile()"
},
{
"answer_id": 9119414,
"author": "Erik Martino",
"author_id": 679892,
"author_profile": "https://Stackoverflow.com/users/679892",
"pm_score": 2,
"selected": false,
"text": "try {\n FileChooserUI fcUi = fileChooser.getUI();\n fcUi.setSelectedFile(defaultDir);\n Class<? extends FileChooserUI> fcClass = fcUi.getClass();\n Method setFileName = fcClass.getMethod(\"setFileName\", String.class);\n setFileName.invoke(fcUi, defaultDir.getName());\n} catch (Exception e) {\n e.printStackTrace();\n}\n setFileName"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] |
356,674 | <p>I'm developing my first ASP.NET MVC application. This application tracks events, users, donors, etc. for a charitable organization. In my events controller I support standard CRUD operations with New/Edit/Show views (delete is done via a button on Show view). But I also want to list all of the events.</p>
<p>Is it better to have a List view that you navigate to from an Index view or have the "List" view be the Index view. The Index view is my default view for the controller. If you keep Index/List separate, what would you put in the Index view?</p>
<p>Right now I'm leaning toward keeping them separate and putting basic help information on the Index view. Should I consider changing this and have the List view become the default view and rename Index to Help?</p>
<p>TIA for the collective wisdom of SO.</p>
| [
{
"answer_id": 357002,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 0,
"selected": false,
"text": "<body>\n <% RenderPartial(\"List\", \"Events\") %>\n</body>\n /Views/Events/List.ascx\n"
},
{
"answer_id": 586211,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": true,
"text": "public ActionResult Index()\n{\n return RedirectToAction( \"List\" );\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12950/"
] |
356,675 | <p>I have a query which is meant to show me any rows in table A which have not been updated recently enough. (Each row should be updated within 2 months after "month_no".):</p>
<pre><code>SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier
AND MONTH_NO > UPD_DATE
</code></pre>
<p>The last line in the WHERE clause causes an "ORA-00904 Invalid Identifier" error. Needless to say, I don't want to repeat the entire DECODE function in my WHERE clause. Any thoughts? (Both fixes and workarounds accepted...)</p>
| [
{
"answer_id": 356699,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 8,
"selected": true,
"text": "SELECT * FROM\n(\n SELECT A.identifier\n , A.name\n , TO_NUMBER(DECODE( A.month_no\n , 1, 200803 \n , 2, 200804 \n , 3, 200805 \n , 4, 200806 \n , 5, 200807 \n , 6, 200808 \n , 7, 200809 \n , 8, 200810 \n , 9, 200811 \n , 10, 200812 \n , 11, 200701 \n , 12, 200702\n , NULL)) as MONTH_NO\n , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE\n FROM table_a A\n , table_b B\n WHERE A.identifier = B.identifier\n) AS inner_table\nWHERE \n MONTH_NO > UPD_DATE\n"
},
{
"answer_id": 1574334,
"author": "James",
"author_id": 190819,
"author_profile": "https://Stackoverflow.com/users/190819",
"pm_score": 4,
"selected": false,
"text": "HAVING"
},
{
"answer_id": 8754376,
"author": "me_an",
"author_id": 1013810,
"author_profile": "https://Stackoverflow.com/users/1013810",
"pm_score": 4,
"selected": false,
"text": " SELECT A.identifier\n , A.name\n , TO_NUMBER(DECODE( A.month_no\n , 1, 200803 \n , 2, 200804 \n , 3, 200805 \n , 4, 200806 \n , 5, 200807 \n , 6, 200808 \n , 7, 200809 \n , 8, 200810 \n , 9, 200811 \n , 10, 200812 \n , 11, 200701 \n , 12, 200702\n , NULL)) as MONTH_NO\n , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE\nFROM table_a A, table_b B\nWHERE .identifier = B.identifier\nHAVING MONTH_NO > UPD_DATE\n"
},
{
"answer_id": 42218778,
"author": "J-Alex",
"author_id": 5898696,
"author_profile": "https://Stackoverflow.com/users/5898696",
"pm_score": 2,
"selected": false,
"text": "WITH inner_table AS\n(SELECT A.identifier\n , A.name\n , TO_NUMBER(DECODE( A.month_no\n , 1, 200803 \n , 2, 200804 \n , 3, 200805 \n , 4, 200806 \n , 5, 200807 \n , 6, 200808 \n , 7, 200809 \n , 8, 200810 \n , 9, 200811 \n , 10, 200812 \n , 11, 200701 \n , 12, 200702\n , NULL)) as MONTH_NO\n , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE\n FROM table_a A\n , table_b B\n WHERE A.identifier = B.identifier)\n\n SELECT * FROM inner_table \n WHERE MONTH_NO > UPD_DATE\n CREATE OR REPLACE VIEW_1 AS (SELECT ...);\nSELECT * FROM VIEW_1;\n"
},
{
"answer_id": 49879308,
"author": "Peter Aylett",
"author_id": 9583906,
"author_profile": "https://Stackoverflow.com/users/9583906",
"pm_score": 1,
"selected": false,
"text": "SELECT A.identifier\n , A.name\n , vars.MONTH_NO\n , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE\nFROM table_a A\n , table_b B ON A.identifier = B.identifier\nOUTER APPLY (\n SELECT\n -- variables\n MONTH_NO = TO_NUMBER(DECODE( A.month_no\n , 1, 200803 \n , 2, 200804 \n , 3, 200805 \n , 4, 200806 \n , 5, 200807 \n , 6, 200808 \n , 7, 200809 \n , 8, 200810 \n , 9, 200811 \n , 10, 200812 \n , 11, 200701 \n , 12, 200702\n , NULL))\n) vars\nWHERE vars.MONTH_NO > UPD_DATE\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] |
356,693 | <p>I was curious if there's a .Net API that would allow me to identify what updates are pending for "Windows Update,"</p>
<p>failing that, is there a windows powershell command that can get it?</p>
| [
{
"answer_id": 361722,
"author": "Andy Schneider",
"author_id": 45571,
"author_profile": "https://Stackoverflow.com/users/45571",
"pm_score": 2,
"selected": false,
"text": "PS C:\\> $updateSession = new-object -com Microsoft.update.Session\nPS C:\\> $updateSession | get-member\n\n\n TypeName: System.__ComObject#{918efd1e-b5d8-4c90-8540-aeb9bdc56f9d}\n\nName MemberType Definition\n---- ---------- ----------\nCreateUpdateDownloader Method IUpdateDownloader CreateUpdateDownloader ()\nCreateUpdateInstaller Method IUpdateInstaller CreateUpdateInstaller ()\nCreateUpdateSearcher Method IUpdateSearcher CreateUpdateSearcher ()\nCreateUpdateServiceManager Method IUpdateServiceManager2 CreateUpdateServiceManager ()\nQueryHistory Method IUpdateHistoryEntryCollection QueryHistory (string, int, int)\nClientApplicationID Property string ClientApplicationID () {get} {set}\nReadOnly Property bool ReadOnly () {get}\nUserLocale Property uint UserLocale () {get} {set}\nWebProxy Property IWebProxy WebProxy () {get} {set}\n\n\nPS C:\\> $searcher = $updateSession.CreateUpdateSearcher()\nPS C:\\> $searcher | gm\n\n\n TypeName: System.__ComObject#{04c6895d-eaf2-4034-97f3-311de9be413a}\n\nName MemberType Definition\n---- ---------- ----------\nBeginSearch Method ISearchJob BeginSearch (string, IUnknown, Variant)\nEndSearch Method ISearchResult EndSearch (ISearchJob)\nEscapeString Method string EscapeString (string)\nGetTotalHistoryCount Method int GetTotalHistoryCount ()\nQueryHistory Method IUpdateHistoryEntryCollection QueryHistory (int, int)\nSearch Method ISearchResult Search (string)\nCanAutomaticallyUpgradeService Property bool CanAutomaticallyUpgradeService () {get} {set}\nClientApplicationID Property string ClientApplicationID () {get} {set}\nIgnoreDownloadPriority Property bool IgnoreDownloadPriority () {get} {set}\nIncludePotentiallySupersededUpdates Property bool IncludePotentiallySupersededUpdates () {get} {set}\nOnline Property bool Online () {get} {set}\nSearchScope Property SearchScope SearchScope () {get} {set}\nServerSelection Property ServerSelection ServerSelection () {get} {set}\nServiceID Property string ServiceID () {get} {set}\n\n\nPS C:\\>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32238/"
] |
356,705 | <p>I wish to send a header to my Apache server on a Linux box. How can I achieve this via a cURL call?</p>
| [
{
"answer_id": 356714,
"author": "Tader",
"author_id": 30700,
"author_profile": "https://Stackoverflow.com/users/30700",
"pm_score": 11,
"selected": false,
"text": "man curl -H/--header <header>\n (HTTP) Extra header to use when getting a web page. You may specify\n any number of extra headers. Note that if you should add a custom\n header that has the same name as one of the internal ones curl would\n use, your externally set header will be used instead of the internal\n one. This allows you to make even trickier stuff than curl would\n normally do. You should not replace internally set headers without\n knowing perfectly well what you're doing. Remove an internal header\n by giving a replacement without content on the right side of the\n colon, as in: -H \"Host:\".\n\n curl will make sure that each header you add/replace get sent with\n the proper end of line marker, you should thus not add that as a\n part of the header content: do not add newlines or carriage returns\n they will only mess things up for you.\n\n See also the -A/--user-agent and -e/--referer options.\n\n This option can be used multiple times to add/replace/remove multi-\n ple headers.\n curl --header \"X-MyHeader: 123\" www.google.com\n curl --header \"Accept: text/javascript\" --header \"X-Test: hello\" -v www.google.com\n -v"
},
{
"answer_id": 356716,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 6,
"selected": false,
"text": "-H or --header"
},
{
"answer_id": 2570832,
"author": "James",
"author_id": 304079,
"author_profile": "https://Stackoverflow.com/users/304079",
"pm_score": 8,
"selected": false,
"text": "curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue'));\n curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName:HeaderValue', 'HeaderName2:HeaderValue2'));\n"
},
{
"answer_id": 19217512,
"author": "Randhi Rupesh",
"author_id": 2056844,
"author_profile": "https://Stackoverflow.com/users/2056844",
"pm_score": 11,
"selected": true,
"text": "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" http://hostname/resource\n curl -H \"Accept: application/xml\" -H \"Content-Type: application/xml\" -X GET http://hostname/resource\n curl --data \"param1=value1¶m2=value2\" http://hostname/resource\n curl --form \"fileupload=@filename.txt\" http://hostname/resource\n curl -X POST -d @filename http://hostname/resource\n curl -d \"username=admin&password=admin&submit=Login\" --dump-header headers http://localhost/Login\ncurl -L -b headers http://localhost/\n"
},
{
"answer_id": 32362678,
"author": "Graham Perks",
"author_id": 434004,
"author_profile": "https://Stackoverflow.com/users/434004",
"pm_score": 3,
"selected": false,
"text": "http http://myurl HeaderName:value\n"
},
{
"answer_id": 33121935,
"author": "Vietnhi Phuvan",
"author_id": 2187089,
"author_profile": "https://Stackoverflow.com/users/2187089",
"pm_score": 6,
"selected": false,
"text": "curl -X GET \"http://localhost:3000/action?result1=gh&result2=ghk\"\n curl --request GET \"http://localhost:3000/action?result1=gh&result2=ghk\"\n curl \"http://localhost:3000/action?result1=gh&result2=ghk\"\n curl -i -H \"Application/json\" -H \"Content-type: application/json\" \"http://localhost:3000/action?result1=gh&result2=ghk\"\n"
},
{
"answer_id": 45588068,
"author": "Palsri",
"author_id": 3687472,
"author_profile": "https://Stackoverflow.com/users/3687472",
"pm_score": 3,
"selected": false,
"text": "curl -v -H @{'custom_header'='custom_header_value'} http://localhost:3000/action?result1=gh&result2=ghk\n"
},
{
"answer_id": 54081490,
"author": "Manuel Pirez",
"author_id": 4221435,
"author_profile": "https://Stackoverflow.com/users/4221435",
"pm_score": 5,
"selected": false,
"text": "curl -X POST(Get or whatever) \\\n http://your_url.com/api/endpoint \\\n -H 'Content-Type: application/json' \\\n -H 'header-element1: header-data1' \\\n -H 'header-element2: header-data2' \\\n -d '{\n \"JsonExArray\": [\n {\n \"json_prop\": \"1\",\n },\n {\n \"json_prop\": \"2\",\n }\n ]\n}'\n"
},
{
"answer_id": 60210041,
"author": "DINA TAKLIT",
"author_id": 9039646,
"author_profile": "https://Stackoverflow.com/users/9039646",
"pm_score": 3,
"selected": false,
"text": "curl.exe http://127.0.0.1:5000/books \n curl.exe http://127.0.0.1:5000/books/8 -X PATCH -H \"Content-Type: application/json\" -d '{\\\"rating\\\":\\\"2\\\"}' \n Failed to decode JSON object: Expecting value: line 1 column 1 (char 0) curl.exe curl Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the \"Content-Type: application/json\" value of type\n\"System.String\" to type \"System.Collections.IDictionary\".\nAt line:1 char:48\n+ ... 0.1:5000/books/8 -X PATCH -H \"Content-Type: application/json\" -d '{\\\" ...\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException\n + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand\n"
},
{
"answer_id": 70682228,
"author": "Sanjay Bharwani",
"author_id": 1503163,
"author_profile": "https://Stackoverflow.com/users/1503163",
"pm_score": 2,
"selected": false,
"text": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Document\n@Validated\npublic class Movie {\n @Id\n private String id;\n private String name;\n @NotNull\n private Integer year;\n @NotNull\n private List<String> cast;\n private LocalDate release_date;\n}\n curl -i \\\n-d '{\"id\":1, \"name\": \"Dhoom\", \"year\":2004,\"cast\":[\"John Abraham\", \"Abhishek Bachan\"],\"release_date\": \"2004-06-15\"}' \\\n-H \"Content-Type: application/json\" \\\n-X POST http://localhost:8080/v1/movies\n curl -i http://localhost:8080/v1/movies\n curl -i http://localhost:8080/v1/movies/1\n curl -i \\\n-d '{\"id\":1, \"name\": \"Dhoom\", \"year\":2005,\"cast\":[\"John Abhraham\", \"Abhishek Bachhan\", \"Uday Chopra\", \"Isha Deol\"],\"release_date\": \"2005-03-25\"}' \\\n-H \"Content-Type: application/json\" \\\n-X PUT http://localhost:8080/v1/movies/1\n curl -i -X DELETE http://localhost:8080/v1/movies/1\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| [
{
"answer_id": 356782,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": -1,
"selected": false,
"text": "def __init__(self, r = 0, g = 0, b = 0):\n # if r is a list\n if (type(r) == type([1,2,3])):\n r, g, b = r[0], r[1], r[2]\n # if r is a color\n if (type(r) == type(self)):\n r, g, b = r.r, r.g, r.b\n self.r = r\n self.g = g\n self.b = b\n"
},
{
"answer_id": 356820,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 4,
"selected": false,
"text": "Color(r, g, b)\nColor(*[r, g, b])\nColor(**{'r': r, 'g': g, 'b': b})\n Color(*Color2.as_list())\n"
},
{
"answer_id": 357004,
"author": "Brandon",
"author_id": 28916,
"author_profile": "https://Stackoverflow.com/users/28916",
"pm_score": 3,
"selected": false,
"text": "class Color (object):\n\n def __init__(self, **parms):\n if parms.get('list'):\n self.r, self.g, self.b = parms['list'] \n elif parms.get('color'):\n color = parms['color']\n self.r = color.r\n self.g = color.g\n self.b = color.b\n else:\n self.r = parms['red']\n self.g = parms['green']\n self.b = parms['blue']\n\nc1 = Color(red=220, green=0, blue=270)\nc2 = Color(list=[220, 0, 70])\nc3 = Color(color=c1)\n"
},
{
"answer_id": 357006,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 0,
"selected": false,
"text": "def function(*args):\n if type(args[0]) is int:\n dothis()\n #and so on\n"
},
{
"answer_id": 357256,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": true,
"text": "@classmethod"
},
{
"answer_id": 357288,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "__add__ isinstance def __add__(self, other):\n if isinstance(other, Color):\n ...\n elif isinstance(other, (int, long)):\n ...\n elif len(other) == 3 and all(isinstance(e, (int, long)) for e in other):\n ...\n else:\n raise TypeError(\"Can only add Color to Color, int or three-tuple\")\n __radd__ 1 + Color(1, 2, 3)\n def __radd__(self, other):\n return self.__add__(other)\n type(other) is Color __iadd__ +="
},
{
"answer_id": 7781667,
"author": "Jürgen Strobel",
"author_id": 833402,
"author_profile": "https://Stackoverflow.com/users/833402",
"pm_score": 1,
"selected": false,
"text": "def __init__(self, method, *args, **kw):\n getattr(self, '_init_'+method)(*args, **kw)\n\ndef _init_coponents(self, r, g, b):\n ...\ndef _init_fromColor(self, color):\n ...\n c1 = Color('components', 0, 0, 0,)\nc2 = Color('fromColor', c1)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11666/"
] |
356,722 | <p>I have a defunct process on my system:</p>
<pre><code>abc 22093 19508 0 23:29 pts/4 00:00:00 grep ProcA
abc 31756 1 0 Dec08 ? 00:00:00 [ProcA_my_collect] <defunct>
</code></pre>
<p>How can I kill the above process, without a reboot of the machine? I have tried with</p>
<pre><code>kill -9 31756
sudo kill -9 31756
</code></pre>
| [
{
"answer_id": 356899,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 5,
"selected": false,
"text": "ps -ef --forest"
},
{
"answer_id": 357018,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": true,
"text": "wait(3) init"
},
{
"answer_id": 1863323,
"author": "tolazy",
"author_id": 226721,
"author_profile": "https://Stackoverflow.com/users/226721",
"pm_score": 0,
"selected": false,
"text": "strace -p <pid>"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
356,724 | <p>I've used Emacs for years on Linux, and I have lots of personally useful keybindings I've put under <kbd>Hyper</kbd> and <kbd>Super</kbd>. Nowadays I'm using Emacs on Windows and am missing those extra keybindings.</p>
<p>Is there some way in Windows to get modifier keys other than <kbd>Ctrl</kbd> and <kbd>Meta</kbd>?</p>
| [
{
"answer_id": 364137,
"author": "Michael Paulukonis",
"author_id": 41153,
"author_profile": "https://Stackoverflow.com/users/41153",
"pm_score": 5,
"selected": true,
"text": "; setting the PC keyboard's various keys to Super or Hyper\n(setq w32-pass-lwindow-to-system nil\n w32-pass-rwindow-to-system nil\n w32-pass-apps-to-system nil\n w32-lwindow-modifier 'super ;; Left Windows key\n w32-rwindow-modifier 'super ;; Right Windows key\n w32-apps-modifier 'hyper) ;; Menu key\n (defun super-test ()\n (interactive)\n (message \"Super\"))\n\n(defun hyper-test ()\n (interactive)\n (message \"Hyper\"))\n\n(global-set-key [(super h)] 'super-test)\n(global-set-key [(hyper h)] 'hyper-test)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39683/"
] |
356,726 | <p>I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this:</p>
<pre><code>int i = true;
</code></pre>
<p>Is it "always" guaranteed that variable i will have value 1 or is it again depends on the compiler I am using ? Further for some Win32 APIs which accept BOOL as the parameter what happens if I pass bool variable?</p>
| [
{
"answer_id": 356728,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "true false enum bool {\n false, true\n};\n _Bool stdbool.h #define bool true false"
},
{
"answer_id": 356730,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 3,
"selected": false,
"text": "bool int int 0 false 1 true int"
},
{
"answer_id": 356768,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": -1,
"selected": false,
"text": "false true if(someval == true){\n if(someval !== false){ // e.g. someval !== 0\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39742/"
] |
356,759 | <p>I can never remember the order of the shorthand property for setting the margin or padding in one declaration. That is:</p>
<pre><code>margin-top: 2px;
margin-bottom: 4px;
margin-left: 3px;
margin-right: 8px;
</code></pre>
<p>may be written as</p>
<pre><code>margin: 2px 8px 4px 3px;
</code></pre>
<p>Yes I understand that one can visualise the order by thinking of a clock, starting at midday and moving clockwise. But I keep forgetting about that. I need to recall the order top, right, bottom, left textually.</p>
<p>Hence, <code>T R B L</code>.</p>
<p>Something like This [R-noun] [B-verb] [L-nouns] is perhaps the way to go but I feel myself lacking inspiration. If anyone has come across a useful mnemonic for this I'd love to hear it. Like a good meme, I'm sure once I get something lodged in my brain I will be unlikely to forget it.</p>
| [
{
"answer_id": 356766,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 1,
"selected": false,
"text": "top\nright \nbottom \nleft\n"
},
{
"answer_id": 356810,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 2,
"selected": false,
"text": "top right-and-left bottom"
},
{
"answer_id": 39037985,
"author": "TRT",
"author_id": 5449241,
"author_profile": "https://Stackoverflow.com/users/5449241",
"pm_score": 2,
"selected": false,
"text": "1 = (T/R/b/l) \n2 = (T=b) (R=l) \n3 = (T) (R=l) (b) \n4 = (T) (R) (b) (l)\n"
},
{
"answer_id": 54934753,
"author": "R K",
"author_id": 10877205,
"author_profile": "https://Stackoverflow.com/users/10877205",
"pm_score": 0,
"selected": false,
"text": "trouble"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18625/"
] |
356,763 | <p>I have a huge mbox file, with maybe 500 emails in it. </p>
<p>It looks like the following:</p>
<pre><code>From x@blah.com Fri Aug 12 09:34:09 2005
Message-ID: <42FBEE81.9090701@blah.com>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <x@blah.com>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <someone@hotmail.com>
Subject: Re: (no subject)
References: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
In-Reply-To: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://x+blah.com@blah.com/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
</code></pre>
<p>I would like to know how I can remove all of the quoted text, strip most of the headers except the To, From and Date lines, and still have it somewhat continuous.</p>
<p>My goal is to be able to print these emails as a book sort of format, and at the moment every program wants to print one email per page, or all of the headers and quoted text. Any suggestions for where to start on whipping up a small program using shell tools?</p>
| [
{
"answer_id": 356871,
"author": "Hudson",
"author_id": 14105,
"author_profile": "https://Stackoverflow.com/users/14105",
"pm_score": 4,
"selected": true,
"text": " #!/usr/bin/perl\n use warnings;\n use strict;\n use Mail::Box::Manager;\n\n my $file = shift || $ENV{MAIL};\n my $mgr = Mail::Box::Manager->new(\n access => 'r',\n );\n\n my $folder = $mgr->open( folder => $file )\n or die \"$file: Unable to open: $!\\n\";\n\n for my $msg ($folder->messages)\n {\n my $to = join( ', ', map { $_->format } $msg->to );\n my $from = join( ', ', map { $_->format } $msg->from );\n my $date = localtime( $msg->timestamp );\n my $subject = $msg->subject;\n my $body = $msg->body;\n\n # Strip all quoted text\n $body =~ s/^>.*$//msg;\n\n print <<\"\";\n From: $from\n To: $to\n Date: $date\n $body\n\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
356,775 | <p>I was recently trying to explain to a programmer why, in ASP.Net, they should create HTMLControls instead of creating HTML strings to create Web pages.</p>
<p>I know it is a better way of doing things, but I really couldn't give concrete reasons, other than, "This way is better."</p>
<p>If you had to answer this question, what would your answer be?</p>
<p>Why is <pre>Dim divA as New HtmlControls.HtmlGenericControl("div")
Dim ulList1 as New HtmlControls.HtmlGenericControl("ul")
Dim liObj1, liObj2, liObj3 as New HtmlControls.HtmlGenericControl("li")
liObj1.innerText = "List item 1"
liObj2.innerText = "List item 2"
liObj3.innerText = "List item 3"
ulList1.Controls.Add(liObj1)
ulList1.Controls.Add(liObj2)
ulList1.Controls.add(liObj3)
divA.Controls.add(ulList1)</pre></p>
<p>"better" than: </p>
<pre><code>Dim strHTML as String
strHTML = "<div><ul><li>List item 1</li><li>List item 2</li><li>List item 3</li></ul></div>"
</code></pre>
<p>? It doesn't look better. Look at all that code! And, this is a very simplistic example, to save space. I don't think I would ever actually create a list manually like that, but would be iterating through a collection or using a more advanced Web control, but I'm trying to illustrate a point.</p>
| [
{
"answer_id": 356840,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": ".ToString()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13449/"
] |
356,778 | <p>I have a function that looks something like this:</p>
<pre><code>//iteration over scales
foreach ($surveyScales as $scale)
{
$surveyItems = $scale->findDependentRowset('SurveyItems');
//nested iteration over items in scale
foreach ($surveyItems as $item)
{
//retrieve a single value from a result table and do some stuff
//depending on certain params from $item / $scale
}
}
</code></pre>
<p><strong>QUESTION</strong>: is it better to do a db query for every single value within the inner foreach or is it better to fetch all result values into an array and get the value from there?</p>
| [
{
"answer_id": 356869,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "findDependentRowset() findDependentRowset() fetchAll()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
356,779 | <p>I have a small form inside a table. POSTing that form creates a new entity. I then want users to see that new entity, but it should open in a new window so that the original view isn't lost.</p>
<p>(How) can I open the result of the form submission in a new window?</p>
| [
{
"answer_id": 356789,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 4,
"selected": true,
"text": "<form ... target=\"windowName\">\n <form ... target=\"windowName\" onsubmit=\"window.open(this.action, this.target, '...attributes...');return true;\">\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4937/"
] |
356,791 | <p>It could be part of the model because it's part of the business logic of the game.</p>
<p>It could be part of the controller because it could be seen as simulating player input, which would be considered part of the controller, right? Or would it?</p>
<p>What about a normal enemy, like a goomba in Mario?</p>
<p>UPDATE: Wow, that's really not the answer I was expecting. As far as I could tell, A.I. is an internal part of the autonomous game system, hence model. I'm still not convinced.</p>
| [
{
"answer_id": 356806,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 1,
"selected": false,
"text": "Goomba.move()\n{\n /* Move Goomba forward one unit. */\n}\n Controller.advanceTime()\n{\n foreach(Goomba goomba in state.getGoombas())\n {\n goomba.move();\n }\n}\n"
},
{
"answer_id": 357133,
"author": "Nick Van Brunt",
"author_id": 30470,
"author_profile": "https://Stackoverflow.com/users/30470",
"pm_score": 0,
"selected": false,
"text": "sprite {\n x,y\n image // this object contains everything about drawing\n path[] // an array of path nodes generated by my AI\n onNode(node) {\n if (x == node.x) && (y == node.y) return true\n return false\n }\n update () {\n moveto(path.last())\n if (onNode(path.last())) path.pop()\n if (path.empty()) path = doAI()\n }\n doAI() {\n ...\n return newPath\n }\n moveto(node) {\n ...\n }\n draw (screen) {\n if (screen.over(x, y)) image.draw(x-screen.x, y-screen.y)\n }\n}\n\nscreen = //something the platform would create\nspriteCollection = //my game objects\n\nforeach (sprite in spriteCollection) {\n sprite.update()\n sprite.draw(screen)\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
356,794 | <p>I've got a JScript error on my page. I know where the error's happening, but I'm attempting to decipher the JScript on that page (to figure out where it came from -- it's on an ASPX page, so any number of user controls could have injected it).</p>
<p>It'd be easier if it was indented properly. Are there any free JScript reformatters for Windows?</p>
| [
{
"answer_id": 356808,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 1,
"selected": false,
"text": "ctrl + a"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
356,796 | <p>I have been using the ASP.NET AJAX UpdatePanel control a lot lately for some intranet apps I've been working on, and for the most part, I have been using it to dynamically refresh data or hide and show controls on a form based on the user's actions.</p>
<p>There is one place where I have been having a bit of trouble, and I'm wondering if anyone has any advice. My form is using a pretty typical table based layout where the table is used to display a grid of labels and fields for the user to fill out. (I already know table based layouts are eschewed by some people, and I understand the pros and cons. But that's the choice I've made, so please don't answer with "Don't use a table based layout".)</p>
<p>Now my problem is that there are times when I would <em>like</em> to wrap an UpdatePanel around a set of rows so that I can hide and show them dynamically, but the UpdatePanel doesn't really let you do that. The basic problem is that it wraps a div around them, and as far as I know, you cannot wrap a div around table rows. It is not valid HTML.</p>
<p>So the way I have been dealing with it is to make my dynamic rows part of a whole new table entirely, which is OK, but then you have to deal with aligning all the columns manually with the table above it, and that is a real pain and pretty fragile.</p>
<p>So, the question is... does anyone know of any technique for dynamically generating or refreshing rows using either an UpdatePanel or something similar? Hopefully, the solution would be almost as easy as dropping an UpdatePanel on the page, but even if not, I'd still like to hear it.</p>
| [
{
"answer_id": 356827,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 3,
"selected": false,
"text": "<tr style=\"display: <%= visible %>\">\n <td></td>\n</tr>\n"
},
{
"answer_id": 361435,
"author": "Astra",
"author_id": 5862,
"author_profile": "https://Stackoverflow.com/users/5862",
"pm_score": 2,
"selected": false,
"text": "<table>\n <tr id=\"row1\" runat=\"server\">\n <td>Label</td><td>Field</td>\n </tr>\n</table>\n row1.visible = false;\n .hidden_row {\n display: none;\n}\n <tr class=\"<%= variable %>\">\n"
},
{
"answer_id": 361440,
"author": "Daniel Schaffer",
"author_id": 2596,
"author_profile": "https://Stackoverflow.com/users/2596",
"pm_score": 2,
"selected": false,
"text": "<button onclick=\"$('.inactive').toggle();\">Toogle Inactive</button>\n\n<table>\n<tr class=\"inactive\"><td>Inactive 1</td></tr>\n<tr class=\"inactive\"><td>Inactive 2</td></tr>\n<tr><td>Active 1</td></tr>\n<tr><td>Active 2</td></tr>\n</table>\n"
},
{
"answer_id": 5723723,
"author": "Marek Kwiendacz",
"author_id": 373021,
"author_profile": "https://Stackoverflow.com/users/373021",
"pm_score": 0,
"selected": false,
"text": "<UpdatePanel>\n<DIV>\n <TABLE>\n <TR>\n <TH class=\"h1\">Name</TH>\n </TR>\n </TABLE>\n\n <UpdatePanel Id='InnerPanel1'>\n <TABLE>\n <TR>\n <TD class=\"h1\">John</TD>\n </TR>\n </TABLE>\n </UpdatePanel>\n</DIV>\n</UpdatePanel>\n"
},
{
"answer_id": 10763434,
"author": "dio",
"author_id": 1418576,
"author_profile": "https://Stackoverflow.com/users/1418576",
"pm_score": 2,
"selected": false,
"text": "<asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\"><ContentTemplate> <table ID=\"Table1\">\n<tr>\n<td >\n...\n</td>\n<asp:UpdatePanel ID=\"UpdatePanel2\" runat=\"server\" UpdateMode=\"Conditional\">\n<ContentTemplate>\n<td >\n....\n</td>\n<td >\n...\n</td>\n<td >\n...\n</td>\n</ContentTemplate>\n</asp:UpdatePanel> \n\n</tr>\n\n </table></ContentTemplate></asp:UpdatePanel> \n"
},
{
"answer_id": 13265768,
"author": "MSR",
"author_id": 1805471,
"author_profile": "https://Stackoverflow.com/users/1805471",
"pm_score": 2,
"selected": false,
"text": "<asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\">\n</asp:ScriptManager>\n<table width=\"100%\">\n <tr>\n <td style=\"width: 300px\">\n Employee First Name\n </td>\n <td>\n <asp:TextBox ID=\"txtFname\" runat=\"server\"></asp:TextBox>\n </td>\n </tr>\n <asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n <tbody>\n <tr>\n <td style=\"width: 300px\">\n Date Of Birth\n </td>\n <td>\n <asp:TextBox ID=\"txtDOB1\" runat=\"server\" OnTextChanged=\"txtDOB_TextChanged\" AutoPostBack=\"true\"></asp:TextBox>\n <asp:CalendarExtender ID=\"txtDOB1_CalendarExtender\" runat=\"server\" Enabled=\"True\"\n TargetControlID=\"txtDOB1\">\n </asp:CalendarExtender>\n </td>\n </tr>\n <tr>\n <td style=\"width: 300px\">\n Age\n </td>\n <td>\n <asp:TextBox ID=\"txtAge\" Style=\"font-weight: bold; font-size: large\" runat=\"server\"\n Enabled=\"false\"></asp:TextBox>\n </td>\n </tr>\n </tbody>\n </ContentTemplate>\n </asp:UpdatePanel>\n <tr>\n <td align=\"right\" style=\"width: 300px\">\n <asp:Button ID=\"btnSubmit\" runat=\"server\" CssClass=\"button\" Text=\"Submit\" />\n </td>\n <td>\n <asp:Button ID=\"btnClear\" runat=\"server\" CssClass=\"button\" Text=\"Reset\" />\n </td>\n </tr>\n</table>\n protected void txtDOB_TextChanged(object sender, EventArgs e)\n{\n try\n {\n DateTime Today = DateTime.Now;\n DateTime DOB = Convert.ToDateTime(txtDOB1.Text);\n ArrayList arr = new ArrayList();\n arr = span(Today, DOB);\n arr[0].ToString();//For Years\n arr[1].ToString();//For Months\n arr[2].ToString();//For Days\n txtAge.Text = \"Y: \" + arr[0].ToString()+\",M: \"+arr[1].ToString()+\",D: \"+arr[2].ToString();\n\n }\n catch (Exception ex)\n {\n\n lblError.Text = \"Error : \" + ex.Message ;\n }\n}\npublic ArrayList span(DateTime f, DateTime l)\n{\n int days;\n int months;\n int years;\n\n int fird = f.Day;\n int lasd = l.Day;\n\n int firm = f.Month;\n int lasm = l.Month;\n\n if (fird >= lasd)\n {\n days = fird - lasd;\n if (firm >= lasm)\n {\n months = firm - lasm;\n years = f.Year - l.Year;\n }\n else\n {\n months = (firm + 12) - lasm;\n years = f.AddYears(-1).Year - l.Year;\n }\n }\n else\n {\n days = (fird + 30) - lasd;\n if ((firm - 1) >= lasm)\n {\n months = (firm - 1) - lasm;\n years = f.Year - l.Year;\n }\n else\n {\n months = (firm - 1 + 12) - lasm;\n years = f.AddYears(-1).Year - l.Year;\n }\n }\n\n\n if (days < 0)\n {\n days = 0 - days;\n }\n if (months < 0)\n {\n months = 0 - months;\n }\n ArrayList ar = new ArrayList();\n ar.Add(years.ToString());\n ar.Add(months.ToString());\n ar.Add(days.ToString());\n return ar;\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436/"
] |
356,807 | <p>I wrote a class that tests for equality, less than, and greater than with two doubles in Java. My general case is comparing price that can have an accuracy of a half cent. 59.005 compared to 59.395. Is the epsilon I chose adequate for those cases?</p>
<pre><code>private final static double EPSILON = 0.00001;
/**
* Returns true if two doubles are considered equal. Tests if the absolute
* difference between two doubles has a difference less then .00001. This
* should be fine when comparing prices, because prices have a precision of
* .001.
*
* @param a double to compare.
* @param b double to compare.
* @return true true if two doubles are considered equal.
*/
public static boolean equals(double a, double b){
return a == b ? true : Math.abs(a - b) < EPSILON;
}
/**
* Returns true if two doubles are considered equal. Tests if the absolute
* difference between the two doubles has a difference less then a given
* double (epsilon). Determining the given epsilon is highly dependant on the
* precision of the doubles that are being compared.
*
* @param a double to compare.
* @param b double to compare
* @param epsilon double which is compared to the absolute difference of two
* doubles to determine if they are equal.
* @return true if a is considered equal to b.
*/
public static boolean equals(double a, double b, double epsilon){
return a == b ? true : Math.abs(a - b) < epsilon;
}
/**
* Returns true if the first double is considered greater than the second
* double. Test if the difference of first minus second is greater then
* .00001. This should be fine when comparing prices, because prices have a
* precision of .001.
*
* @param a first double
* @param b second double
* @return true if the first double is considered greater than the second
* double
*/
public static boolean greaterThan(double a, double b){
return greaterThan(a, b, EPSILON);
}
/**
* Returns true if the first double is considered greater than the second
* double. Test if the difference of first minus second is greater then
* a given double (epsilon). Determining the given epsilon is highly
* dependant on the precision of the doubles that are being compared.
*
* @param a first double
* @param b second double
* @return true if the first double is considered greater than the second
* double
*/
public static boolean greaterThan(double a, double b, double epsilon){
return a - b > epsilon;
}
/**
* Returns true if the first double is considered less than the second
* double. Test if the difference of second minus first is greater then
* .00001. This should be fine when comparing prices, because prices have a
* precision of .001.
*
* @param a first double
* @param b second double
* @return true if the first double is considered less than the second
* double
*/
public static boolean lessThan(double a, double b){
return lessThan(a, b, EPSILON);
}
/**
* Returns true if the first double is considered less than the second
* double. Test if the difference of second minus first is greater then
* a given double (epsilon). Determining the given epsilon is highly
* dependant on the precision of the doubles that are being compared.
*
* @param a first double
* @param b second double
* @return true if the first double is considered less than the second
* double
*/
public static boolean lessThan(double a, double b, double epsilon){
return b - a > epsilon;
}
</code></pre>
| [
{
"answer_id": 356825,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 4,
"selected": false,
"text": "1E-6 epsilon = 1E-5;"
},
{
"answer_id": 356865,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 7,
"selected": false,
"text": "java.math.BigDecimal"
},
{
"answer_id": 3991011,
"author": "Bill",
"author_id": 483442,
"author_profile": "https://Stackoverflow.com/users/483442",
"pm_score": 2,
"selected": false,
"text": "boolean equal(double d1, double d2) {\n double d = d1 / d2;\n return (Math.abs(d - 1.0) < 0.001);\n}\n"
},
{
"answer_id": 21558851,
"author": "carlosvin",
"author_id": 1421059,
"author_profile": "https://Stackoverflow.com/users/1421059",
"pm_score": 3,
"selected": false,
"text": "/**\n *@param precision number of decimal digits\n */\npublic static boolean areEqualDouble(double a, double b, int precision) {\n return Math.abs(a - b) <= Math.pow(10, -precision);\n}\n"
},
{
"answer_id": 28749186,
"author": "Franz D.",
"author_id": 4610114,
"author_profile": "https://Stackoverflow.com/users/4610114",
"pm_score": 2,
"selected": false,
"text": "EPSILON 10.0 10.0 EPSILON double a = 10.0;\n double b = 10.0 + EPSILON;\n if (!equals(a, b)) {\n System.out.println(\"OK: \" + a + \" != \" + b);\n } else {\n System.out.println(\"ERROR: \" + a + \" == \" + b);\n }\n ERROR: 10.0 == 10.00001\n double BigDecimal longs 9'223'372'036'854'775.807"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,809 | <p>Best way to center a <code><div></code> element on a page both vertically and horizontally?</p>
<p>I know that <code>margin-left: auto; margin-right: auto;</code> will center on the horizontal, but what is the best way to do it vertically, too?</p>
| [
{
"answer_id": 356829,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 4,
"selected": false,
"text": "var centerIt = function (el /* (jQuery element) Element to center */) {\n if (!el) {\n return;\n }\n var moveIt = function () {\n var winWidth = $(window).width();\n var winHeight = $(window).height();\n el.css(\"position\",\"absolute\").css(\"left\", ((winWidth / 2) - (el.width() / 2)) + \"px\").css(\"top\", ((winHeight / 2) - (el.height() / 2)) + \"px\");\n }; \n $(window).resize(moveIt);\n moveIt();\n};\n"
},
{
"answer_id": 12110948,
"author": "Dany Y",
"author_id": 667726,
"author_profile": "https://Stackoverflow.com/users/667726",
"pm_score": -1,
"selected": false,
"text": " .middleDiv{\n position : absolute;\n height : 90%;\n bottom: 5%;\n }\n"
},
{
"answer_id": 13356401,
"author": "Vladimir Starkov",
"author_id": 1057730,
"author_profile": "https://Stackoverflow.com/users/1057730",
"pm_score": 10,
"selected": false,
"text": "margin-top: auto top bottom div div {\n width: 100px;\n height: 100px;\n background-color: red;\n \n position: absolute;\n top:0;\n bottom: 0;\n left: 0;\n right: 0;\n \n margin: auto;\n} <div></div>"
},
{
"answer_id": 17502558,
"author": "user2555501",
"author_id": 2555501,
"author_profile": "https://Stackoverflow.com/users/2555501",
"pm_score": 5,
"selected": false,
"text": ".middleDiv {\n position : absolute; \n width : 200px;\n height : 200px;\n left : 50%;\n top : 50%;\n margin-left : -100px; /* half of the width */\n margin-top : -100px; /* half of the height */\n}\n"
},
{
"answer_id": 18618259,
"author": "tombul",
"author_id": 2686625,
"author_profile": "https://Stackoverflow.com/users/2686625",
"pm_score": 7,
"selected": false,
"text": ".centerPseudo {\n display:inline-block;\n text-align:center;\n}\n\n.centerPseudo::before{\n content:'';\n display:inline-block;\n height:100%;\n vertical-align:middle;\n width:0px;\n}\n .centerFlex {\n align-items: center;\n display: flex;\n justify-content: center;\n}\n"
},
{
"answer_id": 18869411,
"author": "Master Programmer",
"author_id": 2768930,
"author_profile": "https://Stackoverflow.com/users/2768930",
"pm_score": 2,
"selected": false,
"text": ".position() <div class=\"positionthis\"></div>\n .positionthis {\n width:100px;\n height:100px;\n position: absolute;\n background:blue;\n}\n $(document).ready(function () {\n $('.positionthis').position({\n of: $(document),\n my: 'center center',\n at: 'center center',\n collision: 'flip flip'\n });\n});\n"
},
{
"answer_id": 19406831,
"author": "Ashish",
"author_id": 2477215,
"author_profile": "https://Stackoverflow.com/users/2477215",
"pm_score": 0,
"selected": false,
"text": " div {\n position: fixed;\n top: 50%;\n left: 50%;\n margin-top: -50px;\n margin-left: -100px;\n }\n"
},
{
"answer_id": 24886524,
"author": "winuxde",
"author_id": 3864443,
"author_profile": "https://Stackoverflow.com/users/3864443",
"pm_score": 3,
"selected": false,
"text": "div {\n border-style: solid;\n position: fixed;\n width: 80%;\n height: 80%;\n left: 10%;\n top: 10%;\n}\n"
},
{
"answer_id": 24935566,
"author": "Asur",
"author_id": 790607,
"author_profile": "https://Stackoverflow.com/users/790607",
"pm_score": 3,
"selected": false,
"text": "<style>\n\n .table {\n display: table;\n height: 100%;\n margin: 0 auto;\n }\n .table-cell {\n display: table-cell;\n vertical-align: middle; \n }\n .centered {\n background-color: red;\n }\n </style>\n <div class=\"table\">\n <div class=\"table-cell\"><div class=\"centered\">centered</div></div>\n</div>\n"
},
{
"answer_id": 25978463,
"author": "giorgio",
"author_id": 777850,
"author_profile": "https://Stackoverflow.com/users/777850",
"pm_score": 3,
"selected": false,
"text": "transformY <div class=\"parent\">\n <div class=\"center-me\">\n Text, images, whatever suits you.\n </div>\n</div>\n\n.parent { \n /* height can be whatever you want, also auto if you want a child \n div to be responsible for the sizing */ \n height: 200px;\n}\n\n.center-me { \n position: relative;\n top: 50%;\n transform: translateY(-50%);\n /* prefixes needed for cross-browser support */\n -ms-transform: translateY(-50%);\n -webkit-transform: translateY(-50%);\n}\n"
},
{
"answer_id": 26282630,
"author": "robjez",
"author_id": 293518,
"author_profile": "https://Stackoverflow.com/users/293518",
"pm_score": 3,
"selected": false,
"text": "<div class=\"container\">\n <div class=\"outer\">\n <div class=\"inner\">\n <div class=\"centered\">\n ...\n </div>\n </div>\n </div>\n</div>\n .outer {\n display: table;\n width: 100%;\n height: 100%;\n}\n.inner {\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n}\n.centered {\n position: relative;\n display: inline-block;\n\n width: 50%;\n padding: 1em;\n background: orange;\n color: white;\n}\n"
},
{
"answer_id": 27424970,
"author": "István",
"author_id": 2857638,
"author_profile": "https://Stackoverflow.com/users/2857638",
"pm_score": 2,
"selected": false,
"text": "<div id=\"container\"> \n <div id=\"centered\"> </div>\n</div>\n #container {\n height: 400px;\n width: 400px;\n background-color: lightblue;\n text-align: center;\n}\n\n#container:before {\n height: 100%;\n content: '';\n display: inline-block;\n vertical-align: middle;\n}\n\n#centered {\n width: 100px;\n height: 100px;\n background-color: blue;\n display: inline-block;\n vertical-align: middle;\n margin: 0 auto;\n}\n"
},
{
"answer_id": 27869108,
"author": "Ulad Kasach",
"author_id": 3068233,
"author_profile": "https://Stackoverflow.com/users/3068233",
"pm_score": 5,
"selected": false,
"text": " <div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>\n <div id = 'div_you_want_centered' style = 'margin:auto;'> \n This will be Centered \n </div>\n </div>\n"
},
{
"answer_id": 27987977,
"author": "robjez",
"author_id": 293518,
"author_profile": "https://Stackoverflow.com/users/293518",
"pm_score": 7,
"selected": false,
"text": "<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>\n div {\n color: white;\n background: red;\n padding: 15px;\n position: absolute;\n top: 50%;\n left: 50%;\n -ms-transform: translateX(-50%) translateY(-50%);\n -webkit-transform: translate(-50%,-50%);\n transform: translate(-50%,-50%);\n} \n"
},
{
"answer_id": 29242110,
"author": "Tebe",
"author_id": 758158,
"author_profile": "https://Stackoverflow.com/users/758158",
"pm_score": 3,
"selected": false,
"text": "<html>\n<head>\n <title>Laravel</title>\n\n <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->\n\n <style>\n .container {\n margin: 0;\n padding: 0;\n width: 100%;\n height: 100%;\n display: table;\n\n }\n\n .inside {\n text-align: center;\n display: table-cell;\n vertical-align: middle;\n }\n\n\n </style>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"inside\">This text is centered</div>\n </div>\n</body>\n"
},
{
"answer_id": 31639985,
"author": "Kop4lyf",
"author_id": 1894565,
"author_profile": "https://Stackoverflow.com/users/1894565",
"pm_score": 5,
"selected": false,
"text": "<div class=\"center-block\">this is any div</div>\n .center-block {\n top:50%;\n left: 50%;\n transform: translate3d(-50%,-50%, 0);\n position: absolute;\n}\n"
},
{
"answer_id": 31810977,
"author": "Sebastien Lorber",
"author_id": 82609,
"author_profile": "https://Stackoverflow.com/users/82609",
"pm_score": 2,
"selected": false,
"text": "position: absolute;\nbackground-color: red;\n\nwidth: 70%; \nheight: 30%; \n\n/* The translate % is relative to the size of the div and not the container*/ \n/* 21.42% = ( (100%-70%/2) / 0.7 ) */\n/* 116.666% = ( (100%-30%/2) / 0.3 ) */\ntransform: translate3d( 21.42%, 116.666%, 0);\n"
},
{
"answer_id": 35640427,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 4,
"selected": false,
"text": "display: table; display: table-cell; vertical-align: middle; text-align: center; display: inline-block; text-align: left; text-align: right; body {\n margin : 0;\n}\n\n.outer-container {\n position : absolute;\n display: table;\n width: 100%; /* This could be ANY width */\n height: 100%; /* This could be ANY height */\n background: #ccc;\n}\n\n.inner-container {\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n}\n\n.centered-content {\n display: inline-block;\n text-align: left;\n background: #fff;\n padding : 20px;\n border : 1px solid #000;\n} <div class=\"outer-container\">\n <div class=\"inner-container\">\n <div class=\"centered-content\">\n You can put anything here!\n </div>\n </div>\n</div> transform: translate(-50%, -50%); transform: translate3d(-50%,-50%, 0); -webkit -ms -moz transform transform"
},
{
"answer_id": 36717369,
"author": "Maxwell175",
"author_id": 1610754,
"author_profile": "https://Stackoverflow.com/users/1610754",
"pm_score": 6,
"selected": false,
"text": "translate position: fixed; top: 50%; left: 50% translate translate translate3d .centered {\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n -webkit-transform: translate(-50%, -50%);\n -moz-transform: translate(-50%, -50%);\n -o-transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n \n font-size: 20px;\n background-color: cyan;\n border: darkgreen 5px solid;\n padding: 5px;\n z-index: 100;\n}\n\ntable {\n position: absolute;\n top: 0;\n left: 0;\n}\n\ntd {\n position: relative;\n top: 0;\n left: 0;\n} <table>\n<tr>\n <td>\n <div class=\"centered\">This div<br />is centered</div>\n <p>\n Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.\n </p>\n </td>\n <td>\n <p>\n Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.\n </p>\n </td>\n</tr>\n</table> .centered {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n -webkit-transform: translate(-50%, -50%);\n -moz-transform: translate(-50%, -50%);\n -o-transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%);\n\n font-size: 20px;\n background-color: cyan;\n border: darkgreen 5px solid;\n padding: 5px;\n z-index: 100;\n}\n\ntable {\n position: absolute;\n top: 0;\n left: 0;\n}\n\ntd {\n position: relative;\n top: 0;\n left: 0;\n} <table>\n<tr>\n <td>\n <div class=\"centered\">This div<br />is centered</div>\n <p>\n Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.\n </p>\n </td>\n <td>\n <p>\n Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.\n </p>\n </td>\n</tr>\n</table>"
},
{
"answer_id": 37858578,
"author": "GibboK",
"author_id": 379008,
"author_profile": "https://Stackoverflow.com/users/379008",
"pm_score": 2,
"selected": false,
"text": "div calc #target {\n position:fixed;\n top: calc(50vh - 100px/2);\n left: calc(50vw - 200px/2);\n width:200px;\n height:100px;\n background-color:red;\n} <div id='target'></div>"
},
{
"answer_id": 38572197,
"author": "AmazingTurtle",
"author_id": 2667808,
"author_profile": "https://Stackoverflow.com/users/2667808",
"pm_score": 4,
"selected": false,
"text": "position: absolute;\nleft: 50%;\ntop: 50%;\n-webkit-transform: translate(-50%, -50%);\n-ms-transform: translate(-50%, -50%);\ntransform: translate(-50%, -50%);\n"
},
{
"answer_id": 45372659,
"author": "siawo",
"author_id": 7611678,
"author_profile": "https://Stackoverflow.com/users/7611678",
"pm_score": 4,
"selected": false,
"text": "div\n{\n position:absolute;\n top:50%;\n left:50%;\n transform:translate(-50%,-50%);\n}"
},
{
"answer_id": 45684473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": ".parent { display: flex; }\n.child { margin: auto }\n"
},
{
"answer_id": 45730337,
"author": "Bourbia Brahim",
"author_id": 2932476,
"author_profile": "https://Stackoverflow.com/users/2932476",
"pm_score": 2,
"selected": false,
"text": "display:grid margin:auto html,body {\n width :100%;\n height:100%;\n margin:0;\n padding:0;\n}\n\n.container {\n display:grid;\n height:90%;\n background-color:blue;\n}\n\n.content {\n margin:auto;\n color:white;\n} <div class=\"container\">\n <div class=\"content\"> cented div here</div>\n</div>"
},
{
"answer_id": 46375392,
"author": "antelove",
"author_id": 7656367,
"author_profile": "https://Stackoverflow.com/users/7656367",
"pm_score": 2,
"selected": false,
"text": "div {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n -ms-transform: translate(-50%, -50%); /* IE 9 */\n -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ \n} <body>\n <div>Div to be aligned vertically</div>\n</body>"
},
{
"answer_id": 46601783,
"author": "Suraj Kavade",
"author_id": 4165560,
"author_profile": "https://Stackoverflow.com/users/4165560",
"pm_score": 0,
"selected": false,
"text": "div {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0px;\n margin: auto;\n width: 100px;\n height: 100px;\n}\n"
},
{
"answer_id": 48485233,
"author": "1valdis",
"author_id": 5748383,
"author_profile": "https://Stackoverflow.com/users/5748383",
"pm_score": 3,
"selected": false,
"text": ".parent{\n display: grid;\n place-items: center center;\n}\n .parent{\n display: grid;\n place-items: center center;\n /*place-items is a shorthand for align-items and justify-items*/\n \n height: 200px;\n border: 1px solid black;\n background: gainsboro;\n}\n\n.child{\n background: white;\n} <div class=\"parent\">\n <div class=\"child\">Centered!</div>\n</div>"
},
{
"answer_id": 48961005,
"author": "Rocks",
"author_id": 4033704,
"author_profile": "https://Stackoverflow.com/users/4033704",
"pm_score": 2,
"selected": false,
"text": "height margin-left margin-right auto .container {\n width: 60vw; /*optional*/\n height: 60vh;\n margin: 20vh auto;\n background: #333;\n } <div class=\"container\">\n</div>"
},
{
"answer_id": 50035114,
"author": "Mahfuzur Rahman",
"author_id": 6570691,
"author_profile": "https://Stackoverflow.com/users/6570691",
"pm_score": 3,
"selected": false,
"text": "body{\n background: #EEE;\n}\n.center-div{\n position: absolute;\n width: 200px;\n height: 60px;\n left: 50%; \n margin-left: -100px;\n top: 50%;\n margin-top: -30px;\n background: #CCC;\n color: #000;\n text-align: center;\n} <div class=\"center-div\">\n <h3>This is center div</h3>\n</div>"
},
{
"answer_id": 52266740,
"author": "Morteza Sadri",
"author_id": 7707724,
"author_profile": "https://Stackoverflow.com/users/7707724",
"pm_score": 5,
"selected": false,
"text": "#parent {\n display: flex;\n justify-content: center;\n align-items: center;\n} <div id=\"parent\">\n <div id=\"child\">Hello World!</div>\n</div> display: flex; justify-content: center; align-items: center; #parent {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 500px;\n width: 500px;\n background: yellow;\n}\n\n#child {\n width: 100px;\n height: 100px;\n background: silver;\n} <div id=\"parent\">\n <div id=\"child\">Hello World!</div>\n</div>"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,830 | <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p>
<p>I have basically this:</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p>
<pre><code>child = pexpect.spawn('command2')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>And the code is hanging at the second "spawn"</p>
<p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p>
<p>Now, the other thing I haven't been able to do is wait until the first one stops.
I've tried:<br>
child.close() - it hangs (both with True and False as parameters)
child.read(-1) - it hangs<br>
child.expect(pexpect.EOF) - it hangs.<br>
child.terminate() - it hangs (both with True and False as parameters)</p>
<p>Any ideas on what could be happening?<br>
NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p>
<p>Thanks!</p>
<hr>
<p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return.
Also, apparently ssh-copy-id never returns an EOF.</p>
| [
{
"answer_id": 357021,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 0,
"selected": false,
"text": "child = pexpect.spawn('command')\nchild.expect('password:')\nchild.sendline('the password')\nchild.close(True)\n child = pexpect.spawn('command')\nchild.expect('password:')\nchild.sendline('the password')\nchild.wait()\nchild = pexpect.spawn('command2')\n...\n def exec_command(cmd):\n child = pexpect.spawn(cmd)\n child.expect('password:')\n child.sendline('the password')\n return child\n\ncommands = ['command1', 'command2']\nchildrens = [exec_command(cmd) for cmd in commands]\nfor child in childrens:\n child.wait() \n"
},
{
"answer_id": 357749,
"author": "user45148",
"author_id": 45148,
"author_profile": "https://Stackoverflow.com/users/45148",
"pm_score": 1,
"selected": false,
"text": "dssh-add -l < passwordfile\n echo \"name-of-server;22;root;password;\" | dssh-add -l\n password name-of-server;22;root;password;\n CONTENTS OF ... dssh root@name-of-server -- echo \"CONTENTS OF ~/.ssh/identity.pub\" > .ssh/authorized_keys \\; chmod og-w .ssh .ssh/authorized_keys\n dssh-add -f passwords\n"
},
{
"answer_id": 1662962,
"author": "drdaeman",
"author_id": 116546,
"author_profile": "https://Stackoverflow.com/users/116546",
"pm_score": 2,
"selected": false,
"text": "echo \"...\" >> $HOME/.ssh/authorized_keys"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
356,831 | <p>I'm very excited about the new "local F specs" coming in V6R1 - see:</p>
<p><a href="http://www.mcpressonline.com/programming/rpg/v6r1-rpg-enhancements.html" rel="nofollow noreferrer">http://www.mcpressonline.com/programming/rpg/v6r1-rpg-enhancements.html</a></p>
<p>Does anyone know a way to simulate this in V5R4 in a SRVPGM procedure?</p>
| [
{
"answer_id": 357021,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 0,
"selected": false,
"text": "child = pexpect.spawn('command')\nchild.expect('password:')\nchild.sendline('the password')\nchild.close(True)\n child = pexpect.spawn('command')\nchild.expect('password:')\nchild.sendline('the password')\nchild.wait()\nchild = pexpect.spawn('command2')\n...\n def exec_command(cmd):\n child = pexpect.spawn(cmd)\n child.expect('password:')\n child.sendline('the password')\n return child\n\ncommands = ['command1', 'command2']\nchildrens = [exec_command(cmd) for cmd in commands]\nfor child in childrens:\n child.wait() \n"
},
{
"answer_id": 357749,
"author": "user45148",
"author_id": 45148,
"author_profile": "https://Stackoverflow.com/users/45148",
"pm_score": 1,
"selected": false,
"text": "dssh-add -l < passwordfile\n echo \"name-of-server;22;root;password;\" | dssh-add -l\n password name-of-server;22;root;password;\n CONTENTS OF ... dssh root@name-of-server -- echo \"CONTENTS OF ~/.ssh/identity.pub\" > .ssh/authorized_keys \\; chmod og-w .ssh .ssh/authorized_keys\n dssh-add -f passwords\n"
},
{
"answer_id": 1662962,
"author": "drdaeman",
"author_id": 116546,
"author_profile": "https://Stackoverflow.com/users/116546",
"pm_score": 2,
"selected": false,
"text": "echo \"...\" >> $HOME/.ssh/authorized_keys"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,835 | <p>OK, if anyone could help me with this I'd be much appreciative. If you copy and paste the following and open up in IE or Firefox</p>
<pre><code><div style="border: solid 1px navy; float: left;">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
<div style="background-color: blue;">
<p>Some Text</p>
<p>Another paragraph</p>
</div>
</code></pre>
<p>Why does the second div which has a blue background expand to be behind the first div that contains the list of items? How do I get it to really float next to the first div?</p>
| [
{
"answer_id": 356872,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "<div style=\"border: solid 1px navy; float: left;\">\n<ul>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n</ul>\n</div>\n<div style=\"background-color: blue; float:left;\"><p>Some Text</p><p>Another paragraph</p></div>\n"
},
{
"answer_id": 356873,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 1,
"selected": false,
"text": "float: left"
},
{
"answer_id": 356877,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 1,
"selected": false,
"text": "overflow: auto; zoom: 1.0; float: left; zoom: 1.0; <div style=\"border: solid 1px navy; float: left;\">\n<ul>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n</ul>\n</div>\n<div style=\"background-color: blue; overflow: auto; zoom: 1.0;\"><p>Some Text</p><p>Another paragraph</p></div>\n"
},
{
"answer_id": 356879,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "float:left overflow: auto zoom:1.0"
},
{
"answer_id": 356941,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 3,
"selected": false,
"text": "<div style=\"border: solid 1px navy; float: left;\">\n <div style=\"background-color: blue; float:left;\">\n <style type=\"text/css\">\n .leftBox, .rightBox\n {\n width: 48%; /*leave some room for varying browser definitions */\n border: 1px solid navy;\n float: left;\n display: inline; /* follow the semantic flow of the page and don't break the line */\n clear: left; /* don't allow any other elements between you and the left margin */\n }\n\n .rightBox\n {\n border: none;\n background-color: blue;\n clear: right;\n }\n</style>\n<div class=\"leftBox\">\n <ul>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n <li>Item 4</li>\n <li>Item 5</li>\n </ul>\n</div>\n<div class=\"rightBox\">\n <p>\n some other text</p>\n</div>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44702/"
] |
356,839 | <p>I've inherited a legacy application that is supposed to grab an on the fly pdf from a reporting services server. Everything works fine up until the point where you try to open the pdf being returned and adobe acrobat tells you:</p>
<blockquote>
<p>Adobe Reader could not open
'thisStoopidReport'.pdf' because it is
either not a supported file type or
because the file has been damaged(for
example, it was sent as an email
attachment and wasn't correctly
decoded).</p>
</blockquote>
<p>I've done some initial troubleshooting on this. If I replace the url in the WebRequest.Create() call with a valid pdf file on my local machine ie: @"C:temp/validpdf.pdf") then I get a valid PDF.</p>
<p>The report itself seems to work fine. If I manually type the URL to the reporting services report that should generate the pdf file I am prompted for user authentication. But after supplying it I get a valid pdf file.</p>
<p>I've replace the actual url,username,userpass and domain strings in the code below with bogus values for obvious reasons.</p>
<pre><code> WebRequest request = WebRequest.Create(@"http://x.x.x.x/reportServer?/reports/reportNam&rs:format=pdf&rs:command=render&rc:parameters=blahblahblah");
int totalSize = 0;
request.Credentials = new NetworkCredential("validUser", "validPass", "validDomain");
request.Timeout = 360000; // 6 minutes in milliseconds.
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = 0;
WebResponse response = request.GetResponse();
Response.Clear();
BinaryReader reader = new BinaryReader(response.GetResponseStream());
Byte[] buffer = new byte[2048];
int count = reader.Read(buffer, 0, 2048);
while (count > 0)
{
totalSize += count;
Response.OutputStream.Write(buffer, 0, count);
count = reader.Read(buffer, 0, 2048);
}
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Expires = 30;
Response.AddHeader("Content-Disposition", "attachment; filename=thisStoopidReport.pdf");
Response.AddHeader("Content-Length", totalSize.ToString());
reader.Close();
Response.Flush();
Response.End();
</code></pre>
| [
{
"answer_id": 357947,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "request.Method = WebRequestMethods.Http.Post;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,846 | <p>Earlier I asked a question about <a href="https://stackoverflow.com/questions/335682/mvc-examples-use-of-var">why I see so many examples use the <code>var</code>keyword</a> and got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'.</p>
<p>Following <a href="http://www.interact-sw.co.uk/iangblog/2005/09/23/varisntobject" rel="noreferrer">this link ("C# 3.0 - Var Isn't Objec")</a> I saw that <code>var</code> gets compiled down to the correct type in the IL (you will see it about midway down article).</p>
<p>My question is how much more, if any, IL code does using the <code>var</code> keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?</p>
| [
{
"answer_id": 356855,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "var var"
},
{
"answer_id": 356862,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "var"
},
{
"answer_id": 356866,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": false,
"text": "var s = \"hi\";\n string s = \"hi\";\n"
},
{
"answer_id": 356884,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var x = new ClassA();\nClassA x = new ClassA();\n var"
},
{
"answer_id": 356892,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 3,
"selected": false,
"text": "var i = 42;\n int i = 42;\n"
},
{
"answer_id": 1756479,
"author": "RichardOD",
"author_id": 97558,
"author_profile": "https://Stackoverflow.com/users/97558",
"pm_score": 5,
"selected": false,
"text": "static void Main(string[] args)\n{\n var x = \"hello\";\n string y = \"hello again!\";\n Console.WriteLine(x);\n Console.WriteLine(y);\n}\n // Methods\nprivate static void Main(string[] args)\n{\n string x = \"hello\";\n string y = \"hello again!\";\n Console.WriteLine(x);\n Console.WriteLine(y);\n}\n"
},
{
"answer_id": 5083406,
"author": "Rob",
"author_id": 629035,
"author_profile": "https://Stackoverflow.com/users/629035",
"pm_score": 4,
"selected": false,
"text": " private static void StringVsVarILOutput()\n {\n var string1 = new String(new char[9]);\n\n string string2 = new String(new char[9]);\n }\n {\n .method private hidebysig static void StringVsVarILOutput() cil managed\n // Code size 28 (0x1c)\n .maxstack 2\n .locals init ([0] string string1,\n [1] string string2)\n IL_0000: nop\n IL_0001: ldc.i4.s 9\n IL_0003: newarr [mscorlib]System.Char\n IL_0008: newobj instance void [mscorlib]System.String::.ctor(char[])\n IL_000d: stloc.0\n IL_000e: ldc.i4.s 9\n IL_0010: newarr [mscorlib]System.Char\n IL_0015: newobj instance void [mscorlib]System.String::.ctor(char[])\n IL_001a: stloc.1\n IL_001b: ret\n } // end of method Program::StringVsVarILOutput\n"
},
{
"answer_id": 24856726,
"author": "mjb",
"author_id": 520848,
"author_profile": "https://Stackoverflow.com/users/520848",
"pm_score": 2,
"selected": false,
"text": "SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();\n var coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();\n SomeCoolNamespace.SomeCoolObject coolObject = new SomeCoolNamespace.SomeCoolObject();\n var coolObject = GetCoolObject(param1, param2);\n"
},
{
"answer_id": 36365153,
"author": "Daniel Lorenz",
"author_id": 1245940,
"author_profile": "https://Stackoverflow.com/users/1245940",
"pm_score": 1,
"selected": false,
"text": "var dict = new Dictionary<string, string>();\n Dictionary<string, string> dict = var result = SomeMethod(); SomeMethod()"
},
{
"answer_id": 56284426,
"author": "Silvio Garcez",
"author_id": 11547585,
"author_profile": "https://Stackoverflow.com/users/11547585",
"pm_score": 0,
"selected": false,
"text": "public class Fruta\n{\n dynamic _instance;\n\n public Fruta(dynamic obj)\n {\n _instance = obj;\n }\n\n public dynamic GetInstance()\n {\n return _instance;\n }\n}\n\npublic class Manga\n{\n public int MyProperty { get; set; }\n public int MyProperty1 { get; set; }\n public int MyProperty2 { get; set; }\n public int MyProperty3 { get; set; }\n}\n\npublic class Pera\n{\n public int MyProperty { get; set; }\n public int MyProperty1 { get; set; }\n public int MyProperty2 { get; set; }\n}\n\npublic class Executa\n{\n public string Exec(int count, int value)\n {\n int x = 0;\n Random random = new Random();\n Stopwatch time = new Stopwatch();\n time.Start();\n\n while (x < count)\n {\n if (value == 0)\n {\n var obj = new Pera();\n }\n else if (value == 1)\n {\n Pera obj = new Pera();\n }\n else if (value == 2)\n {\n var obj = new Banana();\n }\n else if (value == 3)\n {\n var obj = (0 == random.Next(0, 1) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance());\n }\n else\n {\n Banana obj = new Banana();\n }\n\n x++;\n }\n\n time.Stop();\n return time.Elapsed.ToString();\n }\n\n public void ExecManga()\n {\n var obj = new Fruta(new Manga()).GetInstance();\n Manga obj2 = obj;\n }\n\n public void ExecPera()\n {\n var obj = new Fruta(new Pera()).GetInstance();\n Pera obj2 = obj;\n }\n}\n public string Exec(int count, int value)\n{\n int x = 0;\n Random random = new Random();\n Stopwatch time = new Stopwatch();\n time.Start();\n\n for (; x < count; x++)\n {\n switch (value)\n {\n case 0:\n {\n Pera obj5 = new Pera();\n break;\n }\n case 1:\n {\n Pera obj4 = new Pera();\n break;\n }\n case 2:\n {\n Banana obj3 = default(Banana);\n break;\n }\n case 3:\n {\n object obj2 = (random.Next(0, 1) == 0) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance();\n break;\n }\n default:\n {\n Banana obj = default(Banana);\n break;\n }\n }\n }\ntime.Stop();\nreturn time.Elapsed.ToString();\n}\n static void Main(string[] args)\n {\n Executa exec = new Executa(); \n int x = 0;\n int times = 4;\n int count = 100000000;\n int[] intanceType = new int[4] { 0, 1, 2, 3 };\n\n while(x < times)\n { \n Parallel.For(0, intanceType.Length, (i) => {\n Console.WriteLine($\"Tentativa:{x} Tipo de Instancia: {intanceType[i]} Tempo Execução: {exec.Exec(count, intanceType[i])}\");\n });\n x++;\n }\n\n Console.ReadLine();\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40814/"
] |
356,851 | <p>I have been given a DLL ("InfoLookup.dll") that internally allocates structures and returns pointers to them from a lookup function. The structures contain string pointers:</p>
<pre><code>extern "C"
{
struct Info
{
int id;
char* szName;
};
Info* LookupInfo( int id );
}
</code></pre>
<p>In C#, how can I declare the structure layout, declare the Interop call, and (assuming a non-null value is returned) utilize the string value? In other words, how do I translate the following into C#?</p>
<pre><code>#include "InfoLookup.h"
void foo()
{
Info* info = LookupInfo( 0 );
if( info != 0 && info->szName != 0 )
DoSomethingWith( info->szName );
// NOTE: no cleanup here, the DLL is caching the lookup table internally
}
</code></pre>
| [
{
"answer_id": 356874,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": -1,
"selected": false,
"text": "using System.Runtime.InteropServices;\n\n[DllImport(\"mydll.dll\")]\npublic static extern Info LookupInfo(int val);\n\n[StructLayout(LayoutKind.Sequential)]\nstruct Info\n{\n int id;\n String szName;\n}\n\nprivate void SomeFunction\n{\n Info info = LookupInfo(0);\n //Note here that the returned struct cannot be null, so check the ID instead\n if (info.id != 0 && !String.IsNullOrEmpty(info.szName))\n DoSomethingWith(info.szName);\n}\n"
},
{
"answer_id": 356893,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "SHARE_INFO_502 public string shi502_netname"
},
{
"answer_id": 356911,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": true,
"text": "[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct Info {\n\n /// int\n public int id;\n\n /// char*\n [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]\n public string szName;\n}\n\npublic partial class NativeMethods {\n\n /// Return Type: Info*\n ///id: int\n [System.Runtime.InteropServices.DllImportAttribute(\"InfoLookup.dll\", EntryPoint=\"LookupInfo\")]\npublic static extern System.IntPtr LookupInfo(int id) ;\n\n public static LoopInfoWrapper(int id) {\n IntPtr ptr = LookupInfo(id);\n return (Info)(Marshal.PtrToStructure(ptr, typeof(Info));\n }\n\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
356,882 | <p>I've looked at every question so far and none seem to actually answer this question.</p>
<p>I created a UITabBarController and added several view controllers to it. Most of the views are viewed in portrait, but one should be viewed in landscape. I don't want to use the accelerometer or detect when the user rotates the device, I just want to display the view in landscape mode when they choose that view from the tab at the bottom.</p>
<p>I want the regular animations to occur, such as the tab dropping out, the view rotating, etc., when they choose that item, and the opposite to happen when they choose a different view.</p>
<p>Is there not a built-in property or method to tell the system what orientation to display the view as?</p>
<p>Overriding the shouldautorotate... method does absolutely nothing so far as I can tell.</p>
<p>The type of answer I would NOT appreciate is "RTFM" because I already have, and anybody who's developed for the iPhone so far knows that there is very little useful M to F-ing R.</p>
| [
{
"answer_id": 356903,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": true,
"text": "CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation(degreesToRadian(90));\nlandscapeTransform = CGAffineTransformTranslate (landscapeTransform, +80.0, +100.0);\n\n[[appDelegate navController].view setTransform:landscapeTransform];\n"
},
{
"answer_id": 464048,
"author": "Bdebeez",
"author_id": 35516,
"author_profile": "https://Stackoverflow.com/users/35516",
"pm_score": 3,
"selected": false,
"text": "#define degreesToRadian(x) (M_PI * (x) / 180.0)\n [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]; \nif (self.interfaceOrientation == UIInterfaceOrientationPortrait) { \n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));\n self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);\n}\n [UIView beginAnimations:@\"View Flip\" context:nil];\n[UIView setAnimationDuration:1.25];\n[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];\n\n[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]; \nif (self.interfaceOrientation == UIInterfaceOrientationPortrait) { \n self.view.transform = CGAffineTransformIdentity;\n self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(90));\n self.view.bounds = CGRectMake(0.0, 0.0, 480, 320);\n}\n[UIView commitAnimations];\n"
},
{
"answer_id": 8857229,
"author": "oberthelot",
"author_id": 735097,
"author_profile": "https://Stackoverflow.com/users/735097",
"pm_score": 0,
"selected": false,
"text": "- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation \n{\n // Overriden to allow any orientation.\n return UIInterfaceOrientationIsLandscape(interfaceOrientation);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36007/"
] |
356,883 | <p>Is there any way to change the taskbar icon of a browser in windows?</p>
<p>I open alot of browser windows, and I like to group similar websites (in tabs) by window. So I was wondering if there was a way to assign a taskbar icon to them so that you can more easily differentiate between them. </p>
| [
{
"answer_id": 357177,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 4,
"selected": true,
"text": "[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\npublic static extern IntPtr FindWindow(string strClassName, string strWindowName);\n\n[DllImport(\"user32.dll\",CharSet=CharSet.Auto)] \nprivate static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); \n\n[DllImport(\"user32.dll\")] \npublic static extern int DrawMenuBar(int currentWindow);\n\n\nconst int WM_GETICON = 0x7F;\nconst int WM_SETICON = 0x80;\nconst int ICON_SMALL = 0; //16\nconst int ICON_BIG = 1; //32\n\npublic static void SetIcon()\n{\n //Load an icon. This has to be a *.ico.\n System.Drawing.Icon i = new Icon(\"path\\to\\icon\");\n //Find the target window. The caption must be entered exactly \n //as it appears in the title bar\n IntPtr hwnd = FindWindow(null, \"Caption of Target Window\");\n //Set the icon\n SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_SMALL, (IntPtr)i.Handle);\n //Update the title bar with the new icon. Note: the taskbar will\n //update without this, you only need this if you want the title\n //bar to also display the new icon\n DrawMenuBar((int)hwnd);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18149/"
] |
356,886 | <p>I'm using CFHTTP to post data to my payment gateway (Protx).</p>
<p>Protx requires that I whitelist the IP that will send this request.</p>
<p>I am hosted on a shared server running Windows 2008.</p>
<p>This morning, my hosting company assigned a new IP to this server for a customer who required an SSL certificate.
Since then, my CFHTTP post appears to be coming from this new IP (which was not on the Protx whitelist).</p>
<p>My hosting company, being the worst imaginable, doesn't know why this is and aren't willing to look into it further.</p>
<p>Does anyone have any idea how I can specify which referring IP address CFHTTP will use to post data?</p>
| [
{
"answer_id": 357177,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 4,
"selected": true,
"text": "[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\npublic static extern IntPtr FindWindow(string strClassName, string strWindowName);\n\n[DllImport(\"user32.dll\",CharSet=CharSet.Auto)] \nprivate static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); \n\n[DllImport(\"user32.dll\")] \npublic static extern int DrawMenuBar(int currentWindow);\n\n\nconst int WM_GETICON = 0x7F;\nconst int WM_SETICON = 0x80;\nconst int ICON_SMALL = 0; //16\nconst int ICON_BIG = 1; //32\n\npublic static void SetIcon()\n{\n //Load an icon. This has to be a *.ico.\n System.Drawing.Icon i = new Icon(\"path\\to\\icon\");\n //Find the target window. The caption must be entered exactly \n //as it appears in the title bar\n IntPtr hwnd = FindWindow(null, \"Caption of Target Window\");\n //Set the icon\n SendMessage(hwnd, WM_SETICON, (IntPtr)ICON_SMALL, (IntPtr)i.Handle);\n //Update the title bar with the new icon. Note: the taskbar will\n //update without this, you only need this if you want the title\n //bar to also display the new icon\n DrawMenuBar((int)hwnd);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22113/"
] |
356,928 | <p>I am writing a key record look up where the I have an index between the key and the rec number. This is sorted on the key. Is there away to do this better that what I have for speed optimization?</p>
<pre><code>typedef struct
{
char key[MAX_KEYLEN];
int rec;
} KeyRecPair;
typedef struct
{
KeyRecPair *map;
int numRecs;
} KeyRecMap;
int GetRecFromKey(char *key, KeyRecMap *theMap)
{
int cmpValue, bottom = 0;
int half = theMap->numRecs / 2;
int top = theMap->numRecs - 1;
while (bottom != top)
{
cmpValue = strncmp(key, theMap->map[half].key, MAX_KEY_LEN);
if (cmpValue > 0)
{
/*top stays*/
bottom = half + 1;
half = bottom + (top - bottom) / 2;
continue;
}
if (cmpValue < 0)
{
/*bottom stays*/
top = half - 1;
half = bottom + (top - bottom) / 2;
continue;
}
return theMap->map[half].rec;
}
if (0 == strncmp(key, theMap->map[half].key, MAX_KEY_LEN))
return theMap->map[half].rec;
return 0;
}
</code></pre>
| [
{
"answer_id": 356944,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "bsearch"
},
{
"answer_id": 358906,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 0,
"selected": false,
"text": "half if (cmpValue > 0)\n {\n /*top stays*/\n bottom = half + 1;\n half = bottom + (top - bottom) * 3 / 5;\n continue;\n }\n if (cmpValue < 0)\n {\n /*bottom stays*/\n top = half - 1;\n half = bottom + (top - bottom) * 2 / 5;\n continue;\n }\n"
},
{
"answer_id": 359018,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "half"
},
{
"answer_id": 360787,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 0,
"selected": false,
"text": "; 30 : if (cmpValue > 0)\ntest eax, eax\njle SHORT $LN11@GetRecFrom\n; 31 : {\n; omitted inner block for > case.\n$LN11@GetRecFrom:\n; 37 : if (cmpValue < 0)\njge SHORT $LN2@GetRecFrom\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] |
356,929 | <p>I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good.</p>
<p>Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row event. </p>
<p>Is this possible?</p>
| [
{
"answer_id": 356943,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": true,
"text": "If Exists ( Select * From OtherTable\n Where OtherTableFKColumn = MainTablePrimaryKey) \n Begin\n Rollback Transaction\n RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)\n End\n"
},
{
"answer_id": 356945,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "COUNT(*)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6482/"
] |
356,938 | <p>When writing fairly typical Mac code in an OS X 10.5+ environment, what are the disadvantages to using garbage collection?</p>
<p>So far everything else I've written has been either 10.4 compatible or on the iPhone, so I've become fairly comfortable with retain/release, but now that I'm working on a larger project that's 10.5 only I'm wondering if there are any downsides to just going ahead and using the Objective-C 2.0 garbage collector.</p>
<p>What do you guys think?</p>
| [
{
"answer_id": 358910,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 5,
"selected": true,
"text": "-retain -release"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
356,947 | <p>Can someone help me identify what the purpose of this unidentified syntax is. It is an extra little something in the constructor for this object. What I'm trying to figure out is what is the "< IdT >" at the end of the class declaration line? I think that this is something I would find useful, I just need to understand what it is why so many people seem to do this.</p>
<pre><code>using BasicSample.Core.Utils;
namespace BasicSample.Core.Domain
{
/// <summary>
/// For a discussion of this object, see
/// http://devlicio.us/blogs/billy_mccafferty/archive/2007/04/25/using-equals-gethashcode-effectively.aspx
/// </summary>
public abstract class DomainObject<IdT>
{
/// <summary>
/// ID may be of type string, int, custom type, etc.
/// Setter is protected to allow unit tests to set this property via reflection and to allow
/// domain objects more flexibility in setting this for those objects with assigned IDs.
/// </summary>
public IdT ID {
get { return id; }
protected set { id = value; }
}
</code></pre>
| [
{
"answer_id": 356971,
"author": "gcores",
"author_id": 40256,
"author_profile": "https://Stackoverflow.com/users/40256",
"pm_score": 3,
"selected": true,
"text": "new DomainObject<string>(); \n"
},
{
"answer_id": 357009,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "int long Guid"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42987/"
] |
356,948 | <p>I'm building a .NET 3.5 application and have the need to evaluate JS code on the server - basically a user provided rule set that can work within a browser or on the server. Managed JS is not an option, because the JS code would be provided at runtime. Aptana's Jaxer is also not an option. So I was looking into using a build of the V8 engine within my app.</p>
<p>I built the source successfully into a DLL, but that DLL is not not a managed library and is not COM either. V8 is just plain C++.</p>
<p>Any ideas as to how to interop with this type of DLL in C#? Also, I'm open to other suggestions for SpiderMonkey or another JS engine.</p>
<p>Thanks in advance.</p>
<p><strong>UPDATE:</strong></p>
<p>I was able to use Ryan's solution. I just updated the references to the build for the latest from trunk. It worked great. Thanks Ryan.</p>
| [
{
"answer_id": 357284,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 6,
"selected": true,
"text": "V8DotNet.Shell shell = new V8DotNet.Shell();\n\nshell.ExecuteScript(@\"print('V8 version is: ' + version());\");\n"
},
{
"answer_id": 51468616,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "using (var engine = new JsEngine())\n{\n using (var context = engine.CreateContext())\n {\n var x = (double)context.Execute(\"3.14159+2.71828\");\n Console.WriteLine(x); // prints 5.85987\n }\n}\n using (JsEngine js = new JsEngine(4, 32))\n{\n using (JsContext context = js.CreateContext())\n {\n // Create a global variable on the JS side.\n context.Execute(\"var x = {'answer':42, 'tellme':function (x) { return x+' '+this.answer; }}\");\n // Get it and use \"dynamic\" to tell the compiler to use runtime binding.\n dynamic x = context.GetVariable(\"x\");\n // Call the method and print the result. This will print:\n // \"What is the answer to ...? 42\"\n Console.WriteLine(x.tellme(\"What is the answer to ...?\"));\n }\n}\n class Test\n{\n public int Value { get; set; }\n public void PrintValue(string msg)\n {\n Console.WriteLine(msg+\" \"+Value);\n }\n}\n\nusing (JsEngine js = new JsEngine(4, 32))\n{\n using (JsContext context = js.CreateContext())\n {\n context.SetVariable(\"m\", new Test());\n // Sets the property from Javascript.\n context.Execute(\"m.Value = 42\");\n // Call a method on the CLR object from Javascript. This prints:\n // \"And the answer is (again!): 42\"\n context.Execute(\"m.PrintValue('And the answer is (again!):')\");\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30544/"
] |
356,950 | <p>I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?</p>
| [
{
"answer_id": 356992,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 7,
"selected": false,
"text": "operator() class MyFunctor\n{\n public:\n int operator()(int x) { return x * 2;}\n}\n\nMyFunctor doubler;\nint x = doubler(5);\n class Matcher\n{\n int target;\n public:\n Matcher(int m) : target(m) {}\n bool operator()(int x) { return x == target;}\n}\n\nMatcher Is5(5);\n\nif (Is5(n)) // same as if (n == 5)\n{ ....}\n"
},
{
"answer_id": 356993,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 11,
"selected": true,
"text": "// this is a functor\nstruct add_x {\n add_x(int val) : x(val) {} // Constructor\n int operator()(int y) const { return x + y; }\n\nprivate:\n int x;\n};\n\n// Now you can use it like this:\nadd_x add42(42); // create an instance of the functor class\nint i = add42(8); // and \"call\" it\nassert(i == 50); // and it added 42 to its argument\n\nstd::vector<int> in; // assume this contains a bunch of values)\nstd::vector<int> out(in.size());\n// Pass a functor to std::transform, which calls the functor on every element \n// in the input sequence, and stores the result to the output sequence\nstd::transform(in.begin(), in.end(), out.begin(), add_x(1)); \nassert(out[i] == in[i] + 1); // for all i\n std::transform add_x::operator()"
},
{
"answer_id": 357022,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 5,
"selected": false,
"text": "MultiplyBy class MultiplyBy {\nprivate:\n int factor;\n\npublic:\n MultiplyBy(int x) : factor(x) {\n }\n\n int operator () (int other) const {\n return factor * other;\n }\n};\n MultiplyBy int array[5] = {1, 2, 3, 4, 5};\nstd::transform(array, array + 5, array, MultiplyBy(3));\n// Now, array is {3, 6, 9, 12, 15}\n transform"
},
{
"answer_id": 357223,
"author": "Evgeny Lazin",
"author_id": 42371,
"author_profile": "https://Stackoverflow.com/users/42371",
"pm_score": 7,
"selected": false,
"text": "boost::function class Foo\n{\npublic:\n void operator () (int i) { printf(\"Foo %d\", i); }\n};\nvoid Bar(int i) { printf(\"Bar %d\", i); }\nFoo foo;\nboost::function<void (int)> f(foo);//wrap functor\nf(1);//prints \"Foo 1\"\nboost::function<void (int)> b(&Bar);//wrap normal function\nb(1);//prints \"Bar 1\"\n boost::function<void ()> f1 = boost::bind(foo, 2);\nf1();//no more argument, function argument stored in f1\n//and this print \"Foo 2\" (:\n//and normal function\nboost::function<void ()> b1 = boost::bind(&Bar, 2);\nb1();// print \"Bar 2\"\n class SomeClass\n{\n std::string state_;\npublic:\n SomeClass(const char* s) : state_(s) {}\n\n void method( std::string param )\n {\n std::cout << state_ << param << std::endl;\n }\n};\nSomeClass *inst = new SomeClass(\"Hi, i am \");\nboost::function< void (std::string) > callback;\ncallback = boost::bind(&SomeClass::method, inst, _1);//create delegate\n//_1 is a placeholder it holds plase for parameter\ncallback(\"useless\");//prints \"Hi, i am useless\"\n std::list< boost::function<void (EventArg e)> > events;\n//add some events\n....\n//call them\nstd::for_each(\n events.begin(), events.end(), \n boost::bind( boost::apply<void>(), _1, e));\n"
},
{
"answer_id": 7670373,
"author": "Guido Tarsia",
"author_id": 796608,
"author_profile": "https://Stackoverflow.com/users/796608",
"pm_score": 2,
"selected": false,
"text": "pthread_create(..) class::method void* method(void* something)\n Thread MyClass Functor Thread static void* startThread(void* arg) pthread_create(..) startThread(..) void* Functor Functor* run()"
},
{
"answer_id": 14164137,
"author": "Johanne Irish",
"author_id": 1524907,
"author_profile": "https://Stackoverflow.com/users/1524907",
"pm_score": 6,
"selected": false,
"text": "() operator () operator + operator () operator () operator class myFunctor\n{ \n public:\n /* myFunctor is the constructor. parameterVar is the parameter passed to\n the constructor. : is the initializer list operator. myObject is the\n private member object of the myFunctor class. parameterVar is passed\n to the () operator which takes it and adds it to myObject in the\n overloaded () operator function. */\n myFunctor (int parameterVar) : myObject( parameterVar ) {}\n\n /* the \"operator\" word is a keyword which indicates this function is an \n overloaded operator function. The () following this just tells the\n compiler that () is the operator being overloaded. Following that is\n the parameter for the overloaded operator. This parameter is actually\n the argument \"parameterVar\" passed by the constructor we just wrote.\n The last part of this statement is the overloaded operators body\n which adds the parameter passed to the member object. */\n int operator() (int myArgument) { return myObject + myArgument; }\n\n private: \n int myObject; //Our private member object.\n}; \n"
},
{
"answer_id": 14556859,
"author": "Alex Punnen",
"author_id": 429476,
"author_profile": "https://Stackoverflow.com/users/429476",
"pm_score": 1,
"selected": false,
"text": "int CTask::ThreeParameterTask(int par1, int par2, int par3)\n // a template class for converting a member function of the type int function(int,int,int)\n//to be called as a function object\ntemplate<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>\nclass mem_fun3_t\n{\n public:\nexplicit mem_fun3_t(_Ret (_Class::*_Pm)(_arg1,_arg2,_arg3))\n :m_Ptr(_Pm) //okay here we store the member function pointer for later use\n {}\n\n//this operator call comes from the bind method\n_Ret operator()(_Class *_P, _arg1 arg1, _arg2 arg2, _arg3 arg3) const\n{\n return ((_P->*m_Ptr)(arg1,arg2,arg3));\n}\nprivate:\n_Ret (_Class::*m_Ptr)(_arg1,_arg2,_arg3);// method pointer signature\n};\n mem_fun3 template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>\nmem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3> mem_fun3 ( _Ret (_Class::*_Pm) (_arg1,_arg2,_arg3) )\n{\n return (mem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3>(_Pm));\n}\n template<typename _Func,typename _Ptr,typename _arg1,typename _arg2,typename _arg3>\nclass binder3\n{\npublic:\n//This is the constructor that does the binding part\nbinder3(_Func fn,_Ptr ptr,_arg1 i,_arg2 j,_arg3 k)\n :m_ptr(ptr),m_fn(fn),m1(i),m2(j),m3(k){}\n\n //and this is the function object \n void operator()() const\n {\n m_fn(m_ptr,m1,m2,m3);//that calls the operator\n }\nprivate:\n _Ptr m_ptr;\n _Func m_fn;\n _arg1 m1; _arg2 m2; _arg3 m3;\n};\n bind3 //a helper function to call binder3\ntemplate <typename _Func, typename _P1,typename _arg1,typename _arg2,typename _arg3>\nbinder3<_Func, _P1, _arg1, _arg2, _arg3> bind3(_Func func, _P1 p1,_arg1 i,_arg2 j,_arg3 k)\n{\n return binder3<_Func, _P1, _arg1, _arg2, _arg3> (func, p1,i,j,k);\n}\n typedef binder3<mem_fun3_t<int,T,int,int,int> ,T* ,int,int,int> F3;\n//and change the signature of the ctor\n//just to illustrate the usage with a method signature taking more than one parameter\nexplicit Command(T* pObj,F3* p_method,long timeout,const char* key,\nlong priority = PRIO_NORMAL ):\nm_objptr(pObj),m_timeout(timeout),m_key(key),m_value(priority),method1(0),method0(0),\nmethod(0)\n{\n method3 = p_method;\n}\n F3 f3 = PluginThreadPool::bind3( PluginThreadPool::mem_fun3( \n &CTask::ThreeParameterTask), task1,2122,23 );\n f3(); task1->ThreeParameterTask(21,22,23);"
},
{
"answer_id": 16392660,
"author": "Paul Fultz II",
"author_id": 375343,
"author_profile": "https://Stackoverflow.com/users/375343",
"pm_score": 5,
"selected": false,
"text": "std::vector template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>\nstd::vector<U> fmap(F f, const std::vector<T>& vec)\n{\n std::vector<U> result;\n std::transform(vec.begin(), vec.end(), std::back_inserter(result), f);\n return result;\n}\n std::vector<T> std::vector<U> F T U std::shared_ptr template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>\nstd::shared_ptr<U> fmap(F f, const std::shared_ptr<T>& p)\n{\n if (p == nullptr) return nullptr;\n else return std::shared_ptr<U>(new U(f(*p)));\n}\n double double to_double(int x)\n{\n return x;\n}\n\nstd::shared_ptr<int> i(new int(3));\nstd::shared_ptr<double> d = fmap(to_double, i);\n\nstd::vector<int> is = { 1, 2, 3 };\nstd::vector<double> ds = fmap(to_double, is);\n fmap(identity, x) identity(x) struct identity_f\n{\n template<class T>\n T operator()(T x) const\n {\n return x;\n }\n};\nidentity_f identity = {};\n\nstd::vector<int> is = { 1, 2, 3 };\n// These two statements should be equivalent.\n// is1 should equal is2\nstd::vector<int> is1 = fmap(identity, is);\nstd::vector<int> is2 = identity(is);\n fmap(std::bind(f, std::bind(g, _1)), x) fmap(f, fmap(g, x)) double to_double(int x)\n{\n return x;\n}\n\nstruct foo\n{\n double x;\n};\n\nfoo to_foo(double x)\n{\n foo r;\n r.x = x;\n return r;\n}\n\nstd::vector<int> is = { 1, 2, 3 };\n// These two statements should be equivalent.\n// is1 should equal is2\nstd::vector<foo> is1 = fmap(std::bind(to_foo, std::bind(to_double, _1)), is);\nstd::vector<foo> is2 = fmap(to_foo, fmap(to_double, is));\n"
},
{
"answer_id": 21642334,
"author": "nfries88",
"author_id": 2658887,
"author_profile": "https://Stackoverflow.com/users/2658887",
"pm_score": 2,
"selected": false,
"text": "/* prints \"this is a very simple and poorly used task queue\" */\nclass Functor\n{\npublic:\n std::string output;\n Functor(const std::string& out): output(out){}\n operator()() const\n {\n std::cout << output << \" \";\n }\n};\n\nint main(int argc, char **argv)\n{\n std::list<Functor> taskQueue;\n taskQueue.push_back(Functor(\"this\"));\n taskQueue.push_back(Functor(\"is a\"));\n taskQueue.push_back(Functor(\"very simple\"));\n taskQueue.push_back(Functor(\"and poorly used\"));\n taskQueue.push_back(Functor(\"task queue\"));\n for(std::list<Functor>::iterator it = taskQueue.begin();\n it != taskQueue.end(); ++it)\n {\n *it();\n }\n return 0;\n}\n\n/* prints the value stored in \"i\", then asks you if you want to increment it */\nint i;\nbool should_increment;\nint doSomeWork()\n{\n std::cout << \"i = \" << i << std::endl;\n std::cout << \"increment? (enter the number 1 to increment, 0 otherwise\" << std::endl;\n std::cin >> should_increment;\n return 2;\n}\nvoid doSensitiveWork()\n{\n ++i;\n should_increment = false;\n}\nclass BaseCoroutine\n{\npublic:\n BaseCoroutine(int stat): status(stat), waiting(false){}\n void operator()(){ status = perform(); }\n int getStatus() const { return status; }\nprotected:\n int status;\n bool waiting;\n virtual int perform() = 0;\n bool await_status(BaseCoroutine& other, int stat, int change)\n {\n if(!waiting)\n {\n waiting = true;\n }\n if(other.getStatus() == stat)\n {\n status = change;\n waiting = false;\n }\n return !waiting;\n }\n}\n\nclass MyCoroutine1: public BaseCoroutine\n{\npublic:\n MyCoroutine1(BaseCoroutine& other): BaseCoroutine(1), partner(other){}\nprotected:\n BaseCoroutine& partner;\n virtual int perform()\n {\n if(getStatus() == 1)\n return doSomeWork();\n if(getStatus() == 2)\n {\n if(await_status(partner, 1))\n return 1;\n else if(i == 100)\n return 0;\n else\n return 2;\n }\n }\n};\n\nclass MyCoroutine2: public BaseCoroutine\n{\npublic:\n MyCoroutine2(bool& work_signal): BaseCoroutine(1), ready(work_signal) {}\nprotected:\n bool& work_signal;\n virtual int perform()\n {\n if(i == 100)\n return 0;\n if(work_signal)\n {\n doSensitiveWork();\n return 2;\n }\n return 1;\n }\n};\n\nint main()\n{\n std::list<BaseCoroutine* > coroutineList;\n MyCoroutine2 *incrementer = new MyCoroutine2(should_increment);\n MyCoroutine1 *printer = new MyCoroutine1(incrementer);\n\n while(coroutineList.size())\n {\n for(std::list<BaseCoroutine *>::iterator it = coroutineList.begin();\n it != coroutineList.end(); ++it)\n {\n *it();\n if(*it.getStatus() == 0)\n {\n coroutineList.erase(it);\n }\n }\n }\n delete printer;\n delete incrementer;\n return 0;\n}\n"
},
{
"answer_id": 41660282,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "operator() #include <string>\n#include <vector>\n#include <algorithm>\n\ntemplate <typename T>\nT min3(const T& a, const T& b, const T& c)\n{\n return std::min(std::min(a, b), c);\n}\n\nclass levenshtein_distance \n{\n mutable std::vector<std::vector<unsigned int> > matrix_;\n\npublic:\n explicit levenshtein_distance(size_t initial_size = 8)\n : matrix_(initial_size, std::vector<unsigned int>(initial_size))\n {\n }\n\n unsigned int operator()(const std::string& s, const std::string& t) const\n {\n const size_t m = s.size();\n const size_t n = t.size();\n // The distance between a string and the empty string is the string's length\n if (m == 0) {\n return n;\n }\n if (n == 0) {\n return m;\n }\n // Size the matrix as necessary\n if (matrix_.size() < m + 1) {\n matrix_.resize(m + 1, matrix_[0]);\n }\n if (matrix_[0].size() < n + 1) {\n for (auto& mat : matrix_) {\n mat.resize(n + 1);\n }\n }\n // The top row and left column are prefixes that can be reached by\n // insertions and deletions alone\n unsigned int i, j;\n for (i = 1; i <= m; ++i) {\n matrix_[i][0] = i;\n }\n for (j = 1; j <= n; ++j) {\n matrix_[0][j] = j;\n }\n // Fill in the rest of the matrix\n for (j = 1; j <= n; ++j) {\n for (i = 1; i <= m; ++i) {\n unsigned int substitution_cost = s[i - 1] == t[j - 1] ? 0 : 1;\n matrix_[i][j] =\n min3(matrix_[i - 1][j] + 1, // Deletion\n matrix_[i][j - 1] + 1, // Insertion\n matrix_[i - 1][j - 1] + substitution_cost); // Substitution\n }\n }\n return matrix_[m][n];\n }\n};\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
356,957 | <p>Here's the basic idea:</p>
<p>There is a java window (main) that opens another java window (child). When the child is created, part of the initialization sets the focus in the appropriate text field in the child window:</p>
<pre><code>childTextField.requestFocusInWindow();
childTextField.setCaretPosition(0);
</code></pre>
<p>The child is generally opened through a serious of keystrokes via a command line type interface. When the window is requested, 90%ish of the time, the focus correctly goes to the child window text field and the user can type in the box. If the command to open the child is sent off (with a press of the enter key) and the user immediately starts typing before the new window is created, the text is correctly buffered and appears in the new textfield after the window opens. </p>
<p>However, every once in a while when the user requests the child window to open and then starts typing, their text does NOT appear in the text field. Only after they click with the mouse in the field does the text they have typed appear. It's like it's being stored somewhere and doesn't come out until they click.</p>
<p>The real frustrating thing here is that I can't seem to reliably reproduce the issue at all. It definitely happens, but not regularly enough to debug nicely.</p>
<p>There is of course all kinds of other mojo going on behind the scenes, including communication with a server app, but I'm not convinced it's related.</p>
<p>Any thoughts or ideas would be very much appreciated.</p>
| [
{
"answer_id": 357019,
"author": "Chris Mattmiller",
"author_id": 43712,
"author_profile": "https://Stackoverflow.com/users/43712",
"pm_score": 1,
"selected": false,
"text": "init() EventQueue.invokeLater(new Runnable() {\n public void run() {\n childtextfield.requestFocus();\n childTextField.setCaretPosition(0);\n }\n});\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45077/"
] |
356,972 | <p>How do you format the date time to just date? </p>
<p>For example, this is what I retrieved from the database: 12/31/2008 12:00:00 AM, but I just want to show the date and no time.</p>
| [
{
"answer_id": 357349,
"author": "Rick",
"author_id": 1752,
"author_profile": "https://Stackoverflow.com/users/1752",
"pm_score": 4,
"selected": false,
"text": " Dim d As DateTime = Now\n Debug.WriteLine(d.ToLongDateString)\n Debug.WriteLine(d.ToShortDateString)\n Debug.WriteLine(d.ToString(\"d\"))\n Debug.WriteLine(d.ToString(\"yyyy-MM-dd\"))\n Wednesday, December 10, 2008\n12/10/2008\n12/10/2008\n2008-12-10\n"
},
{
"answer_id": 44598450,
"author": "Tony Dong",
"author_id": 760139,
"author_profile": "https://Stackoverflow.com/users/760139",
"pm_score": 3,
"selected": false,
"text": "CDate(YourDate.ToString(\"d\"))\n CDate(YourDate.ToShortDateString)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
356,974 | <p>I have a mystery on my hands. I am trying to learn managed C++ coming from a C# background and have run into a snag. If I have a project which includes two classes, a base class <strong>Soup</strong> and a derived class <strong>TomatoSoup</strong> which I compile as a static library (.lib), I get unresolved tokens on the virtual methods in <strong>Soup</strong>. Here is the code:</p>
<hr>
<h2>Abstracts.proj</h2>
<p><strong>Soup.h</strong></p>
<pre><code>namespace Abstracts
{
public ref class Soup abstract
{
public:
virtual void heat(int Degrees);
};
}
</code></pre>
<p><strong>TomatoSoup.h</strong></p>
<pre><code>#include "Soup.h"
namespace Abstracts
{
public ref class TomatoSoup : Abstracts::Soup
{
public:
virtual void heat(int Degrees) override;
};
}
</code></pre>
<p><strong>TomatoSoup.cpp</strong></p>
<pre><code>#include "TomatoSoup.h"
void Abstracts::TomatoSoup::heat(int Degrees)
{
System::Console::WriteLine("Soup's on.");
}
</code></pre>
<h2>Main.proj</h2>
<p><strong>Main.cpp</strong></p>
<pre><code>#include "TomatoSoup.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Abstracts::TomatoSoup^ ts = gcnew Abstracts::TomatoSoup();
return 0;
}
</code></pre>
<hr>
<p>I get this link-time error on <strong>Main.proj</strong>:</p>
<pre><code>1>Main.obj : error LNK2020: unresolved token (06000001) Abstracts.Soup::heat
</code></pre>
<ol>
<li><p>I've tried setting </p>
<pre><code>virtual void heat(int Degrees)=0;
</code></pre></li>
<li><p>I've tried implementing heat in the base class </p>
<pre><code>virtual void heat(int Degrees){}
</code></pre>
<p>and get an unreferenced formal
parameter warning treated as an
error.</p></li>
<li>I've tried both 1 and 2 with and
without the abstract keyword on the
Soup class</li>
</ol>
<p>This issue is driving me crazy and I hope to prevent it from driving other developers nuts in the future.</p>
<p><strong>UPDATE:</strong> This worked with Greg Hewgill's argument-name commenting method when the TomatoSoup::heat was implemented in the header file, but the error came back when I moved the implementation to TomatoSoup.cpp. I've modified the question to reflect that.</p>
| [
{
"answer_id": 357003,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "Abstracts.Soup::heat virtual void heat(int Degrees); virtual void heat(int Degrees) = 0;\n virtual void heat(int Degrees) {}\n virtual void heat(int /*Degrees*/) {}\n = 0"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] |
356,980 | <p>I have an Access Database that outputs a report in Excel format.</p>
<p>The report is dependent on a date parameter chosen by the user. This parameter is selected via a textbox (text100) that has a pop up calendar.</p>
<p>I would like to use the date in the text box (text100) in the filename.</p>
| [
{
"answer_id": 357039,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 3,
"selected": true,
"text": "Some Module\n\nDim vParam1 as variant\nDim vParam1 as variant\n\nPublic Sub ParameterSet(byval pParamName as String, byval pParamValue as variant)\n\nSelect Case pParamName \n Case \"Param1\": vParam1 = pParamValue \n Case \"Param2\": vParam2 = pParamValue \n Case Else\n msgbox pParamName & \" parameter not defined\"\nEnd Select\n\nEnd Sub\n\nPublic Function ParameterGet(byval pParamName as String) as variant\n\nSelect Case pParamName \n Case \"Param1\": ParamGet = vParam1 \n Case \"Param2\": ParamGet = vParam2 \n Case Else\n msgbox pParamName & \" parameter not defined\"\nEnd Select\n\nEnd Sub\n WHERE Field1 = ParameterGet(\"Param1\")\n Private Sub Export_Click()\n\n dim vParam1 as variant\n\n vParam1 = inputbox(\"Enter the parameter:\")\n\n ParameterSet \"param1\", vParam1\n\n Transferspreadsheet blah, blah, FileName:= vParam1 & \".xls\"\n\nEnd Sub\n"
},
{
"answer_id": 374807,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": 1,
"selected": false,
"text": "function toQueryDate(aFileName as String) as Date\nDim theQueryDate as Date\nDim theParsedDate as String\n\ntheParsedDate=Mid(aFileName,1,4)+\"/\"+Mid(aFileName,6,2)+\"/\"+Mid(aFileName,9,2)\n'IMPROVE:there's no error checking here.... we could see if the individual tokens are numbers\n\nOn Error Resume Next\ntheQueryDate=Cdate(theParsedDate)\nIf err.number then\n Msgbox \"Bad filename: \"+aFilename\n End 'or something else less fatal \nEndif\n\n'we should be OK so:\ntoQueryDate=theParsedDate\nEnd function\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44685/"
] |
356,982 | <p>I'm creating a multi-tenancy web site which hosts pages for clients. The first segment of the URL will be a string which identifies the client, defined in Global.asax using the following URL routing scheme:</p>
<pre><code>"{client}/{controller}/{action}/{id}"
</code></pre>
<p>This works fine, with URLs such as /foo/Home/Index.</p>
<p>However, when using the [Authorize] attribute, I want to redirect to a login page which also uses the same mapping scheme. So if the client is foo, the login page would be /foo/Account/Login instead of the fixed /Account/Login redirect defined in web.config.</p>
<p>MVC uses an HttpUnauthorizedResult to return a 401 unauthorised status, which I presume causes ASP.NET to redirect to the page defined in web.config.</p>
<p>So does anyone know either how to override the ASP.NET login redirect behaviour? Or would it be better to redirect in MVC by creating a custom authorization attribute?</p>
<p><strong>EDIT - Answer:</strong> after some digging into the .Net source, I decided that a custom authentication attribute is the best solution:</p>
<pre><code>public class ClientAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization( AuthorizationContext filterContext )
{
base.OnAuthorization( filterContext );
if (filterContext.Cancel && filterContext.Result is HttpUnauthorizedResult )
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "client", filterContext.RouteData.Values[ "client" ] },
{ "controller", "Account" },
{ "action", "Login" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}
</code></pre>
| [
{
"answer_id": 358554,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 6,
"selected": true,
"text": "FormsAuthentication.RedirectToLoginPage() RedirectToLoginPage() FormsAuthentication"
},
{
"answer_id": 1098132,
"author": "user134936",
"author_id": 134936,
"author_profile": "https://Stackoverflow.com/users/134936",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Resources;\n\nnamespace ePegasus.Web.ActionFilters\n{\n public class CustomAuthorize : AuthorizeAttribute\n {\n public override void OnAuthorization(AuthorizationContext filterContext)\n {\n base.OnAuthorization(filterContext);\n if (filterContext.Result is HttpUnauthorizedResult)\n {\n filterContext.Result = new RedirectToRouteResult(\n new System.Web.Routing.RouteValueDictionary\n {\n { \"langCode\", filterContext.RouteData.Values[ \"langCode\" ] },\n { \"controller\", \"Account\" },\n { \"action\", \"Login\" },\n { \"ReturnUrl\", filterContext.HttpContext.Request.RawUrl }\n });\n }\n }\n }\n}\n <forms loginUrl=\"~/Account/ERROR\" timeout=\"2880\" />\n"
},
{
"answer_id": 3266491,
"author": "Kieron",
"author_id": 5791,
"author_profile": "https://Stackoverflow.com/users/5791",
"pm_score": 2,
"selected": false,
"text": "ActionResult sealed public class RequiresLoginResult : ActionResult\n {\n override public void ExecuteResult (ControllerContext context)\n {\n var response = context.HttpContext.Response;\n\n var url = FormsAuthentication.LoginUrl;\n if (!string.IsNullOrWhiteSpace (url))\n url += \"?returnUrl=\" + HttpUtility.UrlEncode (ReturnUrl);\n\n response.Clear ();\n response.StatusCode = 302;\n response.RedirectLocation = url;\n }\n\n public RequiresLoginResult (string returnUrl = null)\n {\n ReturnUrl = returnUrl;\n }\n\n string ReturnUrl { get; set; }\n }\n"
},
{
"answer_id": 54588074,
"author": "turdus-merula",
"author_id": 1475331,
"author_profile": "https://Stackoverflow.com/users/1475331",
"pm_score": 0,
"selected": false,
"text": "Application_AuthenticateRequest Global.asax.cs protected void Application_AuthenticateRequest(object sender, EventArgs e)\n{\n string url = Request.RawUrl;\n\n if (url.Contains((\"Account/Login\"))\n {\n return;\n }\n\n if (Context.User == null)\n {\n // Your custom tenant-aware logic\n if (url.StartsWith(\"/foo\"))\n {\n // Your custom login page.\n Response.Redirect(\"/foo/Account/Login\");\n Response.End();\n return;\n }\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43649/"
] |
357,033 | <p>I'm trying to do a Data Binding in the C# code behind rather than the XAML. The XAML binding created in Expression Blend 2 to my CLR object works fine. My C# implementation only updates when the application is started after which subsequent changes to the CLR doesn't update my label content. </p>
<p>Here's the working XAML binding.
First a ObjectDataProvider is made in my Window.Resources.</p>
<pre><code><ObjectDataProvider x:Key="PhoneServiceDS"
ObjectType="{x:Type kudu:PhoneService}" d:IsDataSource="True"/>
</code></pre>
<p>And the label content binding:</p>
<pre><code><Label x:Name="DisplayName" Content="{Binding
Path=MyAccountService.Accounts[0].DisplayName, Mode=OneWay,
Source={StaticResource PhoneServiceDS}}"/>
</code></pre>
<p>Works great. But we want this set up in C# so we can independently change the XAML (ie. new skins). My one time working C# as follows:</p>
<pre><code> Binding displayNameBinding = new Binding();
displayNameBinding.Source =
PhoneService.MyAccountService.Accounts[0].DisplayName;
displayNameBinding.Mode = BindingMode.OneWay;
this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding);
</code></pre>
<p>This is inside my MainWindow after InitializeComponent();</p>
<p>Any insight why this only works on startup?</p>
| [
{
"answer_id": 357158,
"author": "devios1",
"author_id": 238948,
"author_profile": "https://Stackoverflow.com/users/238948",
"pm_score": 3,
"selected": true,
"text": "Binding displayNameBinding = new Binding( \"MyAccountService.Accounts[0].DisplayName\" );\ndisplayNameBinding.Source = new ObjectDataProvider { ObjectType = typeof(PhoneService), IsDataSource = true };\ndisplayNameBinding.Mode = BindingMode.OneWay;\nthis.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding);\n"
},
{
"answer_id": 408731,
"author": "Daniel Paull",
"author_id": 43066,
"author_profile": "https://Stackoverflow.com/users/43066",
"pm_score": 1,
"selected": false,
"text": " Binding displayNameBinding = new Binding();\n displayNameBinding.Source = PhoneService;\n displayNameBinding.Path = \"MyAccountService.Accounts[0].DisplayName\";\n displayNameBinding.Mode = BindingMode.OneWay;\n this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36234/"
] |
357,041 | <p>I have LINQ statement that looks like this:</p>
<pre><code>return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
</code></pre>
<p>I'd like to be able to abstract out the select into its own method so that I can have different "mapping" option. What does my method need to return?</p>
<p>In essence, I'd like my LINQ query to look like this:</p>
<pre><code>return ( from c in customers select new Mapper(c));
</code></pre>
<p><strong>Edit:</strong></p>
<p>This is for LINQ to SQL.</p>
| [
{
"answer_id": 357091,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 1,
"selected": false,
"text": "Expression < Func<TSource, TResult> > Expression<Func<CustomerTable, Customer>> someMappingExpression = c => new Customer { Name = c.Name };\nreturn context.CustomerTable.Select(someMappingExpression);\n Select Func Expression Select Expression<Func> Func"
},
{
"answer_id": 357417,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": true,
"text": "IQueryable<T> Func<In, Out> Expression<Func<In, Out>> private static readonly Expression<Func<CustomerInfo, string>> GetName = c => c.Name;\n\nprivate static readonly Expression<Func<CustomerInfo, ClientEntity>> GetEntity = c => new ClientEntity { Name = c.Name, ... };\n var names = customers.Select(GetName);\n\nvar entities = customers.Select(GetEntity);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
357,046 | <p>i have a Sharepoint feature that essentially extends Lists with a new feature, using a List receiver. For each list the feature is attached to, i need to store some configuration.</p>
<p>Now, the first thing that came into my mind is the obvious solution: Have a global list. That works of course, but I wonder if there is some way to store feature-specific configuration in a hidden place? Not that it's sensitive information, but I don't want to clutter the Users Display with too many lists. I believe I can hide lists, but at the same time I wonder if sharepoint allows me to use it's database?</p>
<p>I am not talking about just using ADO.net to access the db directly (which is a big no-no with Sharepoint), I am thinking about some officially supported mechanism.</p>
| [
{
"answer_id": 357083,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 1,
"selected": false,
"text": "string sAdminEmail = ConfigStore.GetValue(\"MyApplication\", \"AdminEmail\");\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
357,048 | <p>I have two tables, we'll call them <code>Foo</code> and <code>Bar</code>, with a one to many relationship where <code>Foo</code> is the parent of <code>Bar</code>. Foo's primary key is an integer automatically generated with a sequence. </p>
<p>Since <code>Bar</code> is fully dependent on <code>Foo</code> how would I setup the primary key of <code>Bar</code> given the following constraints:</p>
<ul>
<li>Records for Bar are programatically
generated so user input can not be
relied upon for an identifier.</li>
<li>Multiple processes are generating
Bar records so anything involving a
<code>Select Max()</code> to generate an <code>ID</code> would
present a race condition.</li>
</ul>
<p>I have come up with two possible solutions that I am not happy with:</p>
<ul>
<li>Treat the tables as if they are a
many to many relationship with a
third table that maps their records
together and have the application
code handle inserting records so
that the mapping between the records
is created correctly. I don't like
this as it makes the database design
misleading and errors in application
code could result in invalid data.</li>
<li>Give Bar two colunms: <code>FooID</code> and
<code>FooBarID</code> and generate a value for
<code>FooBarID</code> by selecting the
<code>max(FooBarID)+1</code> for some <code>FooID</code>, but
as previously stated this creates a
race condition.</li>
</ul>
<p>I appreciate any ideas for an alternative table layout.</p>
| [
{
"answer_id": 357080,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "create table SystemCounter \n( \n SystemCounterId int identity not null, \n BarIdAllocator int \n)\n--initialize SystemCounter to have one record with SystemCounterId = 1\n--and BarIdAllocator = 0\ninsert into SystemCounter values (1,0)\n--id allocator procedure\ncreate procedure GetNextBarId ( @BarId int output ) AS\n SET NOCOUNT ON\n begin tran\n update SystemCounter set \n @BarId = BarIdAllocator = BarIdAllocator + 1\n where SystemCounterId = 1\n commit\nGO\n @BarId = BarIdAllocator = BarIdAllocator + 1\n begin tran\n update SystemCounter set \n BarIdAllocator = BarIdAllocator + 1\n where SystemCounterId = 1\n select \n @BarId = BarIdAllocator\n from SystemCounter\n where SystemCounterId = 1\ncommit\n"
},
{
"answer_id": 357089,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO Foo (foo_id, othercolumn)\n VALUES ( FooSeq.NextVal(), 'yadda yadda');\n\nINSERT INTO Bar (bar_id, foo_id, extracolumn)\n VALUES ( BarSeq.NextVal(), FooSeq.CurrVal(), 'blah blah');\nINSERT INTO Bar (bar_id, foo_id, extracolumn)\n VALUES ( BarSeq.NextVal(), FooSeq.CurrVal(), 'bling bling');\nINSERT INTO Bar (bar_id, foo_id, extracolumn)\n VALUES ( BarSeq.NextVal(), FooSeq.CurrVal(), 'baz baz');\n CURRVAL() CURRVAL()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
357,049 | <p>I have a simple email address sign up form as follows:</p>
<pre><code><form action="" id="newsletterform" method="get">
<input type="text" name="email" class="required email" id="textnewsletter" />
<input type="submit" id="signup" />
</form>
</code></pre>
<p><strong>Here's what I want to be able to do:</strong></p>
<ul>
<li>Validate the form to look for an empty string or a incorrectly filled out email address one the user clicks submit or hits enter.</li>
<li>If one of the above happens (empty string etc), I would like to generate an error to let the user know.</li>
<li>Then once the user fills out a correctly formed email address and hits submit (or enter) I want the form to send the email address to wherever I specify in the jQuery code and then generate a little "Thank you for signing up notice", all without reloading the browser.</li>
</ul>
<p>I have looked at too many tutorials and my eyes are pretty much aching at this stage, so please don't point me to any urls (I most likely have been there).</p>
<p>If someone could provide a barebone outline of what to do It would be so much appreciated. </p>
| [
{
"answer_id": 357075,
"author": "MrChrister",
"author_id": 24229,
"author_profile": "https://Stackoverflow.com/users/24229",
"pm_score": 4,
"selected": true,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <!-- Load JQuery on your page -->\n <script src=\"http://code.jquery.com/jquery-latest.js\"></script>\n <!-- Load JQuery validation sytles and (rules?) on your page -->\n <link rel=\"stylesheet\" href=\"http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css\" type=\"text/css\" media=\"screen\" />\n <!-- Load JQuery validation plugin on your page -->\n <script type=\"text/javascript\" src=\"http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js\"></script>\n <!-- Load JQuery form plugin on your page -->\n <script type=\"text/javascript\" src=\"http://jqueryjs.googlecode.com/svn/trunk/plugins/form/jquery.form.js\"></script>\n <script type=\"text/javascript\" language=\"javascript\">\n //Wait until the document is loaded, then call the validation. Due to magic in JQuery or the plugin\n // this only happens when the form is submitted.\n $(document).ready(function(){\n //When the submit button is clicked\n $(\"#signup\").click(function() {\n //if the form is valid according to the fules\n if ($(\"#newsletterform\").valid()) {\n //Submit the form via AJAX\n $('#newsletterform').ajaxForm(function() { \n //this alert lets me know the submission was successfull\n alert(\"Thank you!\"); }); \n }\n })\n });\n </script>\n <!-- Just some styles -->\n <style type=\"text/css\">\n * { font-family: Verdana; font-size: 96%; }\n label { width: 10em; float: left; }\n label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }\n p { clear: both; }\n .submit { margin-left: 12em; }\n em { font-weight: bold; padding-right: 1em; vertical-align: top; }\n </style> \n</head>\n<body>\n <form action=\"\" id=\"newsletterform\" method=\"get\">\n <!-- The classes assigned here are where the validation rules come fome. \n This is required, and it must be an email -->\n <input type=\"text\" name=\"email\" class=\"required email\" id=\"textnewsletter\" />\n <input type=\"submit\" id=\"signup\" />\n </form>\n</body>\n</html>\n"
},
{
"answer_id": 357100,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 2,
"selected": false,
"text": "submitHandler $('#myform').validate({\n // ...\n submitHandler: function() { alert(\"submitted\"); }\n});\n"
},
{
"answer_id": 360155,
"author": "Keith Donegan",
"author_id": 37418,
"author_profile": "https://Stackoverflow.com/users/37418",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function () {\n $('#textnewsletter').click(function () \n {\n if($('#textnewsletter').val()=='Your email address')\n $(this).attr(\"value\",'');\n });\n\n $('form#newslattersub').submit(function () \n {\n if(!isEmail($('#textnewsletter').val() ))\n {\n $('p.idmsg').html('<span class=\"error\">Please enter a valid email address</span>').hide().fadeIn(\"slow\");\n\n }\n else{\n $.post($('form#newslattersub').attr('action'), { email:$('#textnewsletter').val() },function(data){\n $('p.idmsg').html('<span class=\"success\">Thanks for signing up! Please check your email for confirmation!</span>').hide().fadeIn(\"slow\");\n //alert(\"server return \" + data);\n });\n\n\n }\n return false;\n\n\n });\n\n });\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37418/"
] |
357,068 | <p>Is there a way to use the C sprintf() function without it adding a '\0' character at the end of its output? I need to write formatted text in the middle of a fixed width string.</p>
| [
{
"answer_id": 357081,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "sprintf() sprintf() strncpy()"
},
{
"answer_id": 357391,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": " unsigned int len = sprintf(str, ...);\n str[len] = '<your char here>';\n"
},
{
"answer_id": 358648,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "char my_fixed_width_string_format[] = \"need 10 chars starting here: %10s\";\nchar my_fixed_width_string[40];\nchar string_to_print[] = \"abcdefghijklmnop\";\nsprintf(my_fixed_width_string, my_fixed_width_string_format, string_to_print;\nprintf(my_fixed_width_string);\n"
},
{
"answer_id": 359985,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "char message[32] = \"Hello 123, it's good to see you.\";\n\nsnprintf(&message[6],3,\"Joe\");\n"
},
{
"answer_id": 11320388,
"author": "Todd Freed",
"author_id": 661466,
"author_profile": "https://Stackoverflow.com/users/661466",
"pm_score": 0,
"selected": false,
"text": "// pointer to fixed area we want to write to\nchar* s;\n\n// number of bytes needed, not including the null\nint r = snprintf(0, 0, <your va_args here>);\n\n// char following the last char we will write - null goes here\nchar c = s[r + 1];\n\n// do the formatted write\nsnprintf(s, r + 1, <your_va_args here>);\n\n// replace what was overwritten\ns[r + 1] = c;\n"
},
{
"answer_id": 28649575,
"author": "yan bellavance",
"author_id": 131981,
"author_profile": "https://Stackoverflow.com/users/131981",
"pm_score": 0,
"selected": false,
"text": "char name[9] = \"QQ40dude\"; \nunsigned int i0To100 = 63; \n_snprintf(&name[2],2,\"%d\",i0To100); \nprintf(name);// output will be: QQ63dude \n"
},
{
"answer_id": 59506380,
"author": "afk",
"author_id": 7331858,
"author_profile": "https://Stackoverflow.com/users/7331858",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main(void)\n{\n char buf[100] = { 'a', 'b', 'c', 'd', 'e' };\n const size_t buf_size = sizeof(buf);\n const int i = 123;\n\n int result = snprintf(buf, 0, \"%i\", i);\n if (result < 0)\n {\n printf(\"snprintf error: %i\\n\", result);\n return -1;\n }\n\n int clobbered_index = result; //this index will get the null term written into it\n\n if (result >= buf_size)\n {\n printf(\"buffer not large enough. required %i chars\\n\", result + 1);\n return -1;\n }\n\n char temp_char = buf[clobbered_index];\n result = snprintf(buf, buf_size, \"%i\", i); //add result error checking here to catch future mistakes\n buf[clobbered_index] = temp_char;\n\n printf(\"buf:%s\\n\", buf);\n\n return 0;\n}\n buf:123de"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39702/"
] |
357,076 | <p>I've been a .NET developer for several years now and this is still one of those things I don't know how to do properly. It's easy to hide a window from the taskbar via a property in both Windows Forms and WPF, but as far as I can tell, this doesn't guarantee (or necessarily even affect) it being hidden from the <kbd>Alt</kbd>+<kbd>↹Tab</kbd> dialog. I've seen <em>invisible</em> windows show up in <kbd>Alt</kbd>+<kbd>↹Tab</kbd>, and I'm just wondering what is the best way to guarantee a window will <em>never</em> appear (visible or not) in the <kbd>Alt</kbd>+<kbd>↹Tab</kbd> dialog.</p>
<p><strong>Update:</strong> Please see my posted solution below. I'm not allowed to mark my own answers as the solution, but so far it's the only one that works.</p>
<p><strong>Update 2:</strong> There's now a proper solution by Franci Penov that looks pretty good, but haven't tried it out myself. Involves some Win32, but avoids the lame creation of off-screen windows.</p>
| [
{
"answer_id": 357270,
"author": "Philipp Schmid",
"author_id": 33272,
"author_profile": "https://Stackoverflow.com/users/33272",
"pm_score": 1,
"selected": false,
"text": "<Window x:Class=\"WpfApplication5.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n ShowInTaskbar=\"False\" \n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Grid>\n\n </Grid>\n</Window>\n"
},
{
"answer_id": 357598,
"author": "devios1",
"author_id": 238948,
"author_profile": "https://Stackoverflow.com/users/238948",
"pm_score": 5,
"selected": false,
"text": "Window w = new Window(); // Create helper window\nw.Top = -100; // Location of new window is outside of visible part of screen\nw.Left = -100;\nw.Width = 1; // size of window is enough small to avoid its appearance at the beginning\nw.Height = 1;\nw.WindowStyle = WindowStyle.ToolWindow; // Set window style as ToolWindow to avoid its icon in AltTab \nw.Show(); // We need to show window before set is as owner to our main window\nthis.Owner = w; // Okey, this will result to disappear icon for main window.\nw.Hide(); // Hide helper window just in case\n this.Owner = w w.Hide() w.Show() Window OwnerWindow this.Owner = App.OwnerWindow this.Owner = null ShowInTaskBar=false w"
},
{
"answer_id": 551847,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 8,
"selected": true,
"text": "ShowInTaskbar=\"False\" Visibility=\"Hidden\" WS_EX_TOOLWINDOW WindowStyle=ToolWindow WS_CAPTION WS_SYSMENU WindowStyle=None WS_EX_TOOLWINDOW WindowStyle=None WS_EX_TOOLWINDOW <Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Height=\"300\" Width=\"300\"\n ShowInTaskbar=\"False\" WindowStyle=\"None\"\n Loaded=\"Window_Loaded\" >\n WindowStyle=None ShowInTaskbar=False private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n WindowInteropHelper wndHelper = new WindowInteropHelper(this);\n\n int exStyle = (int)GetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE);\n\n exStyle |= (int)ExtendedWindowStyles.WS_EX_TOOLWINDOW;\n SetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE, (IntPtr)exStyle);\n}\n SetWindowLongPtr SetWindowLong #region Window styles\n[Flags]\npublic enum ExtendedWindowStyles\n{\n // ...\n WS_EX_TOOLWINDOW = 0x00000080,\n // ...\n}\n\npublic enum GetWindowLongFields\n{\n // ...\n GWL_EXSTYLE = (-20),\n // ...\n}\n\n[DllImport(\"user32.dll\")]\npublic static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);\n\npublic static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)\n{\n int error = 0;\n IntPtr result = IntPtr.Zero;\n // Win32 SetWindowLong doesn't clear error on success\n SetLastError(0);\n\n if (IntPtr.Size == 4)\n {\n // use SetWindowLong\n Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));\n error = Marshal.GetLastWin32Error();\n result = new IntPtr(tempResult);\n }\n else\n {\n // use SetWindowLongPtr\n result = IntSetWindowLongPtr(hWnd, nIndex, dwNewLong);\n error = Marshal.GetLastWin32Error();\n }\n\n if ((result == IntPtr.Zero) && (error != 0))\n {\n throw new System.ComponentModel.Win32Exception(error);\n }\n\n return result;\n}\n\n[DllImport(\"user32.dll\", EntryPoint = \"SetWindowLongPtr\", SetLastError = true)]\nprivate static extern IntPtr IntSetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);\n\n[DllImport(\"user32.dll\", EntryPoint = \"SetWindowLong\", SetLastError = true)]\nprivate static extern Int32 IntSetWindowLong(IntPtr hWnd, int nIndex, Int32 dwNewLong);\n\nprivate static int IntPtrToInt32(IntPtr intPtr)\n{\n return unchecked((int)intPtr.ToInt64());\n}\n\n[DllImport(\"kernel32.dll\", EntryPoint = \"SetLastError\")]\npublic static extern void SetLastError(int dwErrorCode);\n#endregion\n"
},
{
"answer_id": 783424,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "private void Form1_Load(object sender, EventArgs e)\n{\n // Making the window invisible forces it to not show up in the ALT+TAB\n this.Visible = false;\n}>\n"
},
{
"answer_id": 2698144,
"author": "Andrey",
"author_id": 324123,
"author_profile": "https://Stackoverflow.com/users/324123",
"pm_score": 4,
"selected": false,
"text": "me.FormBorderStyle = FormBorderStyle.SizableToolWindow\nme.ShowInTaskbar = false\n"
},
{
"answer_id": 2742136,
"author": "Matt Hendricks",
"author_id": 329445,
"author_profile": "https://Stackoverflow.com/users/329445",
"pm_score": 4,
"selected": false,
"text": "// Keep this program out of the Alt-Tab menu\n\nShowInTaskbar = false;\n\nForm form1 = new Form ( );\n\nform1.FormBorderStyle = FormBorderStyle.FixedToolWindow;\nform1.ShowInTaskbar = false;\n\nOwner = form1;\n"
},
{
"answer_id": 2810914,
"author": "Behnam Shomali",
"author_id": 336142,
"author_profile": "https://Stackoverflow.com/users/336142",
"pm_score": 2,
"selected": false,
"text": "[DllImport(\"user32.dll\")]\npublic static extern int SetWindowLong( IntPtr window, int index, int\nvalue);\n[DllImport(\"user32.dll\")]\npublic static extern int GetWindowLong( IntPtr window, int index);\n\n\nconst int GWL_EXSTYLE = -20;\nconst int WS_EX_TOOLWINDOW = 0x00000080;\nconst int WS_EX_APPWINDOW = 0x00040000;\n\nprivate System.Windows.Forms.NotifyIcon notifyIcon1;\n\n\n// I use two icons depending of the status of the app\nnormalIcon = new Icon(this.GetType(),\"Normal.ico\");\nalertIcon = new Icon(this.GetType(),\"Alert.ico\");\nnotifyIcon1.Icon = normalIcon;\n\nthis.WindowState = System.Windows.Forms.FormWindowState.Minimized;\nthis.Visible = false;\nthis.ShowInTaskbar = false;\niconTimer.Start();\n\n//Make it gone frmo the ALT+TAB\nint windowStyle = GetWindowLong(Handle, GWL_EXSTYLE);\nSetWindowLong(Handle, GWL_EXSTYLE, windowStyle | WS_EX_TOOLWINDOW);\n"
},
{
"answer_id": 4579278,
"author": "tiendan",
"author_id": 560440,
"author_profile": "https://Stackoverflow.com/users/560440",
"pm_score": 2,
"selected": false,
"text": "private void Form1_VisibleChanged(object sender, EventArgs e)\n{\n if (this.Visible)\n {\n this.Visible = false;\n }\n}\n"
},
{
"answer_id": 9393818,
"author": "Saravanakumar. N",
"author_id": 1225654,
"author_profile": "https://Stackoverflow.com/users/1225654",
"pm_score": 2,
"selected": false,
"text": "FormBorderStyle FixedToolWindow"
},
{
"answer_id": 12628181,
"author": "Hossein Moradinia",
"author_id": 242079,
"author_profile": "https://Stackoverflow.com/users/242079",
"pm_score": 2,
"selected": false,
"text": "this.FormBorderStyle = FormBorderStyle.None;\nthis.ShowInTaskbar = false;\n protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n // turn on WS_EX_TOOLWINDOW style bit\n cp.ExStyle |= 0x80;\n return cp;\n }\n}\n"
},
{
"answer_id": 17893626,
"author": "Danny Beckett",
"author_id": 1563422,
"author_profile": "https://Stackoverflow.com/users/1563422",
"pm_score": 6,
"selected": false,
"text": "protected override CreateParams CreateParams\n{\n get\n {\n var Params = base.CreateParams;\n Params.ExStyle |= WS_EX_TOOLWINDOW;\n return Params;\n }\n}\n"
},
{
"answer_id": 65937633,
"author": "Dhanraj Kumar",
"author_id": 11617070,
"author_profile": "https://Stackoverflow.com/users/11617070",
"pm_score": 1,
"selected": false,
"text": " private void Particular_txt_KeyPress(object sender, KeyPressEventArgs e)\n {\n Form1 frm = new Form1(); \n frm.Owner = this;\n frm.Show();\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238948/"
] |
357,084 | <p>I do my php work on my dev box at home, where I've got a rudimentary LAMP setup. When I look at my website on my home box, any numbers I echo are automatically truncated to the least required precision. Eg 2 is echoed as 2, 2.2000 is echoed as 2.2.</p>
<p>On the production box, all the numbers are echoed with at least one unnecessary zero, eg 100 becomes 100.0. On both boxes, the PHP version is 5.2.5. Does anyone know offhand if there is a setting I can change which will force PHP to automatically remove any unnecessary zeroes? I don't want to have to go to every place in my code where I output a number and replace echo with printf or something like that.</p>
<p>Muchas gracias.</p>
| [
{
"answer_id": 357128,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 4,
"selected": true,
"text": "// displays 3.14 as 3 and 4.00 as 4 \nprint number_format($price, 0); \n// display 4 as 4.00 and 1234.56 as 1,234.56 aka money style\nprint number_format($int, 2, \".\", \",\"); \n"
},
{
"answer_id": 357130,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "auto_prepend_file output_handler"
},
{
"answer_id": 359102,
"author": "el_champo",
"author_id": 42387,
"author_profile": "https://Stackoverflow.com/users/42387",
"pm_score": 2,
"selected": false,
"text": "return someNumber.' grams';\n return (float)someNumber.' grams';\n"
},
{
"answer_id": 8338716,
"author": "Somnath Muluk",
"author_id": 1045444,
"author_profile": "https://Stackoverflow.com/users/1045444",
"pm_score": 0,
"selected": false,
"text": "round float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] );\n <?php\necho round(3.4); // 3\necho round(3.5); // 4\necho round(3.6); // 4\necho round(3.6, 0); // 4\necho round(1.95583, 2); // 1.96\necho round(1241757, -3); // 1242000\necho round(5.045, 2); // 5.05\necho round(5.055, 2); // 5.06\n?>\n <?php\necho round(9.5, 0, PHP_ROUND_HALF_UP); // 10\necho round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9\necho round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10\necho round(9.5, 0, PHP_ROUND_HALF_ODD); // 9\n\necho round(8.5, 0, PHP_ROUND_HALF_UP); // 9\necho round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8\necho round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8\necho round(8.5, 0, PHP_ROUND_HALF_ODD); // 9\n?>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42387/"
] |
357,095 | <p>I would like to use JConsole to monitor my Websphere application, but I am not sure how to enable JMX.</p>
| [
{
"answer_id": 358814,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 5,
"selected": false,
"text": "service:jmx:iiop://<host>:<port>/jndi/JMXConnector\n 0000000a RMIConnectorC A ADMC0026I: The RMI Connector is available at port 2810\n com.ibm.ws.admin.client_6.1.0.jar\n runtimes D:\\prog\\was61\\java\\bin>jconsole -J-Djava.class.path=d:\\prog\\was61\\java\\lib\\tools.jar;D:\\prog\\was61\\runtimes\\com.ibm.ws.admin.client_6.1.0.jar\n C:\\Program Files\\Java\\jdk1.5.0_11\\bin>jconsole -J-Djava.class.path=\"c:\\Program Files\\Java\\jdk1.5.0_11\\lib\\jconsole.jar\";\"c:\\Program Files\\Java\\jdk1.5.0_11\\lib\\tools.jar\";D:\\prog\\was61\\runtimes\\com.ibm.ws.admin.client_6.1.0.jar;D:\\prog\\was61\\java\\jre\\lib\\ibmorb.jar\n"
},
{
"answer_id": 1545542,
"author": "Alan Chan",
"author_id": 187390,
"author_profile": "https://Stackoverflow.com/users/187390",
"pm_score": 2,
"selected": false,
"text": "com.ibm.ws.admin.client_6.1.0.jar ibmorbapi.jar\nibmorb.jar\nibmcfw.jar\n set JAVA_HOME=C:\\Progra~1\\Java\\jdk1.5.0_20\nset WAS6.1_JARS=C:\\packages\\was61-jmx\n\nset BOOTJARS=%WAS6.1_JARS%\\ibmorbapi.jar\nset BOOTJARS=%BOOTJARS%;%WAS6.1_JARS%\\ibmorb.jar\nset BOOTJARS=%BOOTJARS%;%WAS6.1_JARS%\\ibmcfw.jar\n\nset CLASSPATH=%WAS6.1_JARS%\\com.ibm.ws.admin.client_6.1.0.jar\nset CLASSPATH=%CLASSPATH%;%JAVA_HOME%\\lib\\tools.jar\nset CLASSPATH=%CLASSPATH%;%JAVA_HOME%\\lib\\jconsole.jar\n\n\n%JAVA_HOME%\\bin\\jconsole -J-Xbootclasspath/p:%BOOTJARS% -J-Djava.class.path=%CLASSPATH%\n"
},
{
"answer_id": 2253007,
"author": "Boguś",
"author_id": 271928,
"author_profile": "https://Stackoverflow.com/users/271928",
"pm_score": 3,
"selected": false,
"text": "@echo off \nset HOST=<host>\nset PORT=2809\n\nset WAS_HOME=D:/Programy/IBM/WebSphere/AppServer\n\nset THIS_DIR=E:/Home/Bogus/Pulpit\n\nset CLIENTSAS=-Dcom.ibm.CORBA.ConfigURL=file:/%THIS_DIR%/sas.client.props\nset PROVIDER=-Djava.naming.provider.url=corbaname:iiop:%HOST%:%PORT% \n\nset PROPS=\nset PROPS=%PROPS% %CLIENTSAS%\nset PROPS=%PROPS% %PROVIDER%\n\nset CLASSPATH=\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\java\\lib\\tools.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\runtimes\\com.ibm.ws.admin.client_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\runtimes\\com.ibm.ws.ejb.thinclient_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\runtimes\\com.ibm.ws.orb_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\java\\lib\\jconsole.jar\n\nset URL=service:jmx:iiop://%HOST%:%PORT%/jndi/JMXConnector\n\n@echo on\n\n:: %WAS_HOME%\\java\\bin\\\njava -classpath %CLASSPATH% %PROPS% sun.tools.jconsole.JConsole %URL%\n com.ibm.CORBA.securityEnabled=true\n\ncom.ibm.CORBA.authenticationTarget=BasicAuth\ncom.ibm.CORBA.authenticationRetryEnabled=true\ncom.ibm.CORBA.authenticationRetryCount=3\ncom.ibm.CORBA.validateBasicAuth=true\ncom.ibm.CORBA.securityServerHost=\ncom.ibm.CORBA.securityServerPort=\ncom.ibm.CORBA.loginTimeout=300\ncom.ibm.CORBA.loginSource=prompt\n\ncom.ibm.CORBA.loginUserid=\ncom.ibm.CORBA.loginPassword=\n\ncom.ibm.CORBA.krb5ConfigFile=\ncom.ibm.CORBA.krb5CcacheFile=\n\ncom.ibm.CSI.performStateful=true\n\ncom.ibm.CSI.performClientAuthenticationRequired=false\ncom.ibm.CSI.performClientAuthenticationSupported=true\n\n# SET ALL THE FOLLOWING VALUES TO FALSE\n\ncom.ibm.CSI.performTLClientAuthenticationRequired=false\ncom.ibm.CSI.performTLClientAuthenticationSupported=false\n\ncom.ibm.CSI.performTransportAssocSSLTLSRequired=false\ncom.ibm.CSI.performTransportAssocSSLTLSSupported=false\n\ncom.ibm.CSI.performMessageIntegrityRequired=false\ncom.ibm.CSI.performMessageIntegritySupported=false\n\ncom.ibm.CSI.performMessageConfidentialityRequired=false\ncom.ibm.CSI.performMessageConfidentialitySupported=false\n\n# COMMENT THIS OUT\n#com.ibm.ssl.alias=DefaultSSLSettings\n\n\ncom.ibm.CORBA.requestTimeout=180\n"
},
{
"answer_id": 5456215,
"author": "Robert Höglund",
"author_id": 986283,
"author_profile": "https://Stackoverflow.com/users/986283",
"pm_score": 3,
"selected": false,
"text": "-Djavax.management.builder.initial= \n-Dcom.sun.management.jmxremote \n-Dcom.sun.management.jmxremote.authenticate=false \n-Dcom.sun.management.jmxremote.ssl=false \n-Dcom.sun.management.jmxremote.port=1099\n"
},
{
"answer_id": 7334046,
"author": "Max",
"author_id": 932496,
"author_profile": "https://Stackoverflow.com/users/932496",
"pm_score": 2,
"selected": false,
"text": "<systemProperties xmi:id=\"Property_1315391623828\" name=\"com.sun.management.jmxremote\" value=\"\" required=\"false\"/> <systemProperties xmi:id=\"Property_1315327918140\" name=\"com.sun.management.jmxremote.port\" value=\"1235\" required=\"false\"/>\n<systemProperties xmi:id=\"Property_1315327935281\" name=\"com.sun.management.jmxremote.authenticate\" value=\"false\" required=\"false\"/>\n<systemProperties xmi:id=\"Property_1315327948046\" name=\"com.sun.management.jmxremote.ssl\" value=\"false\" required=\"false\"/>\n<systemProperties xmi:id=\"Property_1315390852859\" name=\"javax.management.builder.initial\" value=\"\" required=\"false\"/>\n"
},
{
"answer_id": 7649099,
"author": "Eddy",
"author_id": 261984,
"author_profile": "https://Stackoverflow.com/users/261984",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh \ncurrent_dir=`dirname \"$0\"`\n\nHOSTNAME=host.fqdn\nPORT=2809\n\nWAS_HOME=/opt/IBM/WebSphere/AppServer\nWAS_PROFILE=$WAS_HOME/profiles/AppSrv01\nWAS_RUNTIMES=$WAS_HOME/runtimes\n\nWAS_LIB=$WAS_HOME/java/lib\nJAVA_HOME=$WAS_HOME/java\n\n\n\nCLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/jconsole.jar:$WAS_RUNTIMES/com.ibm.ws.admin.client_7.0.0.jar:$WAS_LIB/ibmcfw.jar \n\nTARGET=service:jmx:soap://$HOSTNAME:$PORT/jndi/JMXConnector\n\nCP=\"-J-Djava.class.path=$CLASSPATH\"\nSSL_SERVER_KEY=\"-J-Djavax.net.ssl.keyStore=$WAS_PROFILE/etc/DummyServerKeyFile.jks -J-Djavax.net.ssl.keyStorePassword=WebAS\"\nSSL_TRUST_STORE=\"-J-Djavax.net.ssl.trustStore=$WAS_PROFILE/etc/DummyServerTrustFile.jks -J-Djavax.net.ssl.trustStorePassword=WebAS\"\nSSL_OPTS=\"-J-Dcom.ibm.SSL.ConfigURL=file:$WAS_PROFILE/properties/ssl.client.props\"\nSOAP_OPTS=\"-J-Dcom.ibm.SOAP.ConfigURL=file:$WAS_PROFILE/properties/soap.client.props\"\nWAS_OPTS=\"-J-Dwas.install.root=$WAS_HOME -J-Djava.ext.dirs=$WAS_HOME/plugins:$WAS_HOME/lib:$WAS_HOME/plugins/com.ibm.ws.security.crypto_6.1.0:$WAS_HOME/lib:$JAVA_HOME/jre/lib/ext\"\n\nCOMMAND=\"$JAVA_HOME/bin/jconsole $CP $SSL_SERVER_KEY $SSL_TRUST_STORE $SSL_OPTS $SOAP_OPTS $WAS_OPTS $TARGET\"\n\nexec $COMMAND\n"
},
{
"answer_id": 12312827,
"author": "Drago Z Kamenov",
"author_id": 1253090,
"author_profile": "https://Stackoverflow.com/users/1253090",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nWAS_HOME=/opt/IBM/WebSphere/AppServer\n\n# setup server-specific env variables\n. $WAS_HOME/profiles/AppSrv01/bin/setupCmdLine.sh\n\nHOST=localhost\nPORT=9100\n\nCLASSPATH=$JAVA_HOME/lib/jconsole.jar\nCLASSPATH=$CLASSPATH:$WAS_HOME/runtimes/com.ibm.ws.admin.client_8.5.0.jar\nCLASSPATH=$CLASSPATH:$WAS_HOME/runtimes/com.ibm.ws.ejb.thinclient_8.5.0.jar\nCLASSPATH=$CLASSPATH:$WAS_HOME/runtimes/com.ibm.ws.orb_8.5.0.jar\n\n$JAVA_HOME/bin/jconsole \\\n -J-Djava.class.path=$CLASSPATH\\\n -J$CLIENTSAS\\\n -J$CLIENTSSL\\\n service:jmx:iiop://$HOST:$PORT/jndi/JMXConnector\n"
},
{
"answer_id": 15688573,
"author": "Slava Baytalskiy",
"author_id": 2220869,
"author_profile": "https://Stackoverflow.com/users/2220869",
"pm_score": 0,
"selected": false,
"text": "@echo off \nset HOST=<put hostname here>\nset PORT=<put JVM's BOOTSTRAP_PORT here>\n\nset WAS_HOME=C:\\jconsole\nset JAVA_HOME=C:\\glassfish3\\jdk7\nset PROPS_DIR=C:\\jconsole\\properties\n\nset CLIENTSAS=-Dcom.ibm.CORBA.ConfigURL=file:/%PROPS_DIR%/sas.client.props\nset CLIENTSSL=-Dcom.ibm.SSL.ConfigURL=file:/%PROPS_DIR%/ssl.client.props\nset PROVIDER=-Djava.naming.provider.url=corbaname:iiop:%HOST%:%PORT% \n\nset PROPS=\nset PROPS=%PROPS% %CLIENTSAS% %CLIENTSSL% %PROVIDER%\n\nset CLASSPATH=\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\com.ibm.ws.admin.client_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\com.ibm.ws.ejb.thinclient_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%WAS_HOME%\\com.ibm.ws.orb_7.0.0.jar\nset CLASSPATH=%CLASSPATH%;%JAVA_HOME%\\lib\\jconsole.jar\nset CLASSPATH=%CLASSPATH%;%JAVA_HOME%\\lib\\tools.jar\n\nset URL=service:jmx:iiop://%HOST%:%PORT%/jndi/JMXConnector\n\n@echo on\n\n%JAVA_HOME%\\bin\\java -classpath %CLASSPATH% %PROPS% sun.tools.jconsole.JConsole %URL%\n WAS_BIN_HOME/java/jre/lib/endorsed\n java.security\nlocal_policy.jar\nUS_export_policy.jar\n"
},
{
"answer_id": 17184949,
"author": "qxo",
"author_id": 1999483,
"author_profile": "https://Stackoverflow.com/users/1999483",
"pm_score": 2,
"selected": false,
"text": "-Djavax.management.builder.initial= -Dcom.sun.management.jmxremote -Djavax.management.builder.initial= -Dcom.sun.management.jmxremote com.sun.management.jmxremote.port=9001\ncom.sun.management.jmxremote.ssl=false\ncom.sun.management.jmxremote.authenticate=false\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
357,104 | <p>How do I prevent a form that is posted a second time because of a page reload in a browser from being added to my database again with C# Asp.Net.</p>
<p>Thanks,
Steven</p>
| [
{
"answer_id": 357144,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 2,
"selected": false,
"text": "Page_Load Response.Redirect(Request.Url.ToString(), true);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42588/"
] |
357,121 | <p>In my mock class, I'm mocking method foo(). For some test cases, I want the mock implementation of foo() to return a special value. For other test cases, I want to use the real implementation of foo(). I have a boolean defined in my mock class so that I can determine in the mock method whether I want to return the special value, or use the "real" method. The problem is, I can't seem to figure out how to call the real method from the mocked method.</p>
<p>I found that you can define a special member within the mock object named "it" (with type of the object being mocked). This allows you to reference the real class from the mock implementation. So, my plan was, if I needed to invoke the "real" implementation of foo(), the mock method would call it.foo(). However, this doesn't work, because calling it.foo() just calls the mock version again, not the real version, so I end up with infinite recursion.</p>
<p>Is there some way to make this work?</p>
<p>EDIT: it might be clearer with a code example, here's what my current mocked method implementation looks like:</p>
<pre><code>private RealClass it;
...
public SomeClass foo() {
if(fakeIt) {
return new SomeClass("fakevalue");
} else {
// doesn't work, just keeps calling the mock foo
// in infinite recursion
return it.foo();
}
}
</code></pre>
<p>EDIT 2: Also, for most of my test cases I do <em>NOT</em> want the mock implementation. So my initial attempt at this was to only call Mockit.redefineMethods() within those test cases where I needed the mock object. But this didn't work - it seems you can only do this within setup/teardown ... my mock implementation never got called when I tried that.</p>
<p>NOTES ON SOLUTION:</p>
<p>At first I didn't think the answer given worked, but after playing with it some more, it seems the problem is that I was mixing JMockit "core" methods with the "annotation" driven methods. Apparently when using the annotation you need to use Mockit.setupMocks, not Mockit.redefineMethods(). This is what finally worked:</p>
<pre><code>@Before
public void setUp() throws Exception
{
Mockit.setUpMocks(MyMockClass.class);
}
</code></pre>
<p>Then, for the mock class:</p>
<pre><code>@MockClass(realClass = RealClass.class)
public static class MyMockClass {
private static boolean fakeIt = false;
private RealClass it;
@Mock(reentrant = true)
public SomeClass foo() {
if(fakeIt) {
return new SomeClass("fakevalue");
} else {
return it.foo();
}
}
}
</code></pre>
| [
{
"answer_id": 357424,
"author": "ebo",
"author_id": 13226,
"author_profile": "https://Stackoverflow.com/users/13226",
"pm_score": 1,
"selected": false,
"text": "RealClass toTest = new RealClass(){\n public String foo(){\n return \"special value\";\n }\n}\n\n//use toTest in test\n"
},
{
"answer_id": 358432,
"author": "Kris Pruden",
"author_id": 16977,
"author_profile": "https://Stackoverflow.com/users/16977",
"pm_score": 4,
"selected": true,
"text": "@Mock @Mock(reentrant=true)"
},
{
"answer_id": 30745405,
"author": "Trevor Robinson",
"author_id": 123336,
"author_profile": "https://Stackoverflow.com/users/123336",
"pm_score": 4,
"selected": false,
"text": "Invocation.proceed() MockUp public class MyMockClass extends MockUp<RealClass> {\n\n private static boolean fakeIt = false;\n\n @Mock\n public SomeClass foo(Invocation inv) {\n if (fakeIt) {\n return new SomeClass(\"fakevalue\");\n } else {\n return inv.proceed();\n }\n }\n}\n"
},
{
"answer_id": 73661120,
"author": "Pavel",
"author_id": 2206638,
"author_profile": "https://Stackoverflow.com/users/2206638",
"pm_score": 0,
"selected": false,
"text": "SomeClass someClass = new SomeClass(\"fakevalue\");\n\nnew Expectations(someClass){{\n someClass.foo();\n result = <mock>;\n}};\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20437/"
] |
357,122 | <p>Coming from <a href="https://stackoverflow.com/questions/356778/php-query-single-value-per-iteration-or-fetch-all-at-start-and-retrieve-from-ar">another question of mine</a> where I learnt not to EVER use db queries within loops I consequently have to learn how to fetch all the data in a convenient way before I loop through it.</p>
<p>Let's say I have two tables 'scales' and 'items'. Each item in items belongs to one scale in scales and is linked with a foreign key (scaleID). I want to fetch all that data into an array structure in one query such that the first dimension are all the scales with all the columns and nested within, all items of one scale all columns.</p>
<p>Result would be something like that:</p>
<pre><code>scale 1, scaleParam1, scaleParam2, ...
....item1, itemParam1, itemParam2, ...
....item2, itemParam1, itemParam2, ...
scale 2, scaleParam2, scaleParam2, ...
....item1, itemParam1, itemParam2, ...
....item2, itemParam1, itemParam2, ...
</code></pre>
<p>So far I've done mainly left joins for one-to-one relationships. This is a one-to-many and I just can't wrap my mind around it. </p>
<p>Is it a right join, could it also be done with a subquery, how to get the full outer rows into it as well...</p>
<p>later I would like to iterate through it with to nested foreach loops.</p>
<p>Maybe it's just that I have a headache...</p>
| [
{
"answer_id": 357241,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "//first get scales\nwhile ($row = fetchrowfunctionhere()) {\n $scale = $scales->createFromArray($row);\n}\n\n//then get items\n$lastId = null;\nwhile ($row = fetchrowfunctionhere()) {\n $scaleId = $row['scaleID'];\n if ($lastId != $scaleId) {\n $scale = $scales->getByScaleId($scaleId);\n }\n $item = $items->createFromArray($row);\n $scale->addItem($item);\n $lastId = $scaleId;\n}\n $lastId = null;\nwhile ($row = fetchrowfunctionhere()) {\n $scaleData = array_slice($row, 0, 5, true);\n $itemData = array_slice($row, 5, 5, true);\n $scaleId = $scaleData['scaleID'];\n if ($lastId != $scaleId) {\n $scale = $scales->createFromArray($scaleData);\n }\n $item = $items->createFromArray($itemData);\n $scale->addItem($item);\n $lastId = $scaleId;\n}\n while ($row = fetchrowfunctionhere()) {\n $scaleData = array_slice($row, 0, 5, true);\n $itemData = array_slice($row, 5, 5, true);\n $scaleId = $scaleData['scaleID'];\n if (!isset($scales[$scaleId])) {\n $scales[$scaleId] = $scaleData;\n }\n $itemId = $itemData['itemID'];\n $scales[$scaleId]['items'][$itemId] = $itemData;\n}\n"
},
{
"answer_id": 357264,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM scales\nINNER JOIN items ON scales.id = items.scale_id\n $scales = array();\n\nwhile ($row = mysql_fetch_assoc($data))\n{\n if (!isset($scales[$row['scale_id']]))\n {\n $row['items'] = array();\n $scales[$row['scale_id']] = $row;\n }\n\n $scales[$row['scale_id']]['items'][] = $row;\n}\n foreach ($scales as $scale)\n{\n foreach ($scale['items'] as $item)\n ; //... do stuff\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
357,138 | <p>I want to add an ajax:TabContainer to my webpage. I don't get any build errors, but when I try to browse to the page, it gives me the error: "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).".</p>
<p>I re-downloaded the Ajax Control Toolkit for the sample sites, opened the solution in VS, ran the sample for the TabContainer, and it worked fine. I thought it was perhaps a different version of the Ajax Control Toolkit - but no. The AjaxControlToolkit.dll files being referenced by the two sites are identical. Why can't I get the TabContainer to work on my site?</p>
<p>There is one more issue, but I don't know whether it's related. I just recently installed Visual Studio 2008. As soon as I opened my website, VS automatically created the tab "AJAX Controls" in the toolbox and filled it with all the ajax controls. In the source code, all controls are prefixed with "ajax" - i.e., "< ajax:TabContainer runat="server" ... >".</p>
<p>However, when I opened the sample website, Visual studio created another tab in the toolbox - "AjaxControlToolkit Components", filled with all the same controls as in "AJAX Controls". I don't know why it added the same controls twice (but, strangely enough, with different icons for them in the toolbox). In the source code, all controls are prefixed with "ajaxToolkit" - i.e., "< ajaxToolkit:TabContainer runat="server" ... >". What's going on here? I just want the darn TabContainer to work on my site.</p>
| [
{
"answer_id": 357592,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 1,
"selected": false,
"text": "<head> <script>"
},
{
"answer_id": 1058263,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "<head runat=\"server\">...\n <head runat=\"server\">\n <link rel=\"stylesheet\" type=\"text/css\" \n href=\"<%# ResolveUrl( \"~/styles/common.aspx\" ) %>\" />\n...\n Page.Header.DataBind();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
357,170 | <p>I have a project and it needs to access a large amount of proprietary data in ASP.NET. This was done on the Linux/PHP by loading the data in shared memory. I was wondering if trying to use Memory Mapped Files would be the way to go, or if there is a better way with better .NET support. I was thinking of using the Data Cache but not sure of all the pitfalls of size of data being saved in the Cache.</p>
| [
{
"answer_id": 357217,
"author": "Steven Behnke",
"author_id": 42588,
"author_profile": "https://Stackoverflow.com/users/42588",
"pm_score": 1,
"selected": false,
"text": "byte[] fileBytes = Cache[\"fileBytes\"];\nif (null == fileBytes) {\n // reload the file and add it to the cache.\n string fileLocation = Server.MapPath(\"path/to/file.txt\");\n // Just a same of some bytes.\n fileBytes = new byte[10];\n Cache.Insert(fileLocation, fileBytes, new System.Web.Caching.CacheDependency(fileLocation));\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907/"
] |
357,190 | <p>I'm trying to find the file size of a file on a server. The following code I got from <a href="http://www.thejackol.com/2005/06/11/aspnet-get-file-size/" rel="nofollow noreferrer">this guy</a> accomplishes that for your own server:</p>
<pre><code>string MyFile = "~/photos/mymug.gif";
FileInfo finfo = new FileInfo(Server.MapPath(MyFile));
long FileInBytes = finfo.Length;
long FileInKB = finfo.Length / 1024;
Response.Write("File Size: " + FileInBytes.ToString() +
" bytes (" + FileInKB.ToString() + " KB)");
</code></pre>
<p>It works. However, I want to find the filesize of, for example:</p>
<pre><code>string MyFile = "http://www.google.com/intl/en_ALL/images/logo.gif";
FileInfo finfo = new FileInfo(MyFile);
</code></pre>
<p>Then I get a pesky error saying <code>URI formats are not supported.</code></p>
<p>How can I find the file size of Google's logo with ASP.NET?</p>
| [
{
"answer_id": 357220,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 4,
"selected": true,
"text": "WebRequest Content-Length HEAD Content-Length"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
357,203 | <p>Because I am a newbie I am trying to log out any errors that may occur with stored procedures I write. I understand Try/Catch in SQL 2005 and error_procedure(), ERROR_MESSAGE() and the other built in functions. What I can't figure out how to do is capture what record caused the error on an update.</p>
<p>I could probably use a cursor and loop through and update a row at a time. Then in the loop set a value and report on that value. But that seems to defeat the purpose of using SQL.</p>
<p>Any ideas or pointer on where to research this issue greatly appreciated. I do not fully understand RowNumber() could I use that somehow? Kind of grasping at straws here.</p>
<p>cheers and thanks </p>
<p>Bob </p>
<p>I am using SQL 2005.</p>
<p>Edit</p>
<p>I really do not want to use transactions for most of this, as it is just for reporting purposes. So an example of what I am doing is:</p>
<pre><code>/******************************************************************************
Now get update the table with the current worker. That depends on the
current status of the loan.
******************************************************************************/
UPDATE #table SET currWorker = tblUser.UserLogonName
FROM tblUser
JOIN tblLoanInvolvement ON tblLoanInvolvement.invlUnderwriterDeptID = tblUser.userID
WHERE tblLoanInvolvement.LOANid = #table.loanid
AND #table.currstatus in('R_UW_Approved','R_Submitted to Underwriting')
UPDATE #table SET currWorker = tblUser.UserLogonName
FROM tblUser
JOIN tblLoanInvolvement ON tblLoanInvolvement.invlProcessorID = tblUser.userID
WHERE tblLoanInvolvement.LOANid = #table.loanid
AND #table.currstatus in('R_UW Approved With Conditions','R_Loan Resubmitted','R_UW_Suspended','R_Submitted to Processing')
UPDATE #table SET currWorker = tblUser.UserLogonName
FROM tblUser
JOIN tblLoanInvolvement ON tblLoanInvolvement.invlCloserID = tblUser.userID
WHERE tblLoanInvolvement.LOANid = #table.loanid
AND #table.currstatus in('R_Docs Out','R_Ready to Close','R_Scheduled to Close and Fund','Scheduled To Close')
</code></pre>
<p>So if one row does not update correctly I do not want to loose the whole thing. But it would be very handy to know the value of #table.loanid that caused the problem. </p>
<p>Thanks for your time.</p>
| [
{
"answer_id": 357345,
"author": "rlb.usa",
"author_id": 449902,
"author_profile": "https://Stackoverflow.com/users/449902",
"pm_score": -1,
"selected": false,
"text": "DECLARE @problemClientID INT\nBEGIN TRANSACTION\n\n UPDATE ... --etc\n\n IF @@ERROR <> 0\n BEGIN\n ROLLBACK TRANSACTION\n SET @problemClientID = @@IDENTITY\n PRINT N'There was a problem...' --etc\n END\n ELSE\n BEGIN\n -- transaction was a success, do more stuff?\n END\nCOMMIT TRANSACTION\n"
},
{
"answer_id": 357351,
"author": "Paul",
"author_id": 42847,
"author_profile": "https://Stackoverflow.com/users/42847",
"pm_score": 3,
"selected": true,
"text": "BEGIN TRY\n -- Your Code Goes Here --\nEND TRY\nBEGIN CATCH\n SELECT \n ERROR_NUMBER() AS ErrorNumber,\n ERROR_SEVERITY() AS ErrorSeverity,\n ERROR_STATE() AS ErrorState,\n ERROR_PROCEDURE() AS ErrorProcedure,\n ERROR_LINE() AS ErrorLine,\n ERROR_MESSAGE() AS ErrorMessage\nEND CATCH\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18068/"
] |
357,212 | <p>What is the best and easiest way of taking HTML and converting it into a PDF, similar to use CFDOCUMENT on ColdFusion?</p>
<p><strong>UPDATE:</strong> I really appreciate all the comments and suggestions that people have given so far, however I feel that people leaving their answers are missing the point.</p>
<p>1) the solution has to be free or open sourced. one person suggested using pricexml and the other pd4ml. both of these solutions costs money (pricexml costing an arm and a leg) which i'm not about the fork over.</p>
<p>2) they must be able to take in html (either from a file, url or a string variable) and then produce the pdf. libraries like prawn, rprf, rtex are produced using their own methods and not taking in html.</p>
<p>please don't think i'm ungrateful for the suggestions, it's just that pdf generation seems like a really problem for people like me who use ColdFusion but want to convert to Rails.</p>
| [
{
"answer_id": 375689,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": " String content = nextPage.generateResponse().contentString();\n\n content = content.replace(\"Print\", \"\");\n content = content.replace(\"Back\", \"\");\n\n content = content.replace(\"border=\\\"1\\\"\", \"border=\\\"0\\\"\");\n content = content.replace(\"radio\", \"checkbox\");\n\n java.net.InetAddress i = java.net.InetAddress.getLocalHost();\n String address = i.getHostAddress()+\":53000\";\n\n content = content.replace(\"img src=\\\"/cgi-bin\", \"img src=\\\"http://\"+address+\"/cgi-bin\");\n\n System.out.println(content);\n\n PD4ML html = new PD4ML();\n html.setPageSize( new java.awt.Dimension(650, 700) );\n html.setPageInsets( new java.awt.Insets(30, 30, 30, 30) );\n html.setHtmlWidth( 750 );\n html.enableImgSplit( false );\n html.enableTableBreaks(true);\n\n StringReader isr = new StringReader(content);\n baos = new ByteArrayOutputStream();\n html.render( isr, baos);\n PDFRegForm pdfForm = (PDFRegForm)pageWithName(\"PDFRegForm\");\n pdfForm.baos = baos;\n pdfForm.generateResponse();\n"
},
{
"answer_id": 840133,
"author": "tsdbrown",
"author_id": 100213,
"author_profile": "https://Stackoverflow.com/users/100213",
"pm_score": 2,
"selected": false,
"text": "@letter_template = LetterTemplate.find(params[:id])\n\nrespond_to do |format|\n format.html\n format.pdf { send_data render_to_pdf({:action => 'show.rpdf', :layout => 'pdf_report'}), :filename => @letter_template.name + \".pdf\", :disposition => 'inline' }\n end\n def render_to_pdf(options =nil)\n data = render_to_string(options)\n pdf = PDF::HTMLDoc.new\n pdf.set_option :bodycolor, :white\n pdf.set_option :toc, false\n pdf.set_option :portrait, true\n pdf.set_option :links, false\n pdf.set_option :webpage, true\n pdf.set_option :left, '2cm'\n pdf.set_option :right, '2cm'\n pdf.set_option :footer, \"../\"\n pdf.set_option :header, \"...\"\n pdf.set_option :bottom, '2cm'\n pdf.set_option :top, '2cm'\n pdf << data\n pdf.generate\n end\n"
},
{
"answer_id": 32992165,
"author": "Sajjad Murtaza",
"author_id": 4060732,
"author_profile": "https://Stackoverflow.com/users/4060732",
"pm_score": 4,
"selected": false,
"text": "gem 'wicked_pdf' \ngem 'wkhtmltopdf-binary' \n#wicked_pdf is a wrapper for wkhtmltopdf, you'll need to install that, too\n respond_to do |format|\n format.html\n format.pdf do\n pdf = render_to_string :pdf => 'test',\n layout: 'pdf.html.erb',\n template: 'show.pdf.slim',\n header: { :right => '[page] of [topage]'},\n margin: {top: 0,\n bottom: 0,\n left: 0,\n right: 0},\n outline: {outline: true,\n outline_depth: 2}\n end\n end\n = link_to 'Download Pdf', you_show_path(@uour_object, format: :pdf)\n attachments[\"test.pdf\"] = File.read(Rails.root.join('public',\"test.pdf\"))\nmail(:to => to, :cc => cc , :subject => \"subject\")\n File.delete(Rails.root.join(\"public\", \"test.pdf\"))\n"
},
{
"answer_id": 44859380,
"author": "Johnny",
"author_id": 2811258,
"author_profile": "https://Stackoverflow.com/users/2811258",
"pm_score": 0,
"selected": false,
"text": "//initialization \nrequire 'grabzit'\ngrabzItClient = GrabzIt::Client.new(\"APPLICATION KEY\", \"APPLICATION SECRET\")\n\n//capturing the url to PDF\ngrabzItClient.url_to_pdf(\"http://www.google.com\") \n save grabzItClient.save(\"http://www.example.com/handler/index\") \n save_to filepath = \"images/result.jpg\"\ngrabzItClient.save_to(filepath) \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31278/"
] |
357,243 | <p>I am inputting a 200mb file in my application and due to a very strange reason the memory usage of my application is more than 600mb. I have tried vector and deque, as well as std::string and char * with no avail. I need the memory usage of my application to be almost the same as the file I am reading, any suggestions would be extremely helpful.
Is there a bug that causes so much memory consumption? Could you pinpoint the problem or should I rewrite the whole thing?</p>
<p>Windows Vista SP1 x64, Microsoft Visual Studio 2008 SP1, 32Bit Release Version, Intel CPU</p>
<p>The whole application until now:</p>
<pre><code>#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <time.h>
static unsigned int getFileSize (const char *filename)
{
std::ifstream fs;
fs.open (filename, std::ios::binary);
fs.seekg(0, std::ios::beg);
const std::ios::pos_type start_pos = fs.tellg();
fs.seekg(0, std::ios::end);
const std::ios::pos_type end_pos = fs.tellg();
const unsigned int ret_filesize (static_cast<unsigned int>(end_pos - start_pos));
fs.close();
return ret_filesize;
}
void str2Vec (std::string &str, std::vector<std::string> &vec)
{
int newlineLastIndex(0);
for (int loopVar01 = str.size(); loopVar01 > 0; loopVar01--)
{
if (str[loopVar01]=='\n')
{
newlineLastIndex = loopVar01;
break;
}
}
int remainder(str.size()-newlineLastIndex);
std::vector<int> indexVec;
indexVec.push_back(0);
for (unsigned int lpVar02 = 0; lpVar02 < (str.size()-remainder); lpVar02++)
{
if (str[lpVar02] == '\n')
{
indexVec.push_back(lpVar02);
}
}
int memSize(0);
for (int lpVar03 = 0; lpVar03 < (indexVec.size()-1); lpVar03++)
{
memSize = indexVec[(lpVar03+1)] - indexVec[lpVar03];
std::string tempStr (memSize,'0');
memcpy(&tempStr[0],&str[indexVec[lpVar03]],memSize);
vec.push_back(tempStr);
}
}
void readFile(const std::string &fileName, std::vector<std::string> &vec)
{
static unsigned int fileSize = getFileSize(fileName.c_str());
static std::ifstream fileStream;
fileStream.open (fileName.c_str(),std::ios::binary);
fileStream.clear();
fileStream.seekg (0, std::ios::beg);
const int chunks(1000);
int singleChunk(fileSize/chunks);
int remainder = fileSize - (singleChunk * chunks);
std::string fileStr (singleChunk, '0');
int fileIndex(0);
for (int lpVar01 = 0; lpVar01 < chunks; lpVar01++)
{
fileStream.read(&fileStr[0], singleChunk);
str2Vec(fileStr, vec);
}
std::string remainderStr(remainder, '0');
fileStream.read(&remainderStr[0], remainder);
str2Vec(fileStr, vec);
}
int main (int argc, char *argv[])
{
std::vector<std::string> vec;
std::string inFile(argv[1]);
readFile(inFile, vec);
}
</code></pre>
| [
{
"answer_id": 357327,
"author": "Edouard A.",
"author_id": 41363,
"author_profile": "https://Stackoverflow.com/users/41363",
"pm_score": 4,
"selected": true,
"text": " HANDLE heaps[1025];\n DWORD nheaps = GetProcessHeaps((sizeof(heaps) / sizeof(HANDLE)) - 1, heaps);\n\n for (DWORD i = 0; i < nheaps; ++i) \n {\n ULONG HeapFragValue = 2;\n HeapSetInformation(heaps[i],\n HeapCompatibilityInformation,\n &HeapFragValue,\n sizeof(HeapFragValue));\n }\n"
},
{
"answer_id": 357450,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 2,
"selected": false,
"text": "mmap() MapViewOfFile()"
},
{
"answer_id": 358489,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "#include <string>\n#include <vector>\n#include <list>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n#include <iostream>\n\nclass Line: public std::string\n{\n};\n\nstd::istream& operator>>(std::istream& in,Line& line)\n{\n // Relatively efficient way to copy a line into a string.\n return std::getline(in,line);\n}\nstd::ostream& operator<<(std::ostream& out,Line const& line)\n{\n return out << static_cast<std::string const&>(line) << \"\\n\";\n}\n\nvoid readLinesFromStream(std::istream& stream,std::vector<Line>& lines)\n{\n /*\n * Read into a list as this is flexible in memory usage and will not\n * allocate huge chunks of un-required space.\n *\n * Even with huge files the space for list will be insignificant\n * compared to the size of the data.\n *\n * This then allows us to reserve the correct size of the vector\n * Thus avoiding huge memory chunks being prematurely allocated that\n * are not required. It also prevents the internal structure from\n * being copied every time the container is re-sized.\n */\n std::list<Line> data;\n std::copy( std::istream_iterator<Line>(stream),\n std::istream_iterator<Line>(),\n std::inserter(data,data.end())\n );\n\n /*\n * Reserve the correct size in the vector.\n * then copy out of the list into the vector\n */\n lines.reserve(data.size());\n std::copy( data.begin(),\n data.end(),\n std::back_inserter(lines)\n );\n}\n\nvoid readLinesFromFile(std::string const& name,std::vector<Line>& lines)\n{\n /*\n * Set up the file stream and override the default buffer used by the stream.\n * Make it big because we think the istream buffer is insufficient!!!!\n */\n std::ifstream file;\n std::vector<char> buffer(10000);\n file.rdbuf()->pubsetbuf(&buffer[0],buffer.size());\n\n file.open(name.c_str());\n readLinesFromStream(file,lines);\n}\n\n\nint main(int argc,char* argv[])\n{\n std::vector<Line> lines;\n readLinesFromFile(argv[1],lines);\n\n // Un-comment if your file is larger than 1100 lines.\n\n // I tested with a copy of the King James bible. \n // std::cout << \"Lines: \" << lines.size() << \"\\n\";\n // std::copy(lines.begin() + 1000,lines.begin() + 1100,std::ostream_iterator<Line>(std::cout));\n}\n"
},
{
"answer_id": 358525,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "fileStream static str2Vec"
},
{
"answer_id": 379439,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "const char * std::pair<const char*, const char*> const char*"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28954/"
] |
357,244 | <p>One of my columns type is DateTime (Date Registered). I cannot create a query that filters all the data for eg. All registrations who registered on the 22/10/2008 between 18:00 and 20:00.</p>
<p>Thanks</p>
| [
{
"answer_id": 357271,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": true,
"text": "SELECT *\nFROM YourTable\nWHERE DateRegistered BETWEEN '10/22/2008 18:00:00' AND '10/22/2008 20:00:00'\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] |
357,297 | <p>The site I'm working on is done in Classic ASP, and I'm trying to do it as best as possible. I've abstracted it out into a Rails-like directory structure:</p>
<pre>
app_name
- app
- includes
- helpers
- lib
- partials
- public
- stylesheets
- images
- javascripts
</pre>
<p>I've created some Rails-like helpers, for example:</p>
<pre><code>Function ImageTag(ByVal imageFileName, ByVal altText)
path = Server.MapPath(IMAGE_ROOT & imageFileName & ".jpg")
ImageTag = "<img src=""" & path & """ title=""" & altText & """ alt=""" & altText & """ />"
End Function
</code></pre>
<p>Which is used thusly:</p>
<pre><code><%= ImageTag("my_pic") %>
</code></pre>
<p>With "IMAGE_ROOT" defined as "../public/images/" in a config file. I'm doing development on XP so the site is set as a virtual directory. However, the image won't load on the webpage at all. It's displaying the right path to it, because I can copy/paste it into my browser and view the image - it just won't display on the page for some reason. The same thing goes for my CSS stylesheet - the path is right but the page isn't rendering it at all.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 357326,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "Server.MapPath C:\\InetPub\\...\\public\\images\\my_pic.jpg /public/images/my_pic.jpg"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40667/"
] |
357,307 | <p>How do I call the parent function from a derived class using C++? For example, I have a class called <code>parent</code>, and a class called <code>child</code> which is derived from parent. Within
each class there is a <code>print</code> function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?</p>
| [
{
"answer_id": 357312,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": false,
"text": "Parent Child class Parent {\npublic:\n virtual void print(int x);\n};\n\nclass Child : public Parent {\n void print(int x) override;\n};\n\nvoid Parent::print(int x) {\n // some default behavior\n}\n\nvoid Child::print(int x) {\n // use Parent's print method; implicitly passes 'this' to Parent::print\n Parent::print(x);\n}\n Parent"
},
{
"answer_id": 357325,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 5,
"selected": false,
"text": "Base FooBar() Base::FooBar() void Base::FooBar()\n{\n printf(\"in Base\\n\");\n}\n\nvoid ChildOfBase::FooBar()\n{\n Base::FooBar();\n}\n"
},
{
"answer_id": 357380,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 11,
"selected": true,
"text": "private base_class::foo(...) super base class left {\npublic:\n void foo();\n};\n\nclass right {\npublic:\n void foo();\n};\n\nclass bottom : public left, public right {\npublic:\n void foo()\n {\n //base::foo();// ambiguous\n left::foo();\n right::foo();\n\n // and when foo() is not called for 'this':\n bottom b;\n b.left::foo(); // calls b.foo() from 'left'\n b.right::foo(); // call b.foo() from 'right'\n }\n};\n class bottom : public left, public left { // Illegal\n};\n"
},
{
"answer_id": 912128,
"author": "Andrey",
"author_id": 106688,
"author_profile": "https://Stackoverflow.com/users/106688",
"pm_score": 5,
"selected": false,
"text": "// deriv_super.cpp\n// compile with: /c\nstruct B1 {\n void mf(int) {}\n};\n\nstruct B2 {\n void mf(short) {}\n\n void mf(char) {}\n};\n\nstruct D : B1, B2 {\n void mf(short) {\n __super::mf(1); // Calls B1::mf(int)\n __super::mf('s'); // Calls B2::mf(char)\n }\n};\n"
},
{
"answer_id": 23996527,
"author": "superbem",
"author_id": 2170324,
"author_profile": "https://Stackoverflow.com/users/2170324",
"pm_score": -1,
"selected": false,
"text": "struct a{\n int x;\n\n struct son{\n a* _parent;\n void test(){\n _parent->x=1; //success\n }\n }_son;\n\n }_a;\n\nint main(){\n _a._son._parent=&_a;\n _a._son.test();\n}\n"
},
{
"answer_id": 34461014,
"author": "Ajay yadav",
"author_id": 2575399,
"author_profile": "https://Stackoverflow.com/users/2575399",
"pm_score": 3,
"selected": false,
"text": "#include<iostream>\nusing namespace std;\n\nclass Parent\n{\n protected:\n virtual void fun(int i)\n {\n cout<<\"Parent::fun functionality write here\"<<endl;\n }\n void fun1(int i)\n {\n cout<<\"Parent::fun1 functionality write here\"<<endl;\n }\n void fun2()\n {\n\n cout<<\"Parent::fun3 functionality write here\"<<endl;\n }\n\n};\n\nclass Child:public Parent\n{\n public:\n virtual void fun(int i)\n {\n cout<<\"Child::fun partial functionality write here\"<<endl;\n Parent::fun(++i);\n Parent::fun2();\n }\n void fun1(int i)\n {\n cout<<\"Child::fun1 partial functionality write here\"<<endl;\n Parent::fun1(++i);\n }\n\n};\nint main()\n{\n Child d1;\n d1.fun(1);\n d1.fun1(2);\n return 0;\n}\n $ g++ base_function_call_from_derived.cpp\n$ ./a.out \nChild::fun partial functionality write here\nParent::fun functionality write here\nParent::fun3 functionality write here\nChild::fun1 partial functionality write here\nParent::fun1 functionality write here\n"
},
{
"answer_id": 55987086,
"author": "Dean P",
"author_id": 5959372,
"author_profile": "https://Stackoverflow.com/users/5959372",
"pm_score": 3,
"selected": false,
"text": "class Primate {\npublic:\n void whatAmI(){\n cout << \"I am of Primate order\";\n }\n};\n\nclass Human : public Primate{\npublic:\n void whatAmI(){\n cout << \"I am of Human species\";\n }\n void whatIsMyOrder(){\n Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR\n }\n};\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] |
357,314 | <p>I am using Cygwin with a dll version of 1.5.19 (yes, out-of-date, I know, but we're doing it for configuration control reasons). All my files (existing and newly created) show up with permissions 644, despite a umask of 022. Also, using chmod doesn't change the permissions. I have ntsec set in the CYGWIN environment variable. I need to be able to add execute permissions; is there anything I can try to fix this or is it a lost cause?</p>
<hr>
<p>A much later note: I realized that a key part of the problem is that the files I was trying to chmod were in a ClearCase dynamic view, which uses MVFS. I still have not found way to successfully set the execute permissions, though.</p>
| [
{
"answer_id": 357572,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "/etc/passwd /etc/group chmod"
},
{
"answer_id": 1599607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "/etc/passwd /etc/bash.bashrc $HOME/.bashrc .bash_profile"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5241/"
] |
357,315 | <p>I'd like to find a Windows batch counterpart to Bash's <code>$@</code> that holds a list of all arguments passed into a script. </p>
<p>Or I have to bother with <code>shift</code>?</p>
| [
{
"answer_id": 357338,
"author": "dancavallaro",
"author_id": 42891,
"author_profile": "https://Stackoverflow.com/users/42891",
"pm_score": 7,
"selected": false,
"text": "%*"
},
{
"answer_id": 382312,
"author": "matt wilkie",
"author_id": 14420,
"author_profile": "https://Stackoverflow.com/users/14420",
"pm_score": 10,
"selected": true,
"text": "%* %0 foo ..\\foo c:\\bats\\foo.bat %1 %2 %9 SHIFT %~nx0 %~dp0 %~dpnx0"
},
{
"answer_id": 5338799,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 6,
"selected": false,
"text": "%1 %n %* myBatch.bat \"&\"^&\n \"&\"& set var=%1\nset \"var=%1\"\nset var=%~1\nset \"var=%~1\"\n @echo off\nSETLOCAL DisableDelayedExpansion\n\nSETLOCAL\nfor %%a in (1) do (\n set \"prompt=$_\"\n echo on\n for %%b in (1) do rem * #%1#\n @echo off\n) > param.txt\nENDLOCAL\n\nfor /F \"delims=\" %%L in (param.txt) do (\n set \"param1=%%L\"\n)\nSETLOCAL EnableDelayedExpansion\nset \"param1=!param1:*#=!\"\nset \"param1=!param1:~0,-2!\"\necho %%1 is '!param1!'\n echo on %1 rem echo on * # /? param1 param1 %0 FoO.BaT %0 %~0 %~f0 @echo off\necho main %0, %~0, %~f0\ncall :myLabel+xyz\nexit /b\n\n:MYlabel\necho func %0, %~0, %~f0\nexit /b\n main test.bat, test.bat, C:\\temp\\test.bat\nfunc :myLabel+xyz, :myLabel+xyz, C:\\temp\\test.bat\n"
},
{
"answer_id": 9848832,
"author": "KFL",
"author_id": 695964,
"author_profile": "https://Stackoverflow.com/users/695964",
"pm_score": 6,
"selected": false,
"text": "call /? ...\n\n%* in a batch script refers to all the arguments (e.g. %1 %2 %3\n %4 %5 ...)\n\nSubstitution of batch parameters (%n) has been enhanced. You can\nnow use the following optional syntax:\n\n %~1 - expands %1 removing any surrounding quotes (\")\n %~f1 - expands %1 to a fully qualified path name\n %~d1 - expands %1 to a drive letter only\n %~p1 - expands %1 to a path only\n %~n1 - expands %1 to a file name only\n %~x1 - expands %1 to a file extension only\n %~s1 - expanded path contains short names only\n %~a1 - expands %1 to file attributes\n %~t1 - expands %1 to date/time of file\n %~z1 - expands %1 to size of file\n %~$PATH:1 - searches the directories listed in the PATH\n environment variable and expands %1 to the fully\n qualified name of the first one found. If the\n environment variable name is not defined or the\n file is not found by the search, then this\n modifier expands to the empty string\n\nThe modifiers can be combined to get compound results:\n\n %~dp1 - expands %1 to a drive letter and path only\n %~nx1 - expands %1 to a file name and extension only\n %~dp$PATH:1 - searches the directories listed in the PATH\n environment variable for %1 and expands to the\n drive letter and path of the first one found.\n %~ftza1 - expands %1 to a DIR like output line\n\nIn the above examples %1 and PATH can be replaced by other\nvalid values. The %~ syntax is terminated by a valid argument\nnumber. The %~ modifiers may not be used with %*\n"
},
{
"answer_id": 16158149,
"author": "djangofan",
"author_id": 118228,
"author_profile": "https://Stackoverflow.com/users/118228",
"pm_score": 5,
"selected": false,
"text": "@ECHO off\nECHO The %~nx0 script args are...\nfor %%I IN (%*) DO ECHO %%I\npause\n"
},
{
"answer_id": 17932145,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@setlocal enableextensions enabledelayedexpansion\n@ECHO off\nECHO.\nECHO :::::::::::::::::::::::::: arg.bat example :::::::::::::::::::::::::::::::\nECHO :: By: User2631477, 2013-07-29 ::\nECHO :: Version: 1.0 ::\nECHO :: Purpose: Checks the args passed to the batch. ::\nECHO :: ::\nECHO :: Start by gathering all the args with the %%* in a for loop. ::\nECHO :: ::\nECHO :: Now we use a 'for' loop to search for our keys which are identified ::\nECHO :: by the text '--'. The function then sets the --arg ^= to the next ::\nECHO :: arg. \"CALL:Function_GetValue\" ^<search for --^> ^<each arg^> ::\nECHO :: ::\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nECHO.\n\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO :: From the command line you could pass... arg.bat --x 90 --y 220 ::\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO.\nECHO.Checking Args:\"%*\"\n\nFOR %%a IN (%*) do (\n CALL:Function_GetValue \"--\",\"%%a\" \n)\n\nECHO.\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO :: Now lets check which args were set to variables... ::\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO.\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO :: For this we are using the CALL:Function_Show_Defined \"--x,--y,--z\" ::\nECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO.\nCALL:Function_Show_Defined \"--x,--y,--z\"\nendlocal\ngoto done\n\n:Function_GetValue\n\nREM First we use find string to locate and search for the text.\necho.%~2 | findstr /C:\"%~1\" 1>nul\n\nREM Next we check the errorlevel return to see if it contains a key or a value\nREM and set the appropriate action.\n\nif not errorlevel 1 (\n SET KEY=%~2\n) ELSE (\n SET VALUE=%~2\n)\nIF DEFINED VALUE (\n SET %KEY%=%~2\n ECHO.\n ECHO ::::::::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::\n ECHO :: The KEY:'%KEY%' is now set to the VALUE:'%VALUE%' ::\n ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n ECHO.\n ECHO %KEY%=%~2\n ECHO.\n REM It's important to clear the definitions for the key and value in order to\n REM search for the next key value set.\n SET KEY=\n SET VALUE=\n)\nGOTO:EOF\n\n:Function_Show_Defined \nECHO.\nECHO ::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::::\nECHO :: Checks which args were defined i.e. %~2\nECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nECHO.\nSET ARGS=%~1\nfor %%s in (%ARGS%) DO (\n ECHO.\n ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n ECHO :: For the ARG: '%%s' \n IF DEFINED %%s (\n ECHO :: Defined as: '%%s=!%%s!' \n ) else (\n ECHO :: Not Defined '%%s' and thus has no value.\n )\n ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n ECHO.\n)\ngoto:EOF\n\n:done\n"
},
{
"answer_id": 34920539,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "params params_1 params_n n params_0 @echo off\n\nrem Storing the program parameters into the array 'params':\nrem Delayed expansion is left disabled in order not to interpret \"!\" in program parameters' values;\nrem however, if a parameter is not quoted, special characters in it (like \"^\", \"&\", \"|\") get interpreted at program launch\nset /a count=0\n:repeat\n set /a count+=1\n set \"params_%count%=%~1\"\n shift\n if defined params_%count% (\n goto :repeat\n ) else (\n set /a count-=1\n ) \nset /a params_0=count\n\nrem Printing the program parameters stored in the array 'params':\nrem After the variables params_1 .. params_n are set with the program parameters' values, delayed expansion can\nrem be enabled and \"!\" are not interpreted in the variables params_1 .. params_n values\nsetlocal enabledelayedexpansion\n for /l %%i in (1,1,!params_0!) do (\n echo params_%%i: \"!params_%%i!\"\n )\nendlocal\n\npause\ngoto :eof\n"
},
{
"answer_id": 36320045,
"author": "John Ahearn",
"author_id": 6137002,
"author_profile": "https://Stackoverflow.com/users/6137002",
"pm_score": 0,
"selected": false,
"text": "prog_ZipDeleteFiles.bat \"_appPath=C:\\Services\\Logs\\PCAP\" \"_appFile=PCAP*.?\"\n set \"_appPath=C:\\Services\\Logs\\PCAP\"\nset \"_appFile=PCAP*.?\"\n for /f \"tokens* delims= \" in %%A (%*) DO (\n set %%A\n)\n set \"_appPath=C:\\Services\\Logs\\PCAP\"\n set \"_appPath=C:\\Services\\Logs\\PCAP\"\nset \"_appFile=PCAP*.?\"\n SETLOCAL EnableDelayedExpansion\n echo on\n:processArguments\n:: Process all arguments in the order received\nif defined %1 then (\n set %1\n shift\n goto:processArguments\n) ELSE (\n echo off \n)\n echo on\nshift\n:processArguments\n:: Process all arguments in the order received\nif defined %0 then (\n set %0\n shift\n goto:processArguments\n) ELSE (\n echo off \n)\n"
},
{
"answer_id": 51896641,
"author": "Speedstone",
"author_id": 1619541,
"author_profile": "https://Stackoverflow.com/users/1619541",
"pm_score": 2,
"selected": false,
"text": "%* set args=%1\nshift\n:start\nif [%1] == [] goto done\nset args=%args% %1\nshift\ngoto start\n\n:done\n(use %args% here)\n"
},
{
"answer_id": 54907230,
"author": "Io-oI",
"author_id": 8177207,
"author_profile": "https://Stackoverflow.com/users/8177207",
"pm_score": 2,
"selected": false,
"text": "?*&<> @echo off && setlocal EnableDelayedExpansion\n\nfor %%Z in (%*)do set \"_arg_=%%Z\" && set/a \"_cnt+=1+0\" && call set \"_arg_[!_cnt!]=!_arg_!\")\n\n:: write/test these arguments/parameters ::\nfor /l %%l in (1 1 !_cnt!)do echo/ The argument n:%%l is: !_arg_[%%l]!\n\ngoto :eof \n @echo off && setlocal EnableDelayedExpansion\n\nfor %%Z in (%*)do set \"_arg_=%%Z\" && set/a \"_cnt+=1+0\" && call set \"_arg_[!_cnt!]=!_arg_!\"\n\necho= !_arg_[1]! !_arg_[2]! !_arg_[2]!> log.txt\n"
},
{
"answer_id": 56921888,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "For For /? Setlocal /? @echo off\n::For Run Use This = cmd /c \"\"Args.cmd\" Hello USER Scientist etc\"\nsetlocal EnableDelayedExpansion\nset /a Count=0\nfor %%I IN (%*) DO (\n Echo Arg_!Count! = %%I\n set /a Count+=1 \n)\nEcho Count Of Args = !Count!\nEndlocal\n"
},
{
"answer_id": 60079059,
"author": "Fortu",
"author_id": 12846425,
"author_profile": "https://Stackoverflow.com/users/12846425",
"pm_score": 0,
"selected": false,
"text": "Test.bat uno dos tres cuatro cinco seis siete\n @echo off \nsetlocal EnableDelayedExpansion\n\necho Option 1: one by one (same line)\necho %3, %4, %5\necho.\n\necho Option 2: Loop For one by one\nfor %%a in (%3, %4, %5) do echo %%a\necho.\n\necho Option 3: Loop For with check of limits\nset i=0\nfor %%a in (%*) do (\n set /A i=i+1\n If !i! GTR 2 if !i! LSS 6 echo %%a\n)\necho.\n\necho Option 4: Loop For with auxiliary list\nfor /l %%i in (3,1,5) do (\n set a=%%i\n set b=echo %%\n set b=!b!!a!\n call !b!\n)\necho.\n\necho Option 5: Assigning to an array of elements previously\nset e[0]=%0\nset i=0 \nfor %%a in (%*) do (\n set /A i=i+1\n set e[!i!]=%%a\n)\nfor /l %%i in (3,1,5) do (\n echo !e[%%i]!\n)\necho.\n\necho Option 6: using shift and goto loop. It doesn't work with for loop\nset i=2\n:loop6\n set /A i=i+1\n echo %3\n shift\n If %i% LSS 5 goto :loop6\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/357315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15647/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.