qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
313,643 | <p>How can I differentiate a Workflow system from a normal application that automates some work? Are there any specific feature a system must have to be categorized as a workflow system?</p>
| [
{
"answer_id": 313716,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "*participant = resource (human or machine)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74340/"
] |
313,649 | <p>When I publish my ASP.NET site in RELEASE mode, and set compilation debug="false", will my ASP.NET and System.Diagnostics Tracing still work?</p>
| [
{
"answer_id": 313654,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": true,
"text": "<configuration>\n <system.web>\n <trace enabled=\"true\" requestLimit=\"40\" localOnly=\"false\"/>\n </system.web>\n</configuration>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22702/"
] |
313,652 | <p>I have a self-developed program which I want to use as the default opening tool for .jpg and .bmp files. How can I achieve the goal progrmmatically? </p>
<p>Some said that I have to add some registry entries. But I don't konw exactly what I should do. Can anyone tell me the method?</p>
<p>Thank you!</p>
| [
{
"answer_id": 313689,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 0,
"selected": false,
"text": "[HKEY_CLASSES_ROOT\\.txt]\n@=\"textfile\"\n\n[HKEY_CLASSES_ROOT\\textfile\\shell\\open\\command]\n@=\"C:\\\\WINDOWS\\\\NOTEPAD.EXE %1\"\n\n[HKEY_CLASSES_ROOT\\textfile\\shell\\print\\command]\n@=\"C:\\\\WINDOWS\\\\NOTEPAD.EXE /p %1\"\n\n[HKEY_CLASSES_ROOT\\textfile\\DefaultIcon]\n@=\"C:\\\\WINDOWS\\\\SYSTEM\\\\shell32.dll,-152\"\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
313,653 | <p>Is there a way to set "work offline" in TFS without having to try opening a solution, waiting for it to time out, and then having Visual Studio work out that it has failed?</p>
<p>It seems a touch ridiculous that I can't just tick a box to tell it myself, seeing as I'm probably the one most qualified to know when I'm not in the office!</p>
| [
{
"answer_id": 2271119,
"author": "Richard Berg",
"author_id": 74439,
"author_profile": "https://Stackoverflow.com/users/74439",
"pm_score": 4,
"selected": true,
"text": "C:\\Users\\Richard> tfpt tweakui /?\ntfpt tweakui - Enhance how client connects to Team Foundation Server\n\nAllows configuration of how and when the client connects to a \nTeam Foundation Server. This includes client certificates, auto\nreconnect, offline, compression, maximum connections, timeouts, \nand bypassing the proxy.\n"
},
{
"answer_id": 30735947,
"author": "demoncodemonkey",
"author_id": 61697,
"author_profile": "https://Stackoverflow.com/users/61697",
"pm_score": 0,
"selected": false,
"text": "TEAM -> Go Offline\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
313,693 | <p>I want to run program on background . pref C#
I want put icon in the tray.
On specified time it’s synchronizes folders (I know how to sync folders) .
How to run it on background and start sync ( for example at 2am)?</p>
| [
{
"answer_id": 313705,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 1,
"selected": false,
"text": "Form.Visible = False\nForm.ShowInTaskbar = False\n"
},
{
"answer_id": 11197360,
"author": "user1481088",
"author_id": 1481088,
"author_profile": "https://Stackoverflow.com/users/1481088",
"pm_score": 1,
"selected": false,
"text": "MainForm.WindowState = System.Windows.Forms.FormWindowState.Minimized;\nMainForm.ShowInTaskBar = false;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,712 | <p>I have to call ping from c++ code.I'd like to easily read the output for further utilizations.</p>
<p>I have come up with two solutions:</p>
<ul>
<li>use a fork and a pipe, redirect ping output to the pipe and then parse it</li>
<li>find a library suited for the purpose to use a ping(ip_addresss) function directly</li>
</ul>
<p>I'd like the latter but i didn't find anything that was clearly a standard solution.</p>
<p>How would you do it ?</p>
| [
{
"answer_id": 313760,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 2,
"selected": false,
"text": "ping4 ping6 popen(2) pipe fork exec"
},
{
"answer_id": 15573612,
"author": "omeraygor",
"author_id": 969263,
"author_profile": "https://Stackoverflow.com/users/969263",
"pm_score": 3,
"selected": false,
"text": "#include <fcntl.h>\n#include <errno.h>\n#include <sys/socket.h>\n#include <resolv.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <netinet/ip_icmp.h>\n\n\n#define PACKETSIZE 64\nstruct packet\n{\n struct icmphdr hdr;\n char msg[PACKETSIZE-sizeof(struct icmphdr)];\n};\n\nint pid=-1;\nstruct protoent *proto=NULL;\nint cnt=1;\n\n/*--------------------------------------------------------------------*/\n/*--- checksum - standard 1s complement checksum ---*/\n/*--------------------------------------------------------------------*/\nunsigned short checksum(void *b, int len)\n{\n unsigned short *buf = b;\n unsigned int sum=0;\n unsigned short result;\n\n for ( sum = 0; len > 1; len -= 2 )\n sum += *buf++;\n if ( len == 1 )\n sum += *(unsigned char*)buf;\n sum = (sum >> 16) + (sum & 0xFFFF);\n sum += (sum >> 16);\n result = ~sum;\n return result;\n}\n\n\n/*--------------------------------------------------------------------*/\n/*--- ping - Create message and send it. ---*/\n/* return 0 is ping Ok, return 1 is ping not OK. ---*/\n/*--------------------------------------------------------------------*/\nint ping(char *adress)\n{\n const int val=255;\n int i, sd;\n struct packet pckt;\n struct sockaddr_in r_addr;\n int loop;\n struct hostent *hname;\n struct sockaddr_in addr_ping,*addr;\n\n pid = getpid();\n proto = getprotobyname(\"ICMP\");\n hname = gethostbyname(adress);\n bzero(&addr_ping, sizeof(addr_ping));\n addr_ping.sin_family = hname->h_addrtype;\n addr_ping.sin_port = 0;\n addr_ping.sin_addr.s_addr = *(long*)hname->h_addr;\n\n addr = &addr_ping;\n\n sd = socket(PF_INET, SOCK_RAW, proto->p_proto);\n if ( sd < 0 )\n {\n perror(\"socket\");\n return 1;\n }\n if ( setsockopt(sd, SOL_IP, IP_TTL, &val, sizeof(val)) != 0)\n {\n perror(\"Set TTL option\");\n return 1;\n }\n if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )\n {\n perror(\"Request nonblocking I/O\");\n return 1;\n }\n\n for (loop=0;loop < 10; loop++)\n {\n\n int len=sizeof(r_addr);\n\n if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &len) > 0 )\n {\n return 0;\n }\n\n bzero(&pckt, sizeof(pckt));\n pckt.hdr.type = ICMP_ECHO;\n pckt.hdr.un.echo.id = pid;\n for ( i = 0; i < sizeof(pckt.msg)-1; i++ )\n pckt.msg[i] = i+'0';\n pckt.msg[i] = 0;\n pckt.hdr.un.echo.sequence = cnt++;\n pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));\n if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)addr, sizeof(*addr)) <= 0 )\n perror(\"sendto\");\n\n usleep(300000);\n\n }\n\n return 1;\n}\n\n/*--------------------------------------------------------------------*/\n/*--- main - look up host and start ping processes. ---*/\n/*--------------------------------------------------------------------*/\nint main(int argc, char *argv[])\n{\n\n if (ping(\"www.google.com\"))\n printf(\"Ping is not OK. \\n\");\n else\n printf(\"Ping is OK. \\n\");\n\n\n return 0;\n}\n"
},
{
"answer_id": 73908466,
"author": "tswaehn",
"author_id": 3161034,
"author_profile": "https://Stackoverflow.com/users/3161034",
"pm_score": 0,
"selected": false,
"text": " #include <oping.h>\n\n int main(){\n \n // run ping 100times\n for (uint32_t i=0; i< 100; i++){\n pingobj_t * pingObj = ping_construct();\n ping_host_add(pingObj, \"www.gmx.de\");\n\n auto startTime = std::chrono::high_resolution_clock::now();\n auto ret = ping_send(pingObj);\n auto endTime = std::chrono::high_resolution_clock::now();\n if (ret > 0){\n auto duration = (double)std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count()/1000.0;\n std::cout << \"success -- ping in \" << duration << \"ms\" << std::endl;\n } else {\n std::cout << \"failed\" << std::endl;\n }\n ping_destroy(pingObj);\n \n // wait 1sec\n std::this_thread::sleep_for(std::chrono::milliseconds (1000));\n }\n\n }\n liboping sudo apt install liboping-dev"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38507/"
] |
313,718 | <p>While working on an existing project I suddenly got the following error when trying to compile the solution:</p>
<p><em>error MSB3105: The item "[filename]" was specified more than once in the "Resources" parameter. Duplicate items are not supported by the "Resources" parameter.</em></p>
<p>Now, as far as I'm aware, I did not make any change to the project that affects the resources. Also I have checked each and every file within the project, but there is no duplicate reference anywhere to this file.
Now I already found some forum entries regarding this error:</p>
<p>1) Open the .csproj file and remove the duplicate reference. [Tried this, but I cannot find any duplicates in it]</p>
<p>2) In a 'partial class' project, move everything to a single class. [ Could try this, but the project has been split up into partial classes since the start, and I do not want to change this just because of the error ]</p>
<p>So what else could cause this ?</p>
| [
{
"answer_id": 59934672,
"author": "Xav987",
"author_id": 2546739,
"author_profile": "https://Stackoverflow.com/users/2546739",
"pm_score": 1,
"selected": false,
"text": "MyFile.cs myFile.cs"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4313/"
] |
313,729 | <ul>
<li>How can we implement the Builder
pattern of <a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf?" rel="noreferrer">Joshua's
Effective Java</a> in C#?</li>
</ul>
<p>Below is the code I have tried, is there a better way to do this?</p>
<pre><code> public class NutritionFacts
{
public static NutritionFacts.Builder Build(string name, int servingSize, int servingsPerContainer)
{
return new NutritionFacts.Builder(name, servingSize, servingsPerContainer);
}
public sealed class Builder
{
public Builder(String name, int servingSize,
int servingsPerContainer)
{
}
public Builder totalFat(int val) { }
public Builder saturatedFat(int val) { }
public Builder transFat(int val) { }
public Builder cholesterol(int val) { }
//... 15 more setters
public NutritionFacts build()
{
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) { }
protected NutritionFacts() { }
}
</code></pre>
<ul>
<li><p>How do we extend such a class? Do
we need to write separate builder
classes for each of the derived
classes?</p>
<pre><code>public class MoreNutritionFacts : NutritionFacts
{
public new static MoreNutritionFacts.Builder Build(string name, int servingSize, int servingsPerContainer)
{
return new MoreNutritionFacts.Builder(name, servingSize, servingsPerContainer);
}
public new sealed class Builder
{
public Builder(String name, int servingSize,
int servingsPerContainer) {}
public Builder totalFat(int val) { }
public Builder saturatedFat(int val) { }
public Builder transFat(int val) { }
public Builder cholesterol(int val) { }
//... 15 more setters
public Builder newProperty(int val) { }
public MoreNutritionFacts build()
{
return new MoreNutritionFacts(this);
}
}
private MoreNutritionFacts(MoreNutritionFacts.Builder builder) { }
}
</code></pre></li>
</ul>
| [
{
"answer_id": 313747,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "public sealed class SomeMessage\n{\n public string Name { get; private set; }\n public int Age { get; private set; }\n\n // Can only be called in this class and nested types\n private SomeMessage() {}\n\n public sealed class Builder\n {\n private SomeMessage message = new SomeMessage();\n\n public string Name\n {\n get { return message.Name; }\n set { message.Name = value; }\n }\n\n public int Age\n {\n get { return message.Age; }\n set { message.Age = value; }\n }\n\n public SomeMessage Build()\n {\n // Check for optional fields etc here\n SomeMessage ret = message;\n message = null; // Builder is invalid after this\n return ret;\n }\n }\n}\n StringBuilder Build() this"
},
{
"answer_id": 313806,
"author": "alasdairg",
"author_id": 15768,
"author_profile": "https://Stackoverflow.com/users/15768",
"pm_score": 2,
"selected": false,
"text": "public class CustomerBuilder\n{\n\n ...... \n\n public static implicit operator Customer( CustomerBuilder builder ) \n { \n return builder.Build();\n } \n}\n"
},
{
"answer_id": 319546,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 2,
"selected": false,
"text": "public abstract class Builder<T> : IBuilder<T>\n{\n public static implicit operator T(Builder<T> builder)\n {\n return builder.Instance;\n }\n\n private T _instance;\n\n public bool HasInstance { get; private set; }\n\n public T Instance\n {\n get\n {\n if(!HasInstance)\n {\n _instance = CreateInstance();\n\n HasInstance = true;\n }\n\n return _instance;\n }\n }\n\n protected abstract T CreateInstance();\n\n public void ClearInstance()\n {\n _instance = default(T);\n\n HasInstance = false;\n }\n}\n Order public class Order\n{\n public string ReferenceNumber { get; private set; }\n\n public DateTime? ApprovedDateTime { get; private set; }\n\n public void Approve()\n {\n ApprovedDateTime = DateTime.Now;\n }\n}\n ReferenceNumber public Order(string referenceNumber)\n{\n // ... validate ...\n\n ReferenceNumber = referenceNumber;\n}\n Order ReferenceNumber ApprovedDateTime virtual Builder internal internal Order internal Order(string referenceNumber, DateTime? approvedDateTime)\n{\n ReferenceNumber = referenceNumber;\n ApprovedDateTime = approvedDateTime;\n}\n Builder public class OrderBuilder : Builder<Order>\n{\n private string _referenceNumber;\n private DateTime? _approvedDateTime;\n\n public override Order Create()\n {\n return new Order(_referenceNumber, _approvedDateTime);\n }\n\n public string ReferenceNumber\n {\n get { return _referenceNumber; }\n set { SetField(ref _referenceNumber, value); }\n }\n\n public DateTime? ApprovedDateTime\n {\n get { return _approvedDateTime; }\n set { SetField(ref _approvedDateTime, value); }\n }\n}\n SetField Builder protected bool SetField<TField>(\n ref TField field,\n TField newValue,\n IEqualityComparer<T> equalityComparer = null)\n {\n equalityComparer = equalityComparer ?? EqualityComparer<TField>.Default;\n\n var different = !equalityComparer.Equals(field, newValue);\n\n if(different)\n {\n field = newValue;\n\n ClearInstance();\n }\n\n return different;\n }\n ref Order OrderBuilder Order order = new OrderBuilder\n{\n ReferenceNumber = \"ABC123\",\n ApprovedDateTime = new DateTime(2008, 11, 25)\n};\n"
},
{
"answer_id": 3231719,
"author": "Marc Meketon",
"author_id": 1955013,
"author_profile": "https://Stackoverflow.com/users/1955013",
"pm_score": 0,
"selected": false,
"text": " public class NutritionFacts\n {\n public int servingSize { get; private set; }\n public int servings { get; private set; }\n public int calories { get; private set; }\n public int fat { get; private set; }\n public int carbohydrate { get; private set; }\n public int sodium { get; private set; }\n\n public NutritionFacts(int servingSize, int servings, int calories = 0, int fat = 0, int carbohydrate = 0, int sodium = 0)\n {\n this.servingSize = servingSize;\n this.servings = servings;\n this.calories = calories;\n this.fat = fat;\n this.carbohydrate = carbohydrate;\n this.sodium = sodium;\n }\n }\n NutritionFacts nf2 = new NutritionFacts(240, 2, calories: 100, fat: 40);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26036/"
] |
313,737 | <p>For a certain inputform, I'd like to make it possible to do input with the keyboard. I know how to read the keys through KeyPressed and KeyUp, but the problem is that when a control has got the focus and the user presses the Enter key, that control receives the a Click event. Is it possible to prevent that behaviour ? Or is it possible to know if a Click Event was fired by the mouse or by the keyboard ?</p>
| [
{
"answer_id": 313795,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 2,
"selected": false,
"text": "Form.KeyPreview = True\n e.Handled = True\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34723/"
] |
313,746 | <p>I am mulling over a web-app in Perl that will allow users to create bug monitors. So essentially each "bug watch" will be a bug ID that will be passed to a sub routine along with the "sleep" time, and once the "sleep time" is over it must recur without blocking the parent process or the peer processes.</p>
<ul>
<li><p>I tried <a href="http://search.cpan.org/dist/Schedule-Cron" rel="nofollow noreferrer">Schedule::Cron</a>. It supports cron-like format but here the arguments to the subs must be simple scalars hence I ruled it out.</p>
</li>
<li><p>POE/Coro seem to be another options but I don't have much idea about it/ :(</p>
</li>
</ul>
<p>Any insights ? TIA</p>
<p>-Matt.</p>
| [
{
"answer_id": 314510,
"author": "converter42",
"author_id": 28974,
"author_profile": "https://Stackoverflow.com/users/28974",
"pm_score": 2,
"selected": false,
"text": "$cron->add_entry(\n '* * * * *',\n subroutine => \\&mysub,\n arguments => \\@data,\n);\n my $var = 42;\nmy @arr = get_stuff();\n\n$cron->add_entry(\n '* * * * *',\n sub { mysub($var, @arr) },\n);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,753 | <p>I have a incoming stream of bytes (unsigned char) from either a file or network. I need this data placed in a class, and is looking for a NET-way of doing this. </p>
<p>I bet some does this all the time, so I guess there is a better method to do this than using BitConverter. </p>
<p>I realize I supplied too litle information. Let me try with an example class: </p>
<pre><code>class data {
void doSmething();
int var1;
float var2;
}
</code></pre>
<p>Then I want to transfer the data (var1 and var2) contained in this class over f.ex. a network socket and receive the data on the other end</p>
| [
{
"answer_id": 313823,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": false,
"text": " [Serializable]\n [XmlRoot(\"CONFIGURATION\")]\n public class Configuration\n {\n EnterpriseCollection enterprises;\n public Configuration()\n {\n\n enterprises= new EnterpriseCollection();\n }\n [XmlElement(\"ENTERPRISE\")]\n public EnterpriseCollection Enterprises\n {\n get\n {\n return this.enterprises;\n }\n set\n {\n this.enterprises = value;\n }\n }\n private string name;\n [XmlElement(\"NAME\")]\n public string Name\n {\n get\n {\n return name;\n }\n set\n {\n name = value;\n }\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37583/"
] |
313,754 | <p>What is your preferred way of keeping controls centered on its parent when the parent change width or height? </p>
| [
{
"answer_id": 313867,
"author": "mj2008",
"author_id": 5544,
"author_profile": "https://Stackoverflow.com/users/5544",
"pm_score": 0,
"selected": false,
"text": "procedure TMyForm.FormResize(Sender: TObject);\nvar\n nNewTop : Integer;\nbegin\n inherited;\n pnlRegenerating.Left := (ClientWidth - pnlRegenerating.Width) div 2;\n nNewTop := (ClientHeight div 5) {* 4};\n if (nNewTop + pnlRegenerating.Height) > ClientHeight then\n nNewTop := ClientHeight - pnlRegenerating.Height - 4;\n pnlRegenerating.Top := nNewTop;\nend;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11956/"
] |
313,769 | <p>What is best way to allow user to pick date from a mobile device from usability prospective?</p>
| [
{
"answer_id": 1296513,
"author": "davewasthere",
"author_id": 376,
"author_profile": "https://Stackoverflow.com/users/376",
"pm_score": 3,
"selected": true,
"text": "DateTime.TryParse(String, out DateTime)"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
313,778 | <p>I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?</p>
| [
{
"answer_id": 313787,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 7,
"selected": true,
"text": "g++ -MM <your file> # Add .d to Make's recognized suffixes.\nSUFFIXES += .d\n\n#We don't need to clean up when we're making these targets\nNODEPS:=clean tags svn\n#Find all the C++ files in the src/ directory\nSOURCES:=$(shell find src/ -name \"*.cpp\")\n#These are the dependency files, which make will clean up after it creates them\nDEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES))\n\n#Don't create dependencies when we're cleaning, for instance\nifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))\n #Chances are, these files don't exist. GMake will create them and\n #clean up automatically afterwards\n -include $(DEPFILES)\nendif\n\n#This is the rule for creating the dependency files\nsrc/%.d: src/%.cpp\n $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$<)' $< -MF $@\n\n#This rule does the compilation\nobj/%.o: src/%.cpp src/%.d src/%.h\n @$(MKDIR) $(dir $@)\n $(CXX) $(CXXFLAGS) -o $@ -c $<\n $(CXX) gcc src/"
},
{
"answer_id": 10168396,
"author": "Christopher Smith",
"author_id": 60871,
"author_profile": "https://Stackoverflow.com/users/60871",
"pm_score": 5,
"selected": false,
"text": "-MMD CFLAGS OBJS -include $(OBJS:%.o=%.d)\n"
},
{
"answer_id": 13545596,
"author": "fferri",
"author_id": 1044117,
"author_profile": "https://Stackoverflow.com/users/1044117",
"pm_score": 3,
"selected": false,
"text": "-include Makefile.deps\n\nMakefile.deps:\n $(CC) $(CFLAGS) -MM *.[ch] > Makefile.deps\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
313,781 | <p>I am working on localization for an app where custom patterns are used to format the date-time.</p>
<p>one example is:
dd-MM HH:mm</p>
<p>I need to get localized versions of this custom format for dates, so that I get the date using numbers, and the time, basically using the local order (dd MM or MM dd) and the local seperator for both date and time.</p>
<p>This is fairly trivial, as long as I am using the default formatting, but as soon as I stray from these, the formatting becomes hardcoded.</p>
<p>Any ideas?</p>
<p>Thanks, Jonas</p>
<p>edit:
I have the cultureInfo objects, the problem is that when I do a DateTime.ToString("ES-es"), I get too much info - I need only month+day, but with the default ToString, I get year+month+day</p>
<p>Edit again:
I see how I can change the ShortDate pattern for each CultureInfo object I use. However, I also need the default ShortDate pattern in some situations, so changing that would, unfortunately, leave me with another, equivalent problem.</p>
<p>Final edit: in case anyone cares. I never did find a solution, so I ended up coding a static function that checks the current CultureInfo, and returns the correctly formatted date, sans year.</p>
| [
{
"answer_id": 313809,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 2,
"selected": false,
"text": "DateTime.Now.ToString(new System.Globalization.CultureInfo(Thread.CurrentThread.CurrentCulture.Name));\n DateTime.Now.ToString(new System.Globalization.CultureInfo(\"ES-es\"))\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] |
313,786 | <p>Hej, </p>
<p>assuming I have a code that looks like this:</p>
<pre><code>List<User> userList = GetUserByName (u => u.Name == name);
DoSomethingWithTheUsers (userList.ToArray ());
</code></pre>
<p>Now I want to know the type of the objects in the Array in the method <em>DoSomethingWithTheUsers (object[] myObjects)</em></p>
<p>Simply done by <em>myObjects.First ().GetType ()</em> but what is to be done if the array is empty?
Is there a possibility to still get the Type?</p>
| [
{
"answer_id": 313790,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 5,
"selected": true,
"text": "myObjects.GetType().GetElementType()\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33111/"
] |
313,792 | <p>I'm using a Delphi 2009 VCL TProgressBar as a kind of "empty/full" gauge.</p>
<p>On Vista, with Aero theme enabled, this has an animation associated with it, which is annoying and inappropriate for an gauge.</p>
<p>Is there any way of disabling this (NOT by adjusting user's theme settings!) to prevent the animation on this control?</p>
<p>To clarify, I want something basically identical to the 'disk space used' meters in Windows Explorer. No animation, but still with a nice border and shading effects.</p>
<p>Update:</p>
<p>I understand that I need a "meter", rather than a true progress bar. How can a themed meter be implemented using the standard windows progress bar control?</p>
| [
{
"answer_id": 315742,
"author": "Tim Knipe",
"author_id": 10493,
"author_profile": "https://Stackoverflow.com/users/10493",
"pm_score": 3,
"selected": false,
"text": "SetWindowTheme(ProgressBar.Handle, ' ', ' ');\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
313,794 | <p>I would like to automate the deployment of my SSIS and SSAS artifacts to remote development SQL Server 2005 & 2008 instances on a scheduled basis. </p>
<p>What would be the best solution for this? I am using TFS 2008 as the source control system, so I'd like to integrate the solution with MSBuild and a scheduled Team Build.</p>
| [
{
"answer_id": 5189822,
"author": "Darren",
"author_id": 6065,
"author_profile": "https://Stackoverflow.com/users/6065",
"pm_score": 2,
"selected": false,
"text": " <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <Target Name=\"Build\">\n <PropertyGroup>\n <DevEnvTool Condition=\"'$(DevEnvTool)'==''\">C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe</DevEnvTool>\n <DevEnvBuildCommand>\"$(DevEnvTool)\" \"$(MSBuildProjectDirectory)\\Nexus_VS2008.sln\" /Build</DevEnvBuildCommand>\n </PropertyGroup>\n <Exec Command=\"$(DevEnvBuildCommand)\" />\n <ItemGroup>\n <SSASSourceFiles Include=\"$(MSBuildProjectDirectory)\\Readify.Nexus.Analysis\\bin\\Readify.Nexus.Analysis.*\"/>\n </ItemGroup>\n\n <Copy SourceFiles=\"@(SSASSourceFiles)\" DestinationFolder=\"$(OutDir)\" />\n </Target>\n </Project>\n"
},
{
"answer_id": 10546515,
"author": "piers7",
"author_id": 26167,
"author_profile": "https://Stackoverflow.com/users/26167",
"pm_score": 2,
"selected": false,
"text": "$app = new-object Microsoft.SqlServer.Dts.Runtime.Application\n$app.SaveToSqlServerAs($packageObj, $null, \"\\\\$folderName\\$($packageObj.Name)$packageNameSuffix\", $serverName, $null, $null);\n $asDeploy = \"$programfiles32\\Microsoft SQL Server\\100\\Tools\\Binn\\VSShell\\Common7\\IDE\\Microsoft.AnalysisServices.Deployment.exe\"\n\nwrite-host \"Generating XMLA\"\nstart-process -wait -FilePath:$asDeploy -ArgumentList:\"$pwd\\..\\bin\\MyOlap\\MyOlap.asdatabase\",\"/d\",\"/o:$pwd\\MyOlap.xmla\"\nif (-not $?){\n throw \"Failed to generate XMLA: errors were reported above\";\n}\n\nwrite-host \"Deploying SSAS Database\"\n.\\ascmd.exe -S $olapServer -i \"$pwd\\MyOlap.xmla\"\nif (-not $?){\n throw \"Failed to deploy cube: errors were reported above\";\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
] |
313,796 | <p>How can you get castle Windsor to choose the right implantation of a interface at run time when you have multiple implementations in the container.</p>
<p>For example lets say i have a simple interface called IExamCalc that does calculations to work out how someone did in that exam.</p>
<p>No we have several implementation of this like bellow for example,</p>
<pre><code>public interface IExamCalc
{
int CalculateMark(ExamAnswers examAnswers)
}
public class WritenExam : IExamCalc
{
public int CalculateMark(ExamAnswers examAnswers)
{
return 4;
}
}
public class OralExam : IExamCalc
{
public int CalculateMark(ExamAnswers examAnswers)
{
return 8;
}
}
public class ExamMarkService
{
private IExamCalc _examCalc;
public ExamMarkService(IExamCalc examCalc)
{
_examCalc = examCalc;
}
public int[] CalculateExamMarks(ExamAnswers[] examAnswers)
{
IList<int> marks = new List<int>;
foreach(ExamAnswers examanswer in examaAnswers)
{
marks.Add(_examCalc.CalculateMark);
}
}
}
</code></pre>
<p>Say the ExamMarkService is being resloved through Windor how can i make sure that the correct implementation is injected in the constructor and is this an example of a multi-tenancy problem?</p>
<p>Hope that all makes sence</p>
<p>Colin G</p>
| [
{
"answer_id": 313804,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "container.Resolve<IExamCalc>"
},
{
"answer_id": 313851,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 2,
"selected": false,
"text": "container.Resolve(\"someKey\") <component id=\"someService.customer1\" service=\"ISomeService\" type=\"Customer1SomeService\" />\n\n<component id=\"anotherId\" service=\"IAnotherService\" type=\"AnotherService\">\n <parameters>\n <parameterName> <!-- as written in the ctor's signature -->\n ${someService.customer1}\n </parameterName>\n </parameters> \n</component>\n"
},
{
"answer_id": 319263,
"author": "Chris Canal",
"author_id": 5802,
"author_profile": "https://Stackoverflow.com/users/5802",
"pm_score": 5,
"selected": true,
"text": "public class WritenExamHandler : IHandlerSelector\n {\n public bool HasOpinionAbout(string key, Type service)\n {\n // Decision logic here\n return somethingThatWouldBeTrueToSelectWritenExam && service == typeof(IExamCalc);\n }\n\n public IHandler SelectHandler(string key, Type service, IHandler[] handlers)\n {\n return handlers.Where(handler => handler.ComponentModel.Implementation == typeof (WritenExam)).First();\n }\n }\n container.Kernel.AddHandlerSelector(new WritenExamHandler());\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213936/"
] |
313,805 | <p>I don't want to have the user install Google Gears so I can show him his guessed location. Is there a way to get the location without having to use Google Gears?</p>
<p>I have found <a href="http://www.wipmania.com/de/blog/google-geolocation-api/" rel="noreferrer">http://www.wipmania.com/de/blog/google-geolocation-api/</a> but it does not offer an example.</p>
| [
{
"answer_id": 313812,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 4,
"selected": true,
"text": "<?php\n if(isset($_GET[\"ip\"])){\n echo geolocate($_GET[\"ip\"]);\n }\n\n function geolocate($ip){\n $raw_html = file_get_contents(\"http://www.geody.com/geoip.php?ip=$ip\");\n if(preg_match('/Location:(.*)/',$raw_html,$matches)){\n $location_raw = $matches[1];\n\n //Get rid of pesky HTML tags\n $location = preg_replace(\"/<[^>]*>/\",\"\",$location_raw);\n return $location;\n }else{\n return \"ERROR\";\n }\n }\n"
},
{
"answer_id": 313946,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" \n src=\"http://www.google.com/jsapi?key=ABCDEFG\">\n</script>\n if (google.loader.ClientLocation){\n var center = new google.maps.LatLng(\n google.loader.ClientLocation.latitude,\n google.loader.ClientLocation.longitude\n );\n map.setCenter(center);\n}\n ClientLocation.latitude ClientLocation.longitude ClientLocation.address.city ClientLocation.address.country ClientLocation.address.country_code ClientLocation.address.region"
},
{
"answer_id": 12969452,
"author": "Vignesh Gopalakrishnan",
"author_id": 1758274,
"author_profile": "https://Stackoverflow.com/users/1758274",
"pm_score": 1,
"selected": false,
"text": "function functionname(Your IP Here)\n{\n\n $ip = $ClientIP;\n\n $json = file_get_contents(\"http://api.easyjquery.com/ips/?ip=\".$ip.\"&full=true\");\n\n $json = json_decode($json,true);\n\n return $json;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
] |
313,813 | <pre><code><?php
class Box {
var $contents;
function Box($contents) {
$this-&gt;contents = $contents;
}
function get_whats_inside() {
return $this-&gt;contents;
}
}
?>
</code></pre>
<p>I am going through a OO tutorial. I am familiar with PHP and the concept of OO but it is still an uphill struggle most of the time! However, the code above returns the error "Unexpected & on line 7". I cannot find anyone else having had problems with the tutorial. I am running MAMP with php version 5.2.5. Anyone have any ideas?</p>
| [
{
"answer_id": 313817,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 0,
"selected": false,
"text": "$this->contents = $contents;\nreturn $this->contents;\n $this->contents = $contents;\nreturn $this->contents;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
313,822 | <p>How do you modify a propertygrid at runtime in every way? I want to be able to add and remove properties and add "dynamic types", what I mean with that is a type that result in a runtime generated dropdown in the propertygrid using a TypeConverter.</p>
<p>I have actually been able to do both those things (add/remove properties and add dynamic type) but only separately not at the same time.</p>
<p>To implement the support to add and remove properties at runtime I used <a href="http://www.codeproject.com/KB/tabs/Dynamic_Propertygrid.aspx?msg=1027628" rel="noreferrer">this codeproject article</a> and modified the code a bit to support different types (not just strings).</p>
<pre><code>private System.Windows.Forms.PropertyGrid propertyGrid1;
private CustomClass myProperties = new CustomClass();
public Form1()
{
InitializeComponent();
myProperties.Add(new CustomProperty("Name", "Sven", typeof(string), false, true));
myProperties.Add(new CustomProperty("MyBool", "True", typeof(bool), false, true));
myProperties.Add(new CustomProperty("CaptionPosition", "Top", typeof(CaptionPosition), false, true));
myProperties.Add(new CustomProperty("Custom", "", typeof(StatesList), false, true)); //<-- doesn't work
}
/// <summary>
/// CustomClass (Which is binding to property grid)
/// </summary>
public class CustomClass: CollectionBase,ICustomTypeDescriptor
{
/// <summary>
/// Add CustomProperty to Collectionbase List
/// </summary>
/// <param name="Value"></param>
public void Add(CustomProperty Value)
{
base.List.Add(Value);
}
/// <summary>
/// Remove item from List
/// </summary>
/// <param name="Name"></param>
public void Remove(string Name)
{
foreach(CustomProperty prop in base.List)
{
if(prop.Name == Name)
{
base.List.Remove(prop);
return;
}
}
}
</code></pre>
<p>etc...</p>
<pre><code>public enum CaptionPosition
{
Top,
Left
}
</code></pre>
<p>My complete solution can be downloaded <a href="http://helgo.net/salle/misc/PropertyGrid_2005.zip" rel="noreferrer">here</a>.</p>
<p>It works fine when I add strings, bools or enums, but when I try to add a "dynamic type" like StatesList it doesn't work. Does anyone know why and can help me to solve it?</p>
<pre><code>public class StatesList : System.ComponentModel.StringConverter
{
private string[] _States = { "Alabama", "Alaska", "Arizona", "Arkansas" };
public override System.ComponentModel.TypeConverter.StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(_States);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
</code></pre>
<p>The method of using a TypeConverter works fine when you don't try to add the property at runtime, for example <a href="http://www.megasolutions.net/cSharp/PropertyGrid-dynamic-Dropdown-List-4124.aspx" rel="noreferrer">this code</a> works without any problem, but I want to be able to do both.</p>
<p>Please take a look at <a href="http://helgo.net/salle/misc/PropertyGrid_2005.zip" rel="noreferrer">my project</a>.
Thanks!</p>
| [
{
"answer_id": 314025,
"author": "salle55",
"author_id": 39636,
"author_profile": "https://Stackoverflow.com/users/39636",
"pm_score": 3,
"selected": false,
"text": "myProperties.Add(new CustomProperty(\"Custom\", \"\", typeof(States), false, true));\n\n[TypeConverter(typeof(StatesList))]\npublic class States\n{\n}\n"
},
{
"answer_id": 6926846,
"author": "Scott",
"author_id": 744014,
"author_profile": "https://Stackoverflow.com/users/744014",
"pm_score": 3,
"selected": false,
"text": " private List<string> lOptions;\n\n public CustomProperty(string sName, object value, Type tType, bool bReadOnly, bool bVisible, List<string> lOptions)\n {\n this.lOptions = lOptions;\n }\n\n public List<string> Options\n {\n get { return lOptions; }\n }\n public List<string> Options\n {\n get\n {\n return m_Property.Options;\n }\n }\n public override StandardValuesCollection\n GetStandardValues(ITypeDescriptorContext context)\n {\n CustomPropertyDescriptor descriptor = (CustomPropertyDescriptor)context.PropertyDescriptor;\n return new StandardValuesCollection(descriptor.Options);\n }\n List<string> optionsList = new List<string>(new string[] { \"test1\", \"test2\", \"test3\" }); \n CustomProperty myProperty = new CustomProperty(attr.Name, attr.Value, valueType, false, true, optionsList);\n"
},
{
"answer_id": 43627967,
"author": "Dizz Y",
"author_id": 7923852,
"author_profile": "https://Stackoverflow.com/users/7923852",
"pm_score": 0,
"selected": false,
"text": "[TypeConverter(typeof(StatesList))] // not work\npublic class States\n{\n}\n public override TypeConverter Converter\n{\n get {\n if (this.PropertyType.Equals(typeof(States)) ) {\n return new StatesList(); ; \n }\n return base.Converter;\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39636/"
] |
313,824 | <p>all! Typing from Italy
This little piece of code works if the matrix size is less then 800 and fails with a segmentation fault for higher sizes....
I have tried it with gcc 4.3.2 compiler in linux and macosx and VisualStudio compiler in windows.
Seemsthe problem is in the stack size..... how can I increase it ?
How can I solve the problem for bigger matrix sizes ?
The code works fine in serial put fails in parallel execution.
Thanks.</p>
<pre><code>#include <omp.h>
#include <stdio.h>
#define Nu 4000
int main() {
float A[Nu][Nu],B[Nu][Nu],C[Nu][Nu];
int i,j;
#pragma omp parallel
printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
#pragma omp parallel for private(j,i) shared(A,B,C) schedule(static)
for(j=0;j<Nu;j++){
for(i=0;i<Nu;i++){
//printf("Hello from thread %d, i,j %d %d\n", omp_get_thread_num(),i,j );
A[i][j]=0;
B[i][j]=0;
C[i][j]=0;
}}
}
</code></pre>
| [
{
"answer_id": 403341,
"author": "eyberg",
"author_id": 39110,
"author_profile": "https://Stackoverflow.com/users/39110",
"pm_score": 0,
"selected": false,
"text": "'ulimit -s newstacksize'"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
313,831 | <p>I'm trying to use powershell to configure the account credentials, but I need to grant the account "Log on as a service" right in order for it to work. How can I do this in powershell?</p>
| [
{
"answer_id": 21235462,
"author": "grenade",
"author_id": 68115,
"author_profile": "https://Stackoverflow.com/users/68115",
"pm_score": 5,
"selected": false,
"text": "<#\n.Synopsis\n Grant logon as a service right to the defined user.\n.Parameter computerName\n Defines the name of the computer where the user right should be granted.\n Default is the local computer on which the script is run.\n.Parameter username\n Defines the username under which the service should run.\n Use the form: domain\\username.\n Default is the user under which the script is run.\n.Example\n Usage:\n .\\GrantSeServiceLogonRight.ps1 -computerName hostname.domain.com -username \"domain\\username\"\n#>\nparam(\n [string] $computerName = (\"{0}.{1}\" -f $env:COMPUTERNAME.ToLower(), $env:USERDNSDOMAIN.ToLower()),\n [string] $username = (\"{0}\\{1}\" -f $env:USERDOMAIN, $env:USERNAME)\n)\nInvoke-Command -ComputerName $computerName -Script {\n param([string] $username)\n $tempPath = [System.IO.Path]::GetTempPath()\n $import = Join-Path -Path $tempPath -ChildPath \"import.inf\"\n if(Test-Path $import) { Remove-Item -Path $import -Force }\n $export = Join-Path -Path $tempPath -ChildPath \"export.inf\"\n if(Test-Path $export) { Remove-Item -Path $export -Force }\n $secedt = Join-Path -Path $tempPath -ChildPath \"secedt.sdb\"\n if(Test-Path $secedt) { Remove-Item -Path $secedt -Force }\n try {\n Write-Host (\"Granting SeServiceLogonRight to user account: {0} on host: {1}.\" -f $username, $computerName)\n $sid = ((New-Object System.Security.Principal.NTAccount($username)).Translate([System.Security.Principal.SecurityIdentifier])).Value\n secedit /export /cfg $export\n $sids = (Select-String $export -Pattern \"SeServiceLogonRight\").Line\n foreach ($line in @(\"[Unicode]\", \"Unicode=yes\", \"[System Access]\", \"[Event Audit]\", \"[Registry Values]\", \"[Version]\", \"signature=`\"`$CHICAGO$`\"\", \"Revision=1\", \"[Profile Description]\", \"Description=GrantLogOnAsAService security template\", \"[Privilege Rights]\", \"$sids,*$sid\")){\n Add-Content $import $line\n }\n secedit /import /db $secedt /cfg $import\n secedit /configure /db $secedt\n gpupdate /force\n Remove-Item -Path $import -Force\n Remove-Item -Path $export -Force\n Remove-Item -Path $secedt -Force\n } catch {\n Write-Host (\"Failed to grant SeServiceLogonRight to user account: {0} on host: {1}.\" -f $username, $computerName)\n $error[0]\n }\n} -ArgumentList $username\n"
},
{
"answer_id": 22155390,
"author": "Jupaol",
"author_id": 1268570,
"author_profile": "https://Stackoverflow.com/users/1268570",
"pm_score": 3,
"selected": false,
"text": "Import-Module -Name $Path_To_Carbon -Global -Prefix CA\n\n[array]$UserPrivileges = Get-CAPrivileges -Identity $UserName;\n[bool]$LogOnAsAServiceprivilegeFound = $false;\n\nif ($UserPrivileges.Length > 0)\n{\n if ($UserPrivileges -contains \"SeServiceLogonRight\")\n {\n $LogOnAsAServiceprivilegeFound = $true;\n }\n}\n\nif ($LogOnAsAServiceprivilegeFound -eq $false)\n{\n Grant-CAPrivilege -Identity $UserName \"SeServiceLogonRight\"\n}\n"
},
{
"answer_id": 56495995,
"author": "Luke",
"author_id": 4903228,
"author_profile": "https://Stackoverflow.com/users/4903228",
"pm_score": 3,
"selected": false,
"text": "#Requires -RunAsAdministrator\n\n#The SID you want to add\n$AccountSid = 'S-1-5-21-1234567890-1234567890-123456789-500'\n\n$ExportFile = 'c:\\temp\\CurrentConfig.inf'\n$SecDb = 'c:\\temp\\secedt.sdb'\n$ImportFile = 'c:\\temp\\NewConfig.inf'\n\n#Export the current configuration\nsecedit /export /cfg $ExportFile\n\n#Find the current list of SIDs having already this right\n$CurrentServiceLogonRight = Get-Content -Path $ExportFile |\n Where-Object -FilterScript {$PSItem -match 'SeServiceLogonRight'}\n\n#Create a new configuration file and add the new SID\n$FileContent = @'\n[Unicode]\nUnicode=yes\n[System Access]\n[Event Audit]\n[Registry Values]\n[Version]\nsignature=\"$CHICAGO$\"\nRevision=1\n[Profile Description]\nDescription=GrantLogOnAsAService security template\n[Privilege Rights]\n{0}*{1}\n'@ -f $(\n if($CurrentServiceLogonRight){\"$CurrentServiceLogonRight,\"}\n else{'SeServiceLogonRight = '}\n ), $AccountSid\n\nSet-Content -Path $ImportFile -Value $FileContent\n\n#Import the new configuration \nsecedit /import /db $SecDb /cfg $ImportFile\nsecedit /configure /db $SecDb\n"
},
{
"answer_id": 59002251,
"author": "Mariusz",
"author_id": 4028436,
"author_profile": "https://Stackoverflow.com/users/4028436",
"pm_score": 2,
"selected": false,
"text": "function setSecurityPolicy {\nParam\n(\n [Parameter(Mandatory=$true, Position=0)]\n [string] $username,\n [Parameter(Mandatory=$true, Position=1)]\n [string] $securityField\n)\n$sid;\nif($username -like \"*\\*\"){\n $user = $username.split('\\')\n $domain=$user[0]\n $usernametemp=$user[1]\n $sid=(get-wmiobject Win32_useraccount -filter \"name='$usernametemp' and Domain='$domain'\").SID\n} else {\n $sid=(get-wmiobject Win32_useraccount -filter \"name='$username' and Domain='$($env:COMPUTERNAME)'\").SID\n}\nif(-not($sid)){\n try{\n $sid= (Get-Localgroup \"$username\").SID.VALUE\n } catch{\n \n }\n}\n\nif(-not($sid)) {\n $Host.UI.WriteErrorLine(\"setSecurityPolicy error : Account $username not found!\")\n exit 1\n}\n$tmp = [System.IO.Path]::GetTempFileName()\nsecedit.exe /export /cfg \"$tmp\" | Out-Null\n\n$currentSetting = Select-String -Pattern \"$securityField = (.*)\" -path $tmp | select -Expand Matches | % { $_.Groups[1].Value }\nremove-item $tmp -Force\n\nif($currentSetting -notlike \"*$sid*\" ){\n Write-Host \"Modify Setting \"\"$securityField\"\"\"\n if( [string]::IsNullOrEmpty($currentSetting) ) {\n $currentSetting = \"*$sid\"\n } else {\n $currentSetting = \"*$sid,$currentSetting\"\n }\n $outfile = @\"\n[Unicode]\nUnicode=yes\n[Version]\nsignature=\"`$CHICAGO`$\"\nRevision=1\n[Privilege Rights]\n$securityField = $currentSetting\n\"@\n $tmp2 = [System.IO.Path]::GetTempFileName()\n Write-Host \"Import new settings to Local Security Policy\"\n $outfile | Set-Content -Path $tmp2 -Encoding Unicode -Force\n\n try {\n secedit.exe /configure /db \"secedit.sdb\" /cfg \"$tmp2\" /areas USER_RIGHTS \n } finally { \n remove-item $tmp2 -Force\n }\n}\n}\n#example usage\nsetSecurityPolicy -username 'IIS_IUSRS' -securityField 'SeServiceLogonRight'\nsetSecurityPolicy -username 'IIS_IUSRS' -securityField 'SeBatchLogonRight'\nsetSecurityPolicy -username 'IIS_IUSRS' -securityField 'SeImpersonatePrivilege'\n"
},
{
"answer_id": 59980653,
"author": "Brendan Lane",
"author_id": 2199093,
"author_profile": "https://Stackoverflow.com/users/2199093",
"pm_score": 3,
"selected": false,
"text": "AdvAPI32.dll Lsa* Add-Type @'\nusing System;\nusing System.Runtime.InteropServices;\n\npublic enum LSA_AccessPolicy : long\n{\n // Other values omitted for clarity\n POLICY_ALL_ACCESS = 0x00001FFFL\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct LSA_UNICODE_STRING\n{\n public UInt16 Length;\n public UInt16 MaximumLength;\n public IntPtr Buffer;\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct LSA_OBJECT_ATTRIBUTES\n{\n public UInt32 Length;\n public IntPtr RootDirectory;\n public LSA_UNICODE_STRING ObjectName;\n public UInt32 Attributes;\n public IntPtr SecurityDescriptor;\n public IntPtr SecurityQualityOfService;\n}\n\npublic static partial class AdvAPI32 {\n [DllImport(\"advapi32.dll\", SetLastError = true, PreserveSig = true)]\n public static extern uint LsaOpenPolicy(\n ref LSA_UNICODE_STRING SystemName,\n ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,\n uint DesiredAccess,\n out IntPtr PolicyHandle);\n\n [DllImport(\"advapi32.dll\")]\n public static extern Int32 LsaClose(IntPtr ObjectHandle);\n\n [DllImport(\"advapi32.dll\", SetLastError = true, PreserveSig = true)]\n public static extern uint LsaAddAccountRights(\n IntPtr PolicyHandle,\n byte[] AccountSid,\n LSA_UNICODE_STRING[] UserRights,\n uint CountOfRights);\n}\n'@\n function Get-LsaPolicyHandle() {\n $system = New-Object LSA_UNICODE_STRING\n $attrib = New-Object LSA_OBJECT_ATTRIBUTES -Property @{\n Length = 0\n RootDirectory = [System.IntPtr]::Zero\n Attributes = 0\n SecurityDescriptor = [System.IntPtr]::Zero\n SecurityQualityOfService = [System.IntPtr]::Zero\n };\n\n $handle = [System.IntPtr]::Zero\n\n $hr = [AdvAPI32]::LsaOpenPolicy([ref] $system, [ref]$attrib, [LSA_AccessPolicy]::POLICY_ALL_ACCESS, [ref]$handle)\n\n if (($hr -ne 0) -or ($handle -eq [System.IntPtr]::Zero)) {\n Write-Error \"Failed to open Local Security Authority policy. Error code: $hr\"\n } else {\n $handle\n }\n}\n function New-Right([string]$rightName){\n $unicodeCharSize = 2\n New-Object LSA_UNICODE_STRING -Property @{\n Buffer = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($rightName)\n Length = $rightName.Length * $unicodeCharSize\n MaximumLength = ($rightName.Length + 1) * $unicodeCharSize\n }\n}\n function Grant-Rights([System.IntPtr]$policyHandle, [byte[]]$sid, [LSA_UNICODE_STRING[]]$rights) {\n $result = [AdvAPI32]::LsaAddAccountRights($policyHandle, $sid, $rights, 1)\n if ($result -ne 0) {\n Write-Error \"Failed to grant right. Error code $result\"\n } \n}\n function Grant-LogonAsServiceRight([byte[]]$sid) { \n $logonAsServiceRightName = \"SeServiceLogonRight\"\n\n try {\n $policy = Get-LsaPolicyHandle\n $right = New-Right $logonAsServiceRightName\n Grant-Rights $policy $sid @($right)\n }\n finally {\n if($null -ne $policy){\n [AdvAPI32]::LsaClose($policy) | Out-Null\n }\n }\n}\n AdvAPI32 AdvAPI32"
},
{
"answer_id": 62529455,
"author": "Blue Clouds",
"author_id": 1501191,
"author_profile": "https://Stackoverflow.com/users/1501191",
"pm_score": -1,
"selected": false,
"text": ".\".\\Add Account To LogonAsService.ps1\" \"DOMAIN\\Account\"\n"
},
{
"answer_id": 65602397,
"author": "Justin",
"author_id": 3495322,
"author_profile": "https://Stackoverflow.com/users/3495322",
"pm_score": 1,
"selected": false,
"text": "function Get-SidForUser {\n param ([string]$UserName)\n $sid = ((New-Object System.Security.Principal.NTAccount($UserName)).Translate([System.Security.Principal.SecurityIdentifier]))\n [byte[]]$bytes = New-Object byte[] $sid.BinaryLength;\n $sid.GetBinaryForm($bytes, 0);\n return $bytes\n}\n Grant-LogonAsServiceRight (Get-SidForUser -UserName $ServiceAccount)\n"
},
{
"answer_id": 66251990,
"author": "Keith Banner",
"author_id": 4267686,
"author_profile": "https://Stackoverflow.com/users/4267686",
"pm_score": 3,
"selected": false,
"text": "function Add-RightToUser([string] $Username, $Right) {\n $tmp = New-TemporaryFile\n\n $TempConfigFile = \"$tmp.inf\"\n $TempDbFile = \"$tmp.sdb\"\n\n Write-Host \"Getting current policy\"\n secedit /export /cfg $TempConfigFile\n\n $sid = ((New-Object System.Security.Principal.NTAccount($Username)).Translate([System.Security.Principal.SecurityIdentifier])).Value\n\n $currentConfig = Get-Content -Encoding ascii $TempConfigFile\n\n $newConfig = $null\n\n if ($currentConfig | Select-String -Pattern \"^$Right = \") {\n if ($currentConfig | Select-String -Pattern \"^$Right .*$sid.*$\") {\n Write-Host \"Already has right\"\n }\n else {\n Write-Host \"Adding $Right to $Username\"\n\n $newConfig = $currentConfig -replace \"^$Right .+\", \"`$0,*$sid\"\n }\n }\n else {\n Write-Host \"Right $Right did not exist in config. Adding $Right to $Username.\"\n\n $newConfig = $currentConfig -replace \"^\\[Privilege Rights\\]$\", \"`$0`n$Right = *$sid\"\n }\n\n if ($newConfig) {\n Set-Content -Path $TempConfigFile -Encoding ascii -Value $newConfig\n\n Write-Host \"Validating configuration\"\n $validationResult = secedit /validate $TempConfigFile\n\n if ($validationResult | Select-String '.*invalid.*') {\n throw $validationResult;\n }\n else {\n Write-Host \"Validation Succeeded\"\n }\n\n Write-Host \"Importing new policy on temp database\"\n secedit /import /cfg $TempConfigFile /db $TempDbFile\n\n Write-Host \"Applying new policy to machine\"\n secedit /configure /db $TempDbFile /cfg $TempConfigFile\n\n Write-Host \"Updating policy\"\n gpupdate /force\n\n Remove-Item $tmp* -ea 0\n }\n}\n\n#Example\nAdd-RightToUser -Username 'MyDomain\\MyUser' -Right 'SeServiceLogonRight'\n function Remove-RightFromUser([string] $Username, $Right) {\n $tmp = New-TemporaryFile\n\n $TempConfigFile = \"$tmp.inf\"\n $TempDbFile = \"$tmp.sdb\"\n\n Write-Host \"Getting current policy\"\n secedit /export /cfg $TempConfigFile\n\n $sid = ((New-Object System.Security.Principal.NTAccount($Username)).Translate([System.Security.Principal.SecurityIdentifier])).Value\n\n $currentConfig = Get-Content -Encoding ascii $TempConfigFile\n\n if ($currentConfig | Select-String -Pattern \"^$Right .*$sid.*$\") {\n Write-Host \"Removing $Right from $Username\"\n\n $newConfig = $currentConfig -replace \"^($Right = .*?)(?>,\\*$sid(.*?$)|\\*$sid,(.*?$)|\\*$sid$)\", \"$1$2$3\"\n\n Set-Content -Path $TempConfigFile -Encoding ascii -Value $newConfig\n\n Write-Host \"Validating configuration\"\n $validationResult = secedit /validate $TempConfigFile\n\n if ($validationResult | Select-String '.*invalid.*') {\n throw $validationResult;\n }\n else {\n Write-Host \"Validation Succeeded\"\n }\n\n Write-Host \"Importing new policy on temp database\"\n secedit /import /cfg $TempConfigFile /db $TempDbFile\n\n Write-Host \"Applying new policy to machine\"\n secedit /configure /db $TempDbFile /cfg $TempConfigFile\n\n Write-Host \"Updating policy\"\n gpupdate /force\n\n Remove-Item $tmp* -ea 0\n }\n else {\n Write-Host \"User $Username did not have right\"\n }\n}\n\n#Example\nRemove-RightFromUser -Username 'MyDomain\\MyUser' -Right 'SeServiceLogonRight'\n"
},
{
"answer_id": 67010294,
"author": "Andrew Gale",
"author_id": 6684130,
"author_profile": "https://Stackoverflow.com/users/6684130",
"pm_score": 2,
"selected": false,
"text": "Install-Module -Name 'Carbon' -AllowClobber\nImport-Module 'Carbon'\n$Identity = \"<username>\"\n$privilege = \"SeServiceLogonRight\"\n$CarbonDllPath = \"C:\\Program Files\\WindowsPowerShell\\Modules\\Carbon\\2.10.2\\bin\\fullclr\\Carbon.dll\"\n[Reflection.Assembly]::LoadFile($CarbonDllPath)\n[Carbon.Security.Privilege]::GrantPrivileges($Identity, $privilege)\n"
},
{
"answer_id": 70675039,
"author": "Blake Drumm",
"author_id": 4876552,
"author_profile": "https://Stackoverflow.com/users/4876552",
"pm_score": 0,
"selected": false,
"text": "-UserRight -Add -Remove -ComputerName -UserName <#\n .Synopsis\n Add and Remove User Right(s) for defined user(s) and computer(s).\n \n .DESCRIPTION\n Add and Remove User Rights via Powershell.\n \n .PARAMETER AddRight\n You want to Add a user right.\n \n .Parameter ComputerName\n Defines the name of the computer where the user right should be granted. This can be multiple values, comma seperated.\n Default is the local computer on which the script is run.\n \n .PARAMETER RemoveRight\n You want to Remove a user right.\n \n .Parameter Username\n Defines the Username under which the service should run. This can be multiple values, comma seperated.\n Use the form: domain\\Username.\n Default is the user under which the script is run.\n \n .PARAMETER UserRight\n Defines the User Right you want to set. This can be multiple values, comma seperated.\n Name of the right you want to add to: SeServiceLogonRight\n There is no default for this argument\n \n Some (but not all) of the Options you can use:\n \"Log on as a batch job (SeBatchLogonRight)\"\n \"Allow log on locally (SeInteractiveLogonRight)\"\n \"Access this computer from the network (SeNetworkLogonRight)\"\n \"Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)\"\n \"Log on as a service (SeServiceLogonRight)\"\n \"Deny log on as a batch job (SeDenyBatchLogonRight)\"\n \"Deny log on locally (SeDenyInteractiveLogonRight)\"\n \"Deny access to this computer from the network (SeDenyNetworkLogonRight)\"\n \"Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)\"\n \"Deny log on as a service (SeDenyServiceLogonRight)\"\n \n .Example\n Usage:\n Single Users\n Add User Right \"Log on as a service\" for CONTOSO\\User:\n .\\Set-UserRights.ps1 -AddRight -Username CONTOSO\\User -UserRight SeServiceLogonRight\n \n Add User Right \"Log on as a batch job\" for CONTOSO\\User:\n .\\Set-UserRights.ps1 -AddRight -Username CONTOSO\\User -UserRight SeBatchLogonRight\n\n Remove User Right \"Log on as a batch job\" for CONTOSO\\User:\n .\\Set-UserRights.ps1 -RemoveRight -Username CONTOSO\\User -UserRight SeBatchLogonRight\n \n Add User Right \"Allow log on locally\" for current user:\n .\\Set-UserRights.ps1 -AddRight -UserRight SeInteractiveLogonRight\n\n Remove User Right \"Allow log on locally\" for current user:\n .\\Set-UserRights.ps1 -RemoveRight -UserRight SeInteractiveLogonRight\n \n Multiple Users / Services / Computers\n Add User Right \"Log on as a service\" and \"Log on as a batch job\" for CONTOSO\\User and run on, local machine and SQL.contoso.com:\n .\\Set-UserRights.ps1 -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\\User1, CONTOSO\\User2\n \n .Notes\n Original Creator: Bill Loytty (weloytty)\n Based on this script found here: https://github.com/weloytty/QuirkyPSFunctions/blob/ab4b02f9cc05505eee97d2f744f4c9c798143af1/Source/Users/Grant-LogOnAsService.ps1\n I modified to my own needs: https://github.com/blakedrumm/SCOM-Scripts-and-SQL/blob/master/Powershell/General%20Functions/Set-UserRights.ps1\n \n My blog post: https://blakedrumm.com/blog/set-and-check-user-rights-assignment/\n \n Author: Blake Drumm (blakedrumm@microsoft.com)\n First Created on: January 5th, 2022\n Last Modified on: April 23rd, 2022\n#>\nparam\n(\n [Parameter(Position = 0,\n HelpMessage = 'You want to Add a user right.')]\n [Alias('add')]\n [switch]$AddRight,\n [Parameter(Position = 1)]\n [Alias('computer')]\n [array]$ComputerName,\n [Parameter(Position = 2,\n HelpMessage = 'You want to Remove a user right.')]\n [switch]$RemoveRight,\n [Parameter(Position = 3)]\n [Alias('user')]\n [array]$Username,\n [Parameter(Mandatory = $false,\n Position = 4)]\n [ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]\n [Alias('right')]\n [array]$UserRight\n)\nBEGIN\n{\n \n Write-Output '==================================================================='\n Write-Output '========================== Start of Script ======================='\n Write-Output '==================================================================='\n \n $checkingpermission = \"Checking for elevated permissions...\"\n $scriptout += $checkingpermission\n Write-Output $checkingpermission\n if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] \"Administrator\"))\n {\n $currentPath = $myinvocation.mycommand.definition\n $nopermission = \"Insufficient permissions to run this script. Attempting to open the PowerShell script ($currentPath) as administrator.\"\n $scriptout += $nopermission\n Write-Warning $nopermission\n # We are not running \"as Administrator\" - so relaunch as administrator\n # ($MyInvocation.Line -split '\\.ps1[\\s\\''\\\"]\\s*', 2)[-1]\n Start-Process powershell.exe \"-File\", ('\"{0}\"' -f $MyInvocation.MyCommand.Path) -Verb RunAs\n break\n }\n else\n {\n $permissiongranted = \" Currently running as administrator - proceeding with script execution...\"\n Write-Output $permissiongranted\n }\n \n Function Time-Stamp\n {\n $TimeStamp = Get-Date -UFormat \"%B %d, %Y @ %r\"\n return \"$TimeStamp - \"\n }\n}\nPROCESS\n{\n function Inner-SetUserRights\n {\n param\n (\n [Parameter(Position = 0,\n HelpMessage = 'You want to Add a user right.')]\n [Alias('add')]\n [switch]$AddRight,\n [Parameter(Position = 1)]\n [Alias('computer')]\n [array]$ComputerName,\n [Parameter(Position = 2,\n HelpMessage = 'You want to Remove a user right.')]\n [switch]$RemoveRight,\n [Parameter(Position = 3)]\n [Alias('user')]\n [array]$Username,\n [Parameter(Mandatory = $false,\n Position = 4)]\n [Alias('right')]\n [array]$UserRight\n )\n if (!$UserRight)\n {\n Write-Warning \"Inner Function: Unable to continue because you did not supply the '-UserRight' parameter.\"\n break\n }\n if (!$AddRight -and !$RemoveRight)\n {\n Write-Warning \"Inner Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches.\"\n break\n }\n elseif ($AddRight -and $RemoveRight)\n {\n Write-Warning \"Inner Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove.\"\n break\n }\n elseif ($AddRight)\n {\n Write-Verbose \"Inner Function: Detected -AddRight switch in execution.\"\n $ActionType = 'Adding'\n }\n elseif ($RemoveRight)\n {\n Write-Verbose \"Inner Function: Detected -RemoveRight switch in execution.\"\n $ActionType = 'Removing'\n }\n else\n {\n Write-Warning \"Something is wrong, detected logic is broken before executing main function. Exiting.\"\n break\n }\n Function Time-Stamp\n {\n $TimeStamp = Get-Date -UFormat \"%B %d, %Y @ %r\"\n return \"$TimeStamp - \"\n }\n $tempPath = [System.IO.Path]::GetTempPath()\n $import = Join-Path -Path $tempPath -ChildPath \"import.inf\"\n if (Test-Path $import) { Remove-Item -Path $import -Force }\n $export = Join-Path -Path $tempPath -ChildPath \"export.inf\"\n if (Test-Path $export) { Remove-Item -Path $export -Force }\n $secedt = Join-Path -Path $tempPath -ChildPath \"secedt.sdb\"\n if (Test-Path $secedt) { Remove-Item -Path $secedt -Force }\n $Error.Clear()\n try\n {\n foreach ($right in $UserRight)\n {\n $UserLogonRight = switch ($right)\n {\n \"SeBatchLogonRight\" { \"Log on as a batch job (SeBatchLogonRight)\" }\n \"SeDenyBatchLogonRight\" { \"Deny log on as a batch job (SeDenyBatchLogonRight)\" }\n \"SeDenyInteractiveLogonRight\" { \"Deny log on locally (SeDenyInteractiveLogonRight)\" }\n \"SeDenyNetworkLogonRight\" { \"Deny access to this computer from the network (SeDenyNetworkLogonRight)\" }\n \"SeDenyRemoteInteractiveLogonRight\" { \"Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)\" }\n \"SeDenyServiceLogonRight\" { \"Deny log on as a service (SeDenyServiceLogonRight)\" }\n \"SeInteractiveLogonRight\" { \"Allow log on locally (SeInteractiveLogonRight)\" }\n \"SeNetworkLogonRight\" { \"Access this computer from the network (SeNetworkLogonRight)\" }\n \"SeRemoteInteractiveLogonRight\" { \"Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)\" }\n \"SeServiceLogonRight\" { \"Log on as a service (SeServiceLogonRight)\" }\n Default { \"($right)\" }\n }\n Write-Output (\"$(Time-Stamp)$ActionType `\"$UserLogonRight`\" right for user account: '$Username' on host: '$env:COMPUTERNAME'\")\n if ($Username -match \"^S-.*-.*-.*$|^S-.*-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*$\")\n {\n $sid = $Username\n }\n else\n {\n $sid = ((New-Object System.Security.Principal.NTAccount($Username)).Translate([System.Security.Principal.SecurityIdentifier])).Value\n }\n secedit /export /cfg $export | Out-Null\n #Change the below to any right you would like\n $sids = (Select-String $export -Pattern \"$right\").Line\n if ($ActionType -eq 'Adding')\n {\n $sidList = \"$sids,*$sid\"\n }\n elseif ($ActionType -eq 'Removing')\n {\n $sidList = \"$($sids.Replace(\"*$sid\", '').Replace(\"$Username\", '').Replace(\",,\", ',').Replace(\"= ,\", '= '))\"\n }\n foreach ($line in @(\"[Unicode]\", \"Unicode=yes\", \"[System Access]\", \"[Event Audit]\", \"[Registry Values]\", \"[Version]\", \"signature=`\"`$CHICAGO$`\"\", \"Revision=1\", \"[Profile Description]\", \"Description=$ActionType `\"$UserLogonRight`\" right for user account: $Username\", \"[Privilege Rights]\", \"$sidList\"))\n {\n Add-Content $import $line\n }\n }\n \n secedit /import /db $secedt /cfg $import | Out-Null\n secedit /configure /db $secedt | Out-Null\n gpupdate /force | Out-Null\n Write-Verbose \"The script will not delete the following paths due to running in verbose mode, please remove these files manually if needed:\"\n Write-Verbose \"`$import : $import\"\n Write-Verbose \"`$export : $export\"\n Write-Verbose \"`$secedt : $secedt\"\n \n if ($VerbosePreference.value__ -eq 0)\n {\n Remove-Item -Path $import -Force | Out-Null\n Remove-Item -Path $export -Force | Out-Null\n Remove-Item -Path $secedt -Force | Out-Null\n }\n }\n catch\n {\n Write-Output (\"$(Time-Stamp)Failure occurred while granting `\"$right`\" to user account: '$Username' on host: '$env:COMPUTERNAME'\")\n Write-Output \"Error Details: $error\"\n }\n }\n $InnerSetUserRightFunctionScript = \"function Inner-SetUserRights { ${function:Inner-SetUserRights} }\"\n function Set-UserRights\n {\n param\n (\n [Parameter(Position = 0,\n HelpMessage = 'You want to Add a user right.')]\n [Alias('add')]\n [switch]$AddRight,\n [Parameter(Position = 1)]\n [Alias('computer')]\n [array]$ComputerName,\n [Parameter(Position = 2,\n HelpMessage = 'You want to Remove a user right.')]\n [switch]$RemoveRight,\n [Parameter(Position = 3)]\n [Alias('user')]\n [array]$Username,\n [Parameter(Mandatory = $false,\n Position = 4)]\n [ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]\n [Alias('right')]\n [array]$UserRight\n )\n if (!$Username)\n {\n $Username = \"$env:USERDOMAIN`\\$env:USERNAME\"\n }\n if (!$UserRight)\n {\n Write-Warning \"Main Function: Unable to continue because you did not supply the '-UserRight' parameter.\"\n break\n }\n if (!$AddRight -and !$RemoveRight)\n {\n Write-Warning \"Main Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches.\"\n break\n }\n elseif ($AddRight -and $RemoveRight)\n {\n Write-Warning \"Main Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove.\"\n break\n }\n elseif ($AddRight)\n {\n Write-Verbose \"Main Function: Detected -AddRight switch in execution.\"\n $ActionType = 'Adding'\n }\n elseif ($RemoveRight)\n {\n Write-Verbose \"Main Function: Detected -RemoveRight switch in execution.\"\n $ActionType = 'Removing'\n }\n if (!$ComputerName)\n {\n $ComputerName = $env:ComputerName\n }\n foreach ($user in $Username)\n {\n foreach ($right in $UserRight)\n {\n foreach ($computer in $ComputerName)\n {\n if ($computer -match $env:COMPUTERNAME)\n {\n Inner-SetUserRights -UserRight $right -Username $user -AddRight:$AddRight -RemoveRight:$RemoveRight\n }\n else\n {\n Invoke-Command -ComputerName $Computer -Script {\n param ($script,\n [string]$Username,\n [Parameter(Mandatory = $true)]\n [array]$UserRight,\n $AddRight,\n $RemoveRight,\n $VerbosePreference)\n . ([ScriptBlock]::Create($script))\n $VerbosePreference = $VerbosePreference\n $Error.Clear()\n try\n {\n if ($VerbosePreference -eq 0)\n {\n Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight\n }\n else\n {\n Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight -Verbose\n }\n }\n catch\n {\n $info = [PSCustomObject]@{\n Exception = $Error.Exception.Message\n Reason = $Error.CategoryInfo.Reason\n Target = $Error.CategoryInfo.TargetName\n Script = $Error.InvocationInfo.ScriptName\n Line = $Error.InvocationInfo.ScriptLineNumber\n Column = $Error.InvocationInfo.OffsetInLine\n Date = Get-Date\n User = $env:username\n }\n Write-Warning \"$info\"\n }\n \n } -ArgumentList $InnerSetUserRightFunctionScript, $user, $right, $AddRight, $RemoveRight, $VerbosePreference\n }\n }\n }\n }\n \n }\n if ($ComputerName -or $Username -or $UserRight -or $RemoveRight)\n {\n foreach ($user in $Username)\n {\n Set-UserRights -ComputerName $ComputerName -Username $user -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight\n }\n }\n else\n {\n \n <# Edit line 392 to modify the default command run when this script is executed.\n Example: \n Set-UserRights -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\\User1, CONTOSO\\User2\n or\n Set-UserRights -AddRight -UserRight SeBatchLogonRight -Username S-1-5-11\n or\n Set-UserRights -RemoveRight -UserRight SeBatchLogonRight -Username CONTOSO\\User2\n or\n Set-UserRights -RemoveRight -UserRight SeServiceLogonRight, SeBatchLogonRight -Username CONTOSO\\User1\n #>\n Set-UserRights\n }\n}\nEND\n{\n Write-Output \"$(Time-Stamp)Script Completed!\"\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618/"
] |
313,839 | <p>I recently had a problem during the deployment of a windows service. Four computers did not cause any problems, but on the fifth any attempt to start the service failed due to an exception. The exception stack trace is written to the event log, so I though it should be easy to identify the cause:</p>
<pre><code>protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Starting service", EventLogEntryType.Information);
try
{
//...
base.OnStart(args);
}
catch (Exception ex)
{
EventLog.WriteEntry("Service can not start. Stack trace:" + ex.StackTrace, EventLogEntryType.Error);
Stop();
return;
}
EventLog.WriteEntry("Service started", EventLogEntryType.Information);
}
</code></pre>
<p>But alas, no information was ever written to the log. I finally traced it to the first log entry being written. It threw an exception because the application event log was full with recent entries, and configured to only overwrite entries older than 7 days.</p>
<p>What are the best practices on writing to the event log, considering that I can not change the configuration of the application event log? </p>
<p>Should I always put <code>EventLog.WriteEntry</code> in a try block, if yes, how should I handle the exception (writing it to the event log is probably a bad idea), should I check on the event log status in my <code>OnStart</code> method, or do you have any better suggestion?</p>
| [
{
"answer_id": 314118,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics.EventLog log = \n new System.Diagnostics.EventLog(\"YourLogNameHere\");\nlog.ModifyOverflowPolicy(\n System.Diagnostics.OverflowAction.OverwriteAsNeeded, 0);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
] |
313,848 | <p>I have a space delimited list of files names, where spaces in the file names are prefixed by '\'</p>
<p>e.g. "first\ file second\ file"</p>
<p>How can I get my regex to match each file name?</p>
| [
{
"answer_id": 313857,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 5,
"selected": true,
"text": "(\\\\ |[^ ])+\n"
},
{
"answer_id": 313872,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "(\\S|(?<=\\\\) )+\n \\S ?: (?:\\S|(?<=\\\\) )+\n"
},
{
"answer_id": 314048,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "/[^ \\\\]*(?:\\\\ [^\\\\ ]*)*/\n /\"[^\\\\\"]*(?:\\\\.[^\\\\\"]*)*\"/\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259/"
] |
313,859 | <p>Are there Windows API functions that allows reading what the current password policy is? For instance, minimum length, complexity etc.</p>
<p>If not reading, is there a way to verify a password against the policy programmatically?</p>
| [
{
"answer_id": 313907,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 4,
"selected": true,
"text": "Sub ListPasswordPolicyInfo( strDomain )\n Dim objComputer\n Set objComputer = GetObject(\"WinNT://\" & strDomain )\n WScript.Echo \"MinPasswordAge: \" & ((objComputer.MinPasswordAge) / 86400)\n WScript.Echo \"MinPasswordLength: \" & objComputer.MinPasswordLength\n WScript.Echo \"PasswordHistoryLength: \" & objComputer.PasswordHistoryLength\n WScript.Echo \"AutoUnlockInterval: \" & objComputer.AutoUnlockInterval\n WScript.Echo \"LockOutObservationInterval: \" & objComputer.LockOutObservationInterval\nEnd Sub\n\nDim strDomain\nDo\n strDomain = inputbox( \"Please enter a domainname\", \"Input\" )\nLoop until strDomain <> \"\"\n\nListPasswordPolicyInfo( strDomain )\n"
},
{
"answer_id": 10549823,
"author": "Nicholas Wilson",
"author_id": 314722,
"author_profile": "https://Stackoverflow.com/users/314722",
"pm_score": 2,
"selected": false,
"text": "NetValidatePasswordPolicy"
},
{
"answer_id": 31005363,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 1,
"selected": false,
"text": "NetValidatePasswordPolicy NetValidatePasswordPolicy NetUserModalsGet struct USER_MODALS_INFO_0\n{\n DWORD usrmod0_min_passwd_len;\n DWORD usrmod0_max_passwd_age;\n DWORD usrmod0_min_passwd_age\n DWORD usrmod0_force_logoff; \n DWORD usrmod0_password_hist_len;\n}\nPUSER_MODALS_INFO_0 = ^USER_MODALS_INFO_0; \n\nPUSER_MODALS_INFO_0 info0;\n\nNET_API_STATUS res = NetUserModalsGet(nil, 0, out info0);\n\nif (res <> NERR_Success)\n RaiseWin32Error(res);\ntry\n //Specifies the minimum allowable password length. \n //Valid values for this element are zero through PWLEN.\n Log(info0.usrmod0_min_passwd_len);\n\n //Specifies, in seconds, the maximum allowable password age. \n //A value of TIMEQ_FOREVER indicates that the password never expires. \n //The minimum valid value for this element is ONE_DAY. \n //The value specified must be greater than or equal to the value for the usrmod0_min_passwd_age member.\n Log(info0.usrmod0_max_passwd_age);\n\n //Specifies the minimum number of seconds that can elapse between the time\n //a password changes and when it can be changed again. \n //A value of zero indicates that no delay is required between password updates. \n //The value specified must be less than or equal to the value for the usrmod0_max_passwd_age member.\n Log(info0.usrmod0_min_passwd_age);\n\n //Specifies, in seconds, the amount of time between the end of the valid\n // logon time and the time when the user is forced to log off the network. \n //A value of TIMEQ_FOREVER indicates that the user is never forced to log off. \n //A value of zero indicates that the user will be forced to log off immediately when the valid logon time expires.\n Log(info0.usrmod0_force_logoff);\n\n //Specifies the length of password hi'+'story maintained. \n //A new password cannot match any of the previous usrmod0_password_hist_len passwords. \n //Valid values for this element are zero through DEF_MAX_PWHIST\n Log(info0.usrmod0_password_hist_len);\nfinally\n NetApiBufferFree(info0);\nend;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10644/"
] |
313,880 | <p>If you type</p>
<pre><code>nslookup -type=SRV _xmpp-server._tcp.gmail.com
</code></pre>
<p>(or use the dig command in OSX) you get some SRV records relating to google chat</p>
<p>I would like to replicate this functionality in PHP, does anyone have any good ideas how to do this?</p>
<p>I would like to avoid using exec() as this does not return 100% standard responses across OSX/*NIX/WINDOWS</p>
<p>Thanks!</p>
| [
{
"answer_id": 313898,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 4,
"selected": true,
"text": "require_once('Net/DNS.php');\n$resolver = new Net_DNS_Resolver();\n$response = $resolver->query('_xmpp-server._tcp.gmail.com', 'SRV');\nif ($response) {\n foreach ($response->answer as $rr) {\n $rr->display();\n }\n}\n"
},
{
"answer_id": 313901,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "dns_get_record() int $type DNS_SRV"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
313,882 | <p>After creating a instance of a class, can we invoke the constructor explicitly?
For example</p>
<pre><code>class A{
A(int a)
{
}
}
A instance;
instance.A(2);
</code></pre>
<p>Can we do this?</p>
| [
{
"answer_id": 313883,
"author": "Michael Platings",
"author_id": 2651243,
"author_profile": "https://Stackoverflow.com/users/2651243",
"pm_score": 5,
"selected": true,
"text": "new (&instance) A(2);\n A instance(2);\n"
},
{
"answer_id": 313906,
"author": "brofield",
"author_id": 31423,
"author_profile": "https://Stackoverflow.com/users/31423",
"pm_score": 3,
"selected": false,
"text": "class A{\n A(int a) { Set(a); }\n void Set(int a) { }\n}\n\nA instance;\n\ninstance.Set(2);\n"
},
{
"answer_id": 313974,
"author": "yesraaj",
"author_id": 22076,
"author_profile": "https://Stackoverflow.com/users/22076",
"pm_score": 2,
"selected": false,
"text": "Calling instance.A() or A(1) is seens as casting 'function-style cast' : illegal as right side of '.' operator\n class A{\n A(int a)\n { \n init(a);\n }\n\n void init(int a) { } \n }\n\n A instance;\n\n instance.init(2);\n"
},
{
"answer_id": 315052,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "init set instance.~A();\n placement new #include <iostream>\n\nstruct A {\n A(int a) { std::cerr << \"cons \" << a << std::endl; }\n ~A() { std::cerr << \"dest\" << std::endl; }\n};\n\nint main() {\n A instance(2);\n new (&instance) A(3);\n}\n cons 2\ncons 3\ndest\n A"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40236/"
] |
313,893 | <p>I need to get execution time in milliseconds.</p>
<blockquote>
<p>I originally asked this question back in 2008. The accepted answer then was to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>new Date().getTime()</code></a> However, we can all agree now that using the standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance.now" rel="noreferrer"><code>performance.now()</code></a> API is more appropriate. I am therefore changing the accepted answer to this one.</p>
</blockquote>
| [
{
"answer_id": 313903,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": false,
"text": "var start = new Date().getTime();\n\nfor (i = 0; i < 50000; ++i) {\n// do something\n}\n\nvar end = new Date().getTime();\nvar time = end - start;\nalert('Execution time: ' + time);\n"
},
{
"answer_id": 1975103,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 12,
"selected": true,
"text": "var startTime = performance.now()\n\ndoSomething() // <---- measured code goes between startTime and endTime\n \nvar endTime = performance.now()\n\nconsole.log(`Call to doSomething took ${endTime - startTime} milliseconds`)\n Node.js performance const { performance } = require('perf_hooks');\n console.time('doSomething')\n \ndoSomething() // <---- The function you're measuring time for \n \nconsole.timeEnd('doSomething')\n time() timeEnd() console.time()"
},
{
"answer_id": 15641427,
"author": "Pacerier",
"author_id": 632951,
"author_profile": "https://Stackoverflow.com/users/632951",
"pm_score": 9,
"selected": false,
"text": "performance.now() <script>\nvar a = performance.now();\nalert('do something...');\nvar b = performance.now();\nalert('It took ' + (b - a) + ' ms.');\n</script>\n console.time performance.now console.time Date Date now() Date"
},
{
"answer_id": 18039687,
"author": "Levi Roberts",
"author_id": 1251309,
"author_profile": "https://Stackoverflow.com/users/1251309",
"pm_score": 3,
"selected": false,
"text": "console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value\n var time = this._times[label];\n if (!time) {\n throw new Error('No such label: ' + label);\n }\n var duration = Date.now() - time;\n return duration;\n};\n console.time('someFunction timer');\n\nsomeFunction();\n\nvar executionTime = console.timeEndValue('someFunction timer');\nconsole.log(\"The execution time is \" + executionTime);\n"
},
{
"answer_id": 18133870,
"author": "kayz1",
"author_id": 1127843,
"author_profile": "https://Stackoverflow.com/users/1127843",
"pm_score": 4,
"selected": false,
"text": "var StopWatch = function (performance) {\n this.startTime = 0;\n this.stopTime = 0;\n this.running = false;\n this.performance = performance === false ? false : !!window.performance;\n};\n\nStopWatch.prototype.currentTime = function () {\n return this.performance ? window.performance.now() : new Date().getTime();\n};\n\nStopWatch.prototype.start = function () {\n this.startTime = this.currentTime();\n this.running = true;\n};\n\nStopWatch.prototype.stop = function () {\n this.stopTime = this.currentTime();\n this.running = false;\n};\n\nStopWatch.prototype.getElapsedMilliseconds = function () {\n if (this.running) {\n this.stopTime = this.currentTime();\n }\n\n return this.stopTime - this.startTime;\n};\n\nStopWatch.prototype.getElapsedSeconds = function () {\n return this.getElapsedMilliseconds() / 1000;\n};\n\nStopWatch.prototype.printElapsed = function (name) {\n var currentName = name || 'Elapsed:';\n\n console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');\n};\n var stopwatch = new StopWatch();\nstopwatch.start();\n\nfor (var index = 0; index < 100; index++) {\n stopwatch.printElapsed('Instance[' + index + ']');\n}\n\nstopwatch.stop();\n\nstopwatch.printElapsed();\n Instance[0] [0ms] [0s]\nInstance[1] [2.999999967869371ms] [0.002999999967869371s]\nInstance[2] [2.999999967869371ms] [0.002999999967869371s]\n/* ... */\nInstance[99] [10.999999998603016ms] [0.010999999998603016s]\nElapsed: [10.999999998603016ms] [0.010999999998603016s]\n"
},
{
"answer_id": 21121773,
"author": "NicJ",
"author_id": 43815,
"author_profile": "https://Stackoverflow.com/users/43815",
"pm_score": 6,
"selected": false,
"text": "console.time() console.timeEnd() console.time() console.timeEnd() console.time() time() timeEnd() function a() {\n console.time(\"mytimer\");\n ... do stuff ...\n var dur = console.timeEnd(\"myTimer\"); // NOTE: dur only works in FF\n}\n timeEnd() timeEnd() new Date().getTime() function a() {\n var start = new Date().getTime();\n ... do stuff ...\n var end = new Date().getTime();\n var dur = end - start;\n}\n Date window.performance.now() now() Date.getTime() now() now() Date.getTime() Date.getTime() now() now() new Date().getTime() + new Date Date.now() Date now() Date now() Date now() function a() {\n var start = window.performance.now();\n ... do stuff ...\n var end = window.performance.now();\n var dur = end - start;\n}\n now() console.time() console.timeEnd() now() mark(startMarkName) measure(measurename, startMarkname) function a() {\n window.performance.mark(\"start\");\n ... do stuff ...\n window.performance.measure(\"myfunctionduration\", \"start\");\n}\n\n// duration is window.performance.getEntriesByName(\"myfunctionduration\", \"measure\")[0];\n"
},
{
"answer_id": 22443184,
"author": "NlaakALD",
"author_id": 1998155,
"author_profile": "https://Stackoverflow.com/users/1998155",
"pm_score": -1,
"selected": false,
"text": "//=-=|Source|=-=//\n/**\n * JavaScript Timer Object\n *\n * var now=timer['elapsed'](); \n * timer['stop']();\n * timer['start']();\n * timer['reset']();\n * \n * @expose\n * @method timer\n * @return {number}\n */\ntimer=function(){\n var a=Date.now();\n b=0;\n return{\n /** @expose */\n elapsed:function(){return b=Date.now()-a},\n start:function(){return a=Date.now()},\n stop:function(){return Date.now()},\n reset:function(){return a=0}\n }\n}();\n\n//=-=|Google Advanced Optimized|=-=//\ntimer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();\n"
},
{
"answer_id": 25911175,
"author": "Mx.",
"author_id": 1540688,
"author_profile": "https://Stackoverflow.com/users/1540688",
"pm_score": 3,
"selected": false,
"text": "console.time performance.now End() Performance: {\n Timer: {},\n Start: function (name) {\n if (console && console.time) {\n console.time(name);\n } else if (window.performance.now) {\n this.Timer[name] = window.performance.now();\n } else {\n this.Timer[name] = new Date().getTime();\n }\n },\n End: function (name) {\n if (console && console.time) {\n console.timeEnd(name);\n } else {\n var result;\n if (window.performance.now) {\n result = window.performance.now() - this.Timer[name];\n } else {\n result = new Date().getTime() - this.Timer[name];\n }\n console.log(name + \": \" + result);\n }\n }\n}\n"
},
{
"answer_id": 28303392,
"author": "Mirza Selimovic",
"author_id": 2520519,
"author_profile": "https://Stackoverflow.com/users/2520519",
"pm_score": -1,
"selected": false,
"text": "var start = new Date().getTime();\n\nfor (i = 0; i < 50000; ++i) {\n// JavaScript is not waiting until the for is finished !!\n}\n\nvar end = new Date().getTime();\nvar time = end - start;\nalert('Execution time: ' + time); \n var start = new Date().getTime();\n\nfor (i = 0; i < 50000; ++i) {\n $.ajax({\n url: 'www.oneOfYourWebsites.com',\n success: function(){\n console.log(\"success\");\n }\n });\n}\n\nvar end = new Date().getTime();\nvar time = end - start;\nalert('Execution time: ' + time); \n"
},
{
"answer_id": 28747321,
"author": "Varvara Kalinina",
"author_id": 2611340,
"author_profile": "https://Stackoverflow.com/users/2611340",
"pm_score": 5,
"selected": false,
"text": "var performance = window.performance;\nvar t0 = performance.now();\ndoWork();\nvar t1 = performance.now();\nconsole.log(\"Call to doWork took \" + (t1 - t0) + \" milliseconds.\")\n Date.getTime() console.time()"
},
{
"answer_id": 28983214,
"author": "Achim Koellner",
"author_id": 1423747,
"author_profile": "https://Stackoverflow.com/users/1423747",
"pm_score": 4,
"selected": false,
"text": "let hrTime = process.hrtime()\nconsole.log(hrTime[0] * 1000000 + hrTime[1] / 1000)\n"
},
{
"answer_id": 34358928,
"author": "Andrew Marin",
"author_id": 4249254,
"author_profile": "https://Stackoverflow.com/users/4249254",
"pm_score": 2,
"selected": false,
"text": "var t0 = process.hrtime();\n//Start of code to measure\n\n//End of code\nvar timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds\n console.log var timeInMilliseconds = process.hrtime(t0)[1]/1000000; var t0 = process.hrtime();\nsomeAsyncFunction(function(err, results) {\nvar timeInMilliseconds = process.hrtime(t0)[1]/1000000;\n\n});\n"
},
{
"answer_id": 43183130,
"author": "aljgom",
"author_id": 3577695,
"author_profile": "https://Stackoverflow.com/users/3577695",
"pm_score": 3,
"selected": false,
"text": "function timer(lap){ \n if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`); \n timer.prev = performance.now();\n}\n console.time() timer() // set the start\n// do something \ntimer('built') // logs 'built in: 591.815ms'\n// do something\ntimer('copied') // logs 'copied in: 0.065ms'\n// do something\ntimer('compared') // logs 'compared in: 36.41ms'\n console.time() console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');\n"
},
{
"answer_id": 49314887,
"author": "Wajeeh Aslam",
"author_id": 9350033,
"author_profile": "https://Stackoverflow.com/users/9350033",
"pm_score": 3,
"selected": false,
"text": "var t0 = date.now();\ndoSomething();\nvar t1 = date.now();\nconsole.log(\"Call to doSomething took approximate\" + (t1 - t0)/1000 + \" seconds.\")"
},
{
"answer_id": 49348569,
"author": "Jonathan Chasteen",
"author_id": 9129222,
"author_profile": "https://Stackoverflow.com/users/9129222",
"pm_score": 3,
"selected": false,
"text": "function functionTimer() {\n performance.mark('start')\n functionToBeTimed()\n performance.mark('end')\n performance.measure('Start to End', 'start', 'end')\n const measure = performance.getEntriesByName('Start to End')[0]\n console.log(measure.duration)\n}\n performance \nconst { performance } = require('perf_hooks')\n"
},
{
"answer_id": 51135660,
"author": "Alok Deshwal",
"author_id": 5467132,
"author_profile": "https://Stackoverflow.com/users/5467132",
"pm_score": 4,
"selected": false,
"text": " var start = +new Date();\n callYourFunctionHere();\n var end = +new Date();\n var time = end - start;\n console.log('total execution time = '+ time + 'ms');\n"
},
{
"answer_id": 51842869,
"author": "jose920405",
"author_id": 2907751,
"author_profile": "https://Stackoverflow.com/users/2907751",
"pm_score": 1,
"selected": false,
"text": "export default class Singleton {\n\n static myInstance: Singleton = null;\n\n _timers: any = {};\n\n /**\n * @returns {Singleton}\n */\n static getInstance() {\n if (Singleton.myInstance == null) {\n Singleton.myInstance = new Singleton();\n }\n\n return this.myInstance;\n }\n\n initTime(label: string) {\n this._timers[label] = Date.now();\n return this._timers[label];\n }\n\n endTime(label: string) {\n const endTime = Date.now();\n if (this._timers[label]) {\n const delta = endTime - this._timers[label];\n const finalTime = `${label}: ${delta}ms`;\n delete this._timers[label];\n return finalTime;\n } else {\n return null;\n }\n }\n}\n string return Singleton.getInstance().initTime(label); // Returns the time init return Singleton.getInstance().endTime(label); // Returns the total time between init and end"
},
{
"answer_id": 52286301,
"author": "aljgom",
"author_id": 3577695,
"author_profile": "https://Stackoverflow.com/users/3577695",
"pm_score": 4,
"selected": false,
"text": "let test = () => { /* does something */ }\ntest = timed(test) // turns the function into a timed function in one line\ntest() // run your code as normal, logs 'function test took 1001.900ms' \n let timed = (f) => (...args) => {\n let start = performance.now();\n let ret = f(...args);\n console.log(`function ${f.name} took ${(performance.now() - start).toFixed(3)}ms`);\n return ret; \n}\n timed await"
},
{
"answer_id": 52571943,
"author": "Yu Huang",
"author_id": 4306662,
"author_profile": "https://Stackoverflow.com/users/4306662",
"pm_score": 1,
"selected": false,
"text": "function timer() {\n return (target, propertyKey, descriptor) => {\n const start = Date.now();\n let oldFunc = descriptor.value;\n\n descriptor.value = async function (){\n var result = await oldFunc.apply(this, arguments);\n console.log(Date.now() - start);\n return result;\n }\n }\n}\n\n// Util function \nfunction delay(timeout) {\n return new Promise((resolve) => setTimeout(() => {\n resolve();\n }, timeout));\n}\n\nclass Test {\n @timer()\n async test(timout) {\n await delay(timout)\n console.log(\"delay 1\");\n await delay(timout)\n console.log(\"delay 2\");\n }\n}\n\nconst t = new Test();\nt.test(1000)\nt.test(100)\n {\n \"plugins\": [\n \"transform-decorators-legacy\"\n ]\n }\n"
},
{
"answer_id": 54411682,
"author": "gombosg",
"author_id": 8677156,
"author_profile": "https://Stackoverflow.com/users/8677156",
"pm_score": 2,
"selected": false,
"text": "Performance stopwatch.js const perf = typeof performance !== \"undefined\" ? performance : require('perf_hooks').performance;\nconst DIGITS = 2;\n\nlet _timers = {};\n\nconst _log = (label, delta?) => {\n if (_timers[label]) {\n console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +\n `${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);\n }\n};\n\nexport const Stopwatch = {\n start(label) {\n const now = perf.now();\n if (_timers[label]) {\n if (!_timers[label].started) {\n _timers[label].started = now;\n }\n } else {\n _timers[label] = {\n started: now,\n total: 0,\n cycles: 0\n };\n }\n },\n /** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */\n stop(label, log = false) {\n const now = perf.now();\n if (_timers[label]) {\n let delta;\n if(_timers[label].started) {\n delta = now - _timers[label].started;\n _timers[label].started = null;\n _timers[label].total += delta;\n _timers[label].cycles++;\n }\n log && _log(label, delta);\n return _timers[label].total;\n } else {\n return null;\n }\n },\n /** Logs total time */\n log: _log,\n delete(label) {\n delete _timers[label];\n }\n};\n"
},
{
"answer_id": 54474622,
"author": "user1032559",
"author_id": 1032559,
"author_profile": "https://Stackoverflow.com/users/1032559",
"pm_score": 4,
"selected": false,
"text": "var timer = -performance.now();\n\n// Do something\n\ntimer += performance.now();\nconsole.log(\"Time: \" + (timer/1000).toFixed(5) + \" sec.\")\n timer/1000 .toFixed(5)"
},
{
"answer_id": 55807916,
"author": "Rohit Jaiswal",
"author_id": 11397980,
"author_profile": "https://Stackoverflow.com/users/11397980",
"pm_score": 3,
"selected": false,
"text": "console.time('function');\n//run the function in between these two lines for that you need to \n//measure time taken by the function. (\"ex. function();\")\nconsole.timeEnd('function');\n var v1 = performance.now();\n//run the function here for which you have top measure the time \nvar v2 = performance.now();\nconsole.log(\"total time taken = \"+(v2-v1)+\"milliseconds\");\n var h2 = +new Date(); //or\nvar h2 = new Date().getTime();\nfor(i=0;i<500;i++) { /* do something */}\nvar h3 = +new Date(); //or \nvar h3 = new Date().getTime();\nvar timeTaken = h3-h2;\nconsole.log(\"time ====\", timeTaken);\n getTime()"
},
{
"answer_id": 56010922,
"author": "toonday",
"author_id": 6054358,
"author_profile": "https://Stackoverflow.com/users/6054358",
"pm_score": 2,
"selected": false,
"text": "performance hooks mark measure duration const { performance, PerformanceObserver } = require('perf_hooks');\n\nconst measures = []\n\nconst obs = new PerformanceObserver(list => measures.push(...list.getEntries()));\nobs.observe({ entryTypes: ['measure'] });\nconst getEntriesByType = cb => cb(measures);\n\nconst doSomething = val => {\n performance.mark('beginning of the process');\n\n val *= 2;\n\n performance.mark('after multiplication');\n\n performance.measure('time taken', 'beginning of the process', 'after multiplication');\n\n getEntriesByType(entries => {\n entries.forEach(entry => console.log(entry));\n })\n\n return val;\n}\n\ndoSomething(4);\n"
},
{
"answer_id": 56870264,
"author": "iCPSoni",
"author_id": 10012101,
"author_profile": "https://Stackoverflow.com/users/10012101",
"pm_score": 2,
"selected": false,
"text": "var time0 = performance.now(); // Store the time at this point into time0\n\nyourFunction(); // The function you're measuring time for \n\nvar time1 = performance.now(); // Store the time at this point into time1\n\nconsole.log(\"youFunction took \" + (time1 - time0) + \" milliseconds to execute\");\n console.time('someFunction');\n\nsomeFunction(); // Whatever is timed goes between the two \"console.time\"\n\nconsole.timeEnd('someFunction');\n"
},
{
"answer_id": 58904687,
"author": "bvdb",
"author_id": 1833961,
"author_profile": "https://Stackoverflow.com/users/1833961",
"pm_score": 1,
"selected": false,
"text": "console.time(\"myTimer\"); console.timeLog(\"myTimer\"); console.timeEnd(\"myTimer\");"
},
{
"answer_id": 68604931,
"author": "aryan singh",
"author_id": 7579299,
"author_profile": "https://Stackoverflow.com/users/7579299",
"pm_score": 2,
"selected": false,
"text": "console.time('some label here') console.timeEnd('some label here')"
},
{
"answer_id": 69985146,
"author": "Vijay",
"author_id": 14475036,
"author_profile": "https://Stackoverflow.com/users/14475036",
"pm_score": 3,
"selected": false,
"text": "const startTime =new Date().getTime();\n\n//do something \nconst endTime = new Date().getTime();\nconsole.log(`time taken ${(endTime - startTime)/1000} seconds`);\n"
},
{
"answer_id": 71058675,
"author": "User_coder",
"author_id": 2021554,
"author_profile": "https://Stackoverflow.com/users/2021554",
"pm_score": 0,
"selected": false,
"text": "start('something') stop('something') /**\n * Mark entries\n */\nexport const marks: { [id: string]: number } = {};\n\n/**\n * Start timing \n */\nexport const start = (id: string) => {\n return Object.assign(marks, {[id]: Date.now() })[id]\n}\n\n/**\n * Clear all \n */\nexport const clear = () => {\n for (const id in marks) delete marks[id]; \n};\n\n/**\n * Stop timing and return formatted elapsed time\n */\nexport const stop = (id: string) => {\n const ms = Date.now() - marks[id];\n delete marks[id];\n return ms > 1000 \n ? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms` \n : `${ms.toFixed(0)}ms`;\n};\n\n as import * as time from './timer.js'\n\ntime.start('foo')\n\n// do something\n\nconsole.log('elapsed time: ' + time.stop('bar'))\n"
},
{
"answer_id": 74329995,
"author": "Rajaruban Rajindram",
"author_id": 16935706,
"author_profile": "https://Stackoverflow.com/users/16935706",
"pm_score": 1,
"selected": false,
"text": " // Create one-liner timer function\n let [timer, timingMonitor] = [0, () => timer = !timer ? Date.now() : `${Date.now() - timer}ms`]\n \n // Initiate timer\n timingMonitor();\n \n // Your code here\n doSomething();\n \n // Capture and store the End timer \n const timeElapsed = timingMonitor();\n\n console.log(timeElapsed);\n // Console output: \"102ms\", for example \n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
313,900 | <p>Using ICU 4.0 regex library, I find that the following regex is exhibiting exponential time:</p>
<pre><code>actual: "[^<]*<\?"
C code: "[^<]*<\\?"
</code></pre>
<p>Aim: find "<?" where there is no other "<" before it</p>
<p>When running this regex on plain text with no "<" characters at all it appears to take exponential time. If the text has at least a single "<" then it is quick. I don't understand why. </p>
<p>Shouldn't the required match on "<?" prevent this from needing to backtrack? I would have thought that it would try to find the first "<" and then test the rest of the expression. If it can't find a "<" then it would give up because the pattern obviously can't match.</p>
<p>Is this a bug in the ICU regex or is it expected?</p>
| [
{
"answer_id": 313925,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "<?"
},
{
"answer_id": 313939,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": true,
"text": "\"^[^<]*<\\?\""
},
{
"answer_id": 314003,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 2,
"selected": false,
"text": "String regex = \"[^<]*+<\\\\?\";\n String regex = \"(?>[^<]*)<\\\\?\";\n [^<]*"
},
{
"answer_id": 314973,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "perl -Mre=debug -e' \"abcdefghijklm\" =~ /[^<]*<[?]/; '\n\nCompiling REx \"[^<]*<[?]\"\nFinal program:\n 1: STAR (13)\n 2: ANYOF[\\0-;=-\\377{unicode_all}] (0)\n 13: EXACT <<?> (17)\n 17: END (0)\nfloating \"<?\" at 0..2147483647 (checking floating) minlen 2 \nGuessing start of match in sv for REx \"[^<]*<[?]\" against \"abcdefghijklm\"\nDid not find floating substr \"<?\"...\nMatch rejected by optimizer\nFreeing REx: \"[^<]*<[?]\"\n perl -Mre=debug -e' \"ab<?\" =~ /[^<]*(?!<)<[?]/; '\n\nCompiling REx \"[^<]*(?!<)<[?]\"\nFinal program:\n 1: STAR (13)\n 2: ANYOF[\\0-;=-\\377{unicode_all}] (0)\n 13: UNLESSM[0] (19)\n 15: EXACT <<> (17)\n 17: SUCCEED (0)\n 18: TAIL (19)\n 19: EXACT <<?> (23)\n 23: END (0)\nfloating \"<?\" at 0..2147483647 (checking floating) minlen 2 \nGuessing start of match in sv for REx \"[^<]*(?!<)<[?]\" against \"ab<?\"\nFound floating substr \"<?\" at offset 2...\nGuessed: match at offset 0\nMatching REx \"[^<]*(?!<)<[?]\" against \"ab<?\"\n\n# Start at first pos()\n# |\n# V\n 0 <> <ab<?> | 1:STAR(13)\n ANYOF[\\0-;=-\\377{unicode_all}] can match 2 times out of 2147483647...\n 2 <ab> <<?> | 13: UNLESSM[0](19)\n 2 <ab> <<?> | 15: EXACT <<>(17)\n 3 <ab<> <?> | 17: SUCCEED(0)\n subpattern success...\n failed...\n# try with one fewer [^<]*\n 1 <a> <b<?> | 13: UNLESSM[0](19)\n 1 <a> <b<?> | 15: EXACT <<>(17)\n failed...\n# try with one fewer [^<]* again\n 1 <a> <b<?> | 19: EXACT <<?>(23)\n failed...\n# try with zero [^<]*\n 0 <> <ab<?> | 13: UNLESSM[0](19)\n 0 <> <ab<?> | 15: EXACT <<>(17)\n failed...\n 0 <> <ab<?> | 19: EXACT <<?>(23)\n failed...\n failed...\n\n# Start at second pos()\n# |\n# V\n 1 <a> <b<?> | 1:STAR(13)\n ANYOF[\\0-;=-\\377{unicode_all}] can match 1 times out of 2147483647...\n 2 <ab> <<?> | 13: UNLESSM[0](19)\n 2 <ab> <<?> | 15: EXACT <<>(17)\n 3 <ab<> <?> | 17: SUCCEED(0)\n subpattern success...\n failed...\n 1 <a> <b<?> | 13: UNLESSM[0](19)\n 1 <a> <b<?> | 15: EXACT <<>(17)\n failed...\n 1 <a> <b<?> | 19: EXACT <<?>(23)\n failed...\n failed...\n\n# Start at third and final pos()\n# |\n# V\n 2 <ab> <<?> | 1:STAR(13)\n ANYOF[\\0-;=-\\377{unicode_all}] can match 0 times out of 2147483647...\n 2 <ab> <<?> | 13: UNLESSM[0](19)\n 2 <ab> <<?> | 15: EXACT <<>(17)\n 3 <ab<> <?> | 17: SUCCEED(0)\n subpattern success...\n failed...\n failed...\nMatch failed\nFreeing REx: \"[^<]*(?!<)<[?]\"\n '[^<]*' '<?' ^ perl -Mre=debug -e' \"abcdefghijklm<?\" =~ /^[^<]*+(?!<)<[?]/; '\n\nCompiling REx \"^[^<]*+(?!<)<[?]\"\nFinal program:\n 1: BOL (2)\n 2: SUSPEND (18)\n 4: STAR (16)\n 5: ANYOF[\\0-;=-\\377{unicode_all}] (0)\n 16: SUCCEED (0)\n 17: TAIL (18)\n 18: UNLESSM[0] (24)\n 20: EXACT <<> (22)\n 22: SUCCEED (0)\n 23: TAIL (24)\n 24: EXACT <<?> (28)\n 28: END (0)\nfloating \"<?\" at 0..2147483647 (checking floating) anchored(BOL) minlen 2 \nGuessing start of match in sv for REx \"^[^<]*+(?!<)<[?]\" against \"abcdefghijklm<?\"\nFound floating substr \"<?\" at offset 13...\nGuessed: match at offset 0\nMatching REx \"^[^<]*+(?!<)<[?]\" against \"abcdefghijklm<?\"\n 0 <> <abcdefghij> | 1:BOL(2)\n 0 <> <abcdefghij> | 2:SUSPEND(18)\n 0 <> <abcdefghij> | 4: STAR(16)\n ANYOF[\\0-;=-\\377{unicode_all}] can match 13 times out of 2147483647...\n 13 <defghijklm> <<?> | 16: SUCCEED(0)\n subpattern success...\n 13 <defghijklm> <<?> | 18:UNLESSM[0](24)\n 13 <defghijklm> <<?> | 20: EXACT <<>(22)\n 14 <defghijklm<> <?> | 22: SUCCEED(0)\n subpattern success...\n failed...\nMatch failed\nFreeing REx: \"^[^<]*+(?!<)<[?]\"\n"
},
{
"answer_id": 355124,
"author": "user44511",
"author_id": 44511,
"author_profile": "https://Stackoverflow.com/users/44511",
"pm_score": 0,
"selected": false,
"text": "s '<' [^<]* s[0] s[n-1] s '<' [^<]* s[0] s[n-2] '<' * s[1] <? < <<? <? ba<abc<?def abc<? ^[^<]*<\\?"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31423/"
] |
313,910 | <p>At the moment, I have some functions which look like this:</p>
<pre><code>private bool inFunction1 = false;
public void function1()
{
if (inFunction1) return;
inFunction1 = true;
// do stuff which might cause function1 to get called
...
inFunction1 = false;
}
</code></pre>
<p>I'd like to be able to declare them like this:</p>
<pre><code>[NoReEntry]
public void function1()
{
// do stuff which might cause function1 to get called
...
}
</code></pre>
<p>Is there an attribute I can add to a function to prevent reentry? If not, how would I go about making one? I've heard about AOP attributes that can be used to add code before and after function calls; would they be suitable?</p>
| [
{
"answer_id": 313923,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 1,
"selected": false,
"text": "if (inFunction1) \n return;\n\ntry\n{\n inFunction1 = true;\n\n // do stuff which might cause function1 to get called\n ...\n}\nfinally \n{\n inFunction1 = false;\n}\n"
},
{
"answer_id": 313934,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": "private volatile bool inFunction1 = false;\n"
},
{
"answer_id": 313943,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "static Func<TArg,T> WrapAgainstReentry<TArg,T>(Func<TArg,T> code, Func<TArg,T> onReentry)\n{\n bool entered = false;\n return x =>\n {\n if (entered)\n return onReentry(x);\n entered = true;\n try\n {\n return code(x);\n }\n finally\n {\n entered = false;\n }\n };\n}\n"
},
{
"answer_id": 313965,
"author": "Sean",
"author_id": 26095,
"author_profile": "https://Stackoverflow.com/users/26095",
"pm_score": 4,
"selected": false,
"text": "long m_InFunction=0;\n\nif(Interlocked.CompareExchange(ref m_InFunction,1,0)==0)\n{\n // We're not in the function\n try\n {\n }\n finally\n {\n m_InFunction=0;\n }\n}\nelse\n{\n // We're already in the function\n}\n"
},
{
"answer_id": 314376,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 2,
"selected": false,
"text": " [MethodImpl(MethodImplOptions.NoInlining)]\n private static bool IsReEntry() {\n StackTrace stack = new StackTrace();\n StackFrame[] frames = stack.GetFrames();\n\n if (frames.Length < 2)\n return false;\n\n string currentMethod = frames[1].GetMethod().Name;\n\n for (int i = 2; i < frames.Length; i++) {\n if (frames[i].GetMethod().Name == currentMethod) {\n return true;\n }\n }\n\n return false;\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
313,916 | <p>I have a Java Swing application, developed on Mac OS X 10.5 using Java 1.5.</p>
<p>I'm trying to make a custom cursor appear when the user moves the mouse over some text in a dialog. The cursor never changes, though. </p>
<p>When I don't use a JFrame instead of a JDialog, the cursor does change. But then I'll have to write all the dialog code myself.</p>
<p>How can I get the cursor to appear?</p>
<p>Here's the simplest code I could create to demonstrate the problem:</p>
<pre><code>import javax.swing.*;
import java.awt.*;
public class CursorTest {
public static void main(String[] args) {
JLabel label = new JLabel("Move mouse here for hand cursor");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JOptionPane pane = new JOptionPane(label);
pane.setOptions(new Object[]{"OK"});
JDialog dialog = pane.createDialog(null, "Test Dialog");
dialog.setVisible(true);
}
}
</code></pre>
| [
{
"answer_id": 313985,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "public class CursorTest extends JFrame\n{\n private CursorTest()\n {\n }\n\n private void ShowDialog()\n {\n JLabel label = new JLabel(\"Move mouse here for hand cursor\");\n label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));\n JOptionPane pane = new JOptionPane(label);\n pane.setOptions(new Object[] { \"OK\" } );\n\n JDialog dialog = pane.createDialog(this, \"Test Dialog\");\n dialog.setVisible(true);\n }\n\n public static void main(String[] args)\n {\n SwingUtilities.invokeLater(new Runnable()\n {\n public void run()\n {\n CursorTest testFrame = new CursorTest();\n testFrame.setTitle(\"Test GUI\");\n testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n testFrame.setSize(500, 300);\n testFrame.setVisible(true);\n testFrame.ShowDialog();\n }\n });\n }\n}\n"
},
{
"answer_id": 314005,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 2,
"selected": false,
"text": "import javax.swing.*;\nimport java.awt.*;\n\npublic class CursorTest {\n\n public static void main(String[] args) {\n JLabel label = new JLabel(\"Move mouse here for hand cursor\");\n label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));\n JOptionPane pane = new JOptionPane(label);\n pane.setOptions(new Object[]{\"OK\"});\n\n JFrame parent = new JFrame();\n parent.setVisible(true);\n JDialog dialog = pane.createDialog(parent, \"Test Dialog\");\n dialog.setModal(false);\n dialog.setVisible(true);\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
] |
313,917 | <p>I've got a 1-based array of four items which I need to traverse. For a given index in the array, I need to work out the index of the next item, and the index of the previous item. This sounds simple but the array needs to wrap around. So when you are at the beginning of the array, the previous item is considered to be the last item. Likewise, if you are at the end of the array, the next item is considered to be the first item.</p>
<p>I realise this can be solved by using conditional statements, but I wondered if it was possible to do it using mathematical equations. I've got one that works nicely for the next item</p>
<pre><code>NextItem = Modulus(CurrentItem, 4) + 1
</code></pre>
<p>(the modulus function returns the remainder of one number divided by another).</p>
<p>Has anyone got any ideas as to how I can work out the previous item?</p>
| [
{
"answer_id": 313928,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "CurrentItem - 1 PrevItem = Modulus(CurrentItem - 1 + 3, 4) + 1\n PrevItem = Modulus(CurrentItem + 2, 4) + 1\n"
},
{
"answer_id": 313956,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 1,
"selected": false,
"text": "Modulus(-1,n) = n-1 Modulus() 0 NextItem = Modulus((CurrentItem-1)+1, NumberOfItems) + 1\nPrevItem = Modulus((CurrentItem-1)-1, NumberOfItems) + 1\n NumberOfItems = 4 Modulus(-2,4) = 2"
},
{
"answer_id": 313960,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": -1,
"selected": false,
"text": "for i = 1, 8 do\n local idxF = i % 4 + 1\n local idxB = (i - 2) % 4 + 1\n print(i .. \" \" .. idxF .. \" \" .. idxB)\nend\n PreviousItem = Modulus(CurrentItem - 2, 4) + 1"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12277/"
] |
313,921 | <pre><code>class Score
{
var $score;
var $name;
var $dept;
var $date;
function Score($score, $name, $dept, $date)
{
$this->scores = ($score);
$this->name = ($name);
$this->dept = ($dept);
$this->date = ($date);
}
function return_score(){
return $this->scores;
return $this->name;
return $this->dept;
return $this->date;
}
}
$newscore = new Score("131313","James", "Marketing", "19/05/2008");
echo $newscore->return_score();
</code></pre>
<p>The above code is only echoing 131313. I am just beginning to learn OO PHP so please go easy! Totally lost, so any help would be much appreciated.</p>
| [
{
"answer_id": 313936,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 2,
"selected": false,
"text": "public function getScore() {\n return $this->score;\n}\n\npublic function getName() {\n return $this->name;\n}\n\npublic function getDept() {\n return $this->dept;\n}\n\n\npublic function getDate() {\n return $this->date;\n}\n public function getAll() {\n return $this->getScore(). \" \" .$this->getName() . \" \" .$this->getDept(). \" \" .$this->getDate();\n}\n"
},
{
"answer_id": 313967,
"author": "philistyne",
"author_id": 16597,
"author_profile": "https://Stackoverflow.com/users/16597",
"pm_score": 3,
"selected": true,
"text": "return $this->scores.' '.this->name.' '.$this->dept.' '.$this->date;\n//added spaces for readability, but this is a silly thing to do anyway...\n <tr>\n <td><?php echo $score->name; ?></td>\n <td><?php echo $score->scores; ?></td>\n <!-- more cells for more properies? -->\n</tr>\n"
},
{
"answer_id": 313978,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "var $score;\nvar $name;\nvar $dept;\nvar $date;\n protected $score;\n protected $_score;\n function Score($score, $name, $dept, $date)\n{\n $this->scores = ($score);\n $this->name = ($name);\n $this->dept = ($dept);\n $this->date = ($date);\n $this->score = $score;\n $this->name = $name;\n $this->dept = $dept;\n $this->date = $date;\n\n}\n public function getScore() {\n return $this->score;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
313,924 | <p>(EDIT: This question is now outdated for my particular issue, as Google Code supports git now and I've converted Protocol Buffers to Mercurial anyway. However, it's still of general interest, IMO.)</p>
<p>My <a href="http://github.com/jskeet/dotnet-protobufs/tree/master" rel="noreferrer">C# Protocol Buffers Port</a> uses github for its source control, and I'm beginning to really enjoy using git. However, as far as I can tell, github doesn't provide any project management tools: defect and feature tracking, discussions, feature requests, docs etc. Given my affiliations, <a href="http://code.google.com" rel="noreferrer">Google Code</a> would be a natural choice, but it would seem odd to create a project there but host the source on github.</p>
<p><a href="https://stackoverflow.com/questions/39186/should-i-use-githubfogbugz-or-assembla">This question about Fogbugz/Assembla</a> seems to mostly focus on the defect tracking. I was wondering what experiences others have had when it comes to a more "complete" project management solution. Does Fogbugz actually do everything I need? (Using a wiki for docs has its advantages, although I also want to be able to distribute documentation with the code.) Beyond the explicit features mentioned in the first paragraph, are there other project aspects I <em>should</em> be considering which I may have missed?</p>
<p>This will definitely stay an open source project, and although I'd rather not pay I don't mind if a small fee is required. Currently I'm the only developer, but that may change and there may very well be lots of people filing bugs and feature requests. (In other words, I hope and expect it to be popular, but with me doing most of the work.)</p>
<p>Previously I've <em>contributed</em> to various open source projects, but haven't done much in the way of running a very visible and active one. (<a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> is currently still "hosted" on my website, with occasional releases - the actual source control is on my local NAS.)</p>
<p>Anyone care to share their experiences?</p>
<p>EDIT: Another option I'm now considering is a Google Code project (I really would like to be loyal to my employer) and an occasional merge from git to svn (at the very least, every time I do a release). This would allow non-git users to get hold of the source easily too.</p>
| [
{
"answer_id": 314031,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 3,
"selected": false,
"text": "*"
},
{
"answer_id": 11584054,
"author": "Sudhir Jonathan",
"author_id": 73831,
"author_profile": "https://Stackoverflow.com/users/73831",
"pm_score": 0,
"selected": false,
"text": "<plug> </plug>"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22656/"
] |
313,935 | <p>I have a sql query that runs super fast, around one second, when not using variables, like:</p>
<pre><code>WHERE id BETWEEN 5461094 and 5461097
</code></pre>
<p>But when I have:</p>
<pre><code>declare @firstId int
declare @lastId int
set @firstId = 5461094
set @lastId = 5461097
...
WHERE id BETWEEN @firstId and @lastId
</code></pre>
<p>... the query runs really slow, finishing only after some minutes. Why does it happen? I need to use variables. Can I do any improvement to avoid this performance problems?</p>
| [
{
"answer_id": 314032,
"author": "DiGi",
"author_id": 12042,
"author_profile": "https://Stackoverflow.com/users/12042",
"pm_score": 2,
"selected": false,
"text": "DECLARE @sql VARCHAR(8000)\n\nSET @sql = 'SELECT * FROM table_x WHERE id BETWEEN ' + CAST(@firstId AS VARCHAR) + ' AND ' + CAST(@lastId AS VARCHAR)\n\nEXEC (@sql)\n"
},
{
"answer_id": 1164116,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "WHERE id BETWEEN @firstId and @lastId\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
313,962 | <p>I'm currently using the following SQL for retrieving the last seven days worth of entries from a table:</p>
<pre><code>purchased >= date_sub(now() ,interval 7 day)
</code></pre>
<p>However, I need to change this so it retrieves the last full weeks worth of entries (midnight Saturday to midnight Saturday). So basically, throughout the week the results never change, but when someone visits on Sunday morning they will have refreshed.</p>
<p>I just can't get my head around how to work out the days etc. Also, are there built in MySQL functions for doing this?</p>
<p>I hope I've explained that clearly enough.
This is in a PHP application.</p>
| [
{
"answer_id": 313995,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 3,
"selected": true,
"text": "SELECT * FROM table WHERE YEARWEEK(purchased) = YEARWEEK(NOW());\n $sunday = date(('Y-m-d H:i:s'), strtotime('last sunday 00:00'));\n$sql = \"SELECT * FROM table WHERE purchased >= '$sunday'\";\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39428/"
] |
313,969 | <p>I have the the following html elements:</p>
<pre><code><tr>
<td> <label for="casenumber">Case:</label></td>
<td>
<%=Html.TextBox("casenumber", "", new Dictionary<string, object>
{
{"id", "casenumberID"}
})%>
</td>
</tr>
<tr>
<td><label for="fogbugzUser">Users:</label></td>
<td>
<%=Html.DropDownList("UserList", (SelectList)ViewData["UserList"], new Dictionary<string, object>
{
{"id", "userlistid"}
})%>
</td>
</tr>
</code></pre>
<p>Now, when the <code>casenumber</code> loses focus, I want to call the database to return me a selected value in the <code>UserList</code>.</p>
<p>Here's the Javascript:</p>
<pre><code>$(function() {
$("#casenumberID").blur(function() {
//don't know how to do!!);
});
});
</code></pre>
<p>And here's the client side scripting:</p>
<pre><code>public JsonResult GetOpenByUser(string casenumber)
{
return Json(userContext.OpenBy(casenumber));
}
</code></pre>
<p>The question is how to write the function "blur" so that I can pass in the value of the textbox <code>casenumber</code> to the <code>GetOpenByUser</code>? </p>
<p>Also, how to complete the function <code>blur</code> so that the option that has the same value as the one that is returned by <code>GetOpenByUser</code> will be selected?</p>
| [
{
"answer_id": 314172,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "#fogbugzUser get() $(function() {\n $(\"#casenumberID\").blur(function() {\n $.get(\n \"url/to/some.page/fetching.the.userid\",\n // this will be turned into URL parameters, e.g.: \"casenumberID=15\"\n { casenumberID: this.value },\n function(result) {\n /* check if result is a string of numbers only (change for \n * something that better suits your needs if numbers is not\n * what you expect here */\n if (/^\\d+$/.test(result))\n $(\"#fogbugzUser\").val(result);\n else\n alert(\"Server returned an unexpected result: \" + result);\n }\n }); \n });\n});\n getJSON()"
},
{
"answer_id": 316344,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 0,
"selected": false,
"text": " public JsonResult GetOpenByUser(string casenumber)\n {\n\n return Json(userContext.OpenBy(casenumber));\n }\n <form id=\"subForm\">\n <tr> \n <td> <label for=\"casenumber\">Case:</label></td>\n <td><%=Html.TextBox(\"casenumber\", \"\")%> </td>\n </tr>\n <tr>\n <td><label for=\"fogbugzUser\">Users:</label></td>\n <td><%=Html.DropDownList(\"UserList\", (SelectList)ViewData[\"UserList\"])%></td>\n </tr>\n</form>\n $(function() {\n $(\"#casenumber\").blur(function() {\n $.getJSON(\"Home/GetOpenByUser\",\n { casenumber: this.value },\n function(result) {\n if (result == \"\")\n return;\n\n $(\"#subForm select[@name='UserList'] option[@selected='selected']\").removeAttr(\"selected\"); //remove any selected items\n $(\"#subForm select[@name='UserList'] option[@value='\" + result + \"']\").attr(\"selected\", \"selected\"); //select the item that is returned from the server\n\n });\n });\n\n});\n"
},
{
"answer_id": 317532,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 0,
"selected": false,
"text": "$(function() {\n $(\"#casenumber\").blur(function() {\n $.getJSON(\"Home/GetOpenByUser\",\n { casenumber: this.value },\n function(result) {\n if (result == \"\")\n return;\n\n $(\"#UserList\").val(this.value)\n\n });\n });\n\n});\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
313,970 | <p>I want to convert a <code>std::string</code> to lowercase. I am aware of the function <code>tolower()</code>. However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a <code>std::string</code> would require iterating over each character.</p>
<p>Is there an alternative which works 100% of the time?</p>
| [
{
"answer_id": 313988,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 9,
"selected": false,
"text": "#include <boost/algorithm/string.hpp>\n\nstd::string str = \"HELLO, WORLD!\";\nboost::algorithm::to_lower(str); // modifies str\n #include <boost/algorithm/string.hpp>\n\nconst std::string str = \"HELLO, WORLD!\";\nconst std::string lower_str = boost::algorithm::to_lower_copy(str);\n"
},
{
"answer_id": 313990,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 11,
"selected": true,
"text": "#include <algorithm>\n#include <cctype>\n#include <string>\n\nstd::string data = \"Abc\";\nstd::transform(data.begin(), data.end(), data.begin(),\n [](unsigned char c){ return std::tolower(c); });\n tolower() char asciitolower(char in) {\n if (in <= 'Z' && in >= 'A')\n return in - ('Z' - 'z');\n return in;\n}\n\nstd::transform(data.begin(), data.end(), data.begin(), asciitolower);\n tolower()"
},
{
"answer_id": 15675512,
"author": "user2218467",
"author_id": 2218467,
"author_profile": "https://Stackoverflow.com/users/2218467",
"pm_score": 5,
"selected": false,
"text": "std::transform #include <string>\n#include <algorithm>\n#include <iostream>\n\nint main (int argc, char* argv[])\n{\n std::string sourceString = \"Abc\";\n std::string destinationString;\n\n // Allocate the destination space\n destinationString.resize(sourceString.size());\n\n // Convert the source string to lower case\n // storing the result in destination string\n std::transform(sourceString.begin(),\n sourceString.end(),\n destinationString.begin(),\n ::tolower);\n\n // Output the result of the conversion\n std::cout << sourceString\n << \" -> \"\n << destinationString\n << std::endl;\n}\n"
},
{
"answer_id": 18881634,
"author": "Jason Enochs",
"author_id": 752911,
"author_profile": "https://Stackoverflow.com/users/752911",
"pm_score": 3,
"selected": false,
"text": "#include \"Poco/String.h\"\nusing namespace Poco;\n\nstd::string hello(\"Stack Overflow!\");\n\n// Copies \"STACK OVERFLOW!\" into 'newString' without altering 'hello.'\nstd::string newString(toUpper(hello));\n\n// Changes newString in-place to read \"stack overflow!\"\ntoLowerInPlace(newString);\n"
},
{
"answer_id": 19266247,
"author": "incises",
"author_id": 951155,
"author_profile": "https://Stackoverflow.com/users/951155",
"pm_score": 5,
"selected": false,
"text": "#include <iostream> // std::cout\n#include <string> // std::string\n#include <locale> // std::locale, std::tolower\n\nint main ()\n{\n std::locale loc;\n std::string str=\"Test String.\\n\";\n\n for(auto elem : str)\n std::cout << std::tolower(elem,loc);\n}\n"
},
{
"answer_id": 21002884,
"author": "user2548100",
"author_id": 2548100,
"author_profile": "https://Stackoverflow.com/users/2548100",
"pm_score": 2,
"selected": false,
"text": "#include <clocale>\nstatic char UtoL[256];\n// ----------------------------------------------------------------------------\nvoid InitUtoLMap() {\n for (int i = 0; i < sizeof(UtoL); i++) {\n if (isupper(i)) {\n UtoL[i] = (char)(i + 32);\n } else {\n UtoL[i] = i;\n }\n }\n}\n// ----------------------------------------------------------------------------\nchar *LowerStr(char *szMyStr) {\n char *p = szMyStr;\n // do conversion in-place so as not to require a destination buffer\n while (*p) { // szMyStr must be null-terminated\n *p = UtoL[*p]; \n p++;\n }\n return szMyStr;\n}\n// ----------------------------------------------------------------------------\nint main() {\n time_t start;\n char *Lowered, Upper[128];\n InitUtoLMap();\n strcpy(Upper, \"Every GOOD boy does FINE!\");\n\n Lowered = LowerStr(Upper);\n return 0;\n}\n"
},
{
"answer_id": 24063783,
"author": "DevSolar",
"author_id": 60281,
"author_profile": "https://Stackoverflow.com/users/60281",
"pm_score": 8,
"selected": false,
"text": "std::string 0x7f std::string .substr() std::toupper( 'ß' ) std::tolower( 'Σ' ) ß SS Σ σ ς std::tolower( 'I' ) i ı std:: std::basic_string<> std::u16string std::u32string std::u8string #include <unicode/unistr.h>\n#include <unicode/ustream.h>\n#include <unicode/locid.h>\n\n#include <iostream>\n\nint main()\n{\n /* \"Odysseus\" */\n char const * someString = u8\"ΟΔΥΣΣΕΥΣ\";\n icu::UnicodeString someUString( someString, \"UTF-8\" );\n // Setting the locale explicitly here for completeness.\n // Usually you would use the user-specified system locale,\n // which *does* make a difference (see ı vs. i above).\n std::cout << someUString.toLower( \"el_GR\" ) << \"\\n\";\n std::cout << someUString.toUpper( \"el_GR\" ) << \"\\n\";\n return 0;\n}\n g++ -Wall example.cpp -licuuc -licuio\n ὀδυσσεύς\n <algorithm>"
},
{
"answer_id": 24679044,
"author": "Phil",
"author_id": 3455897,
"author_profile": "https://Stackoverflow.com/users/3455897",
"pm_score": -1,
"selected": false,
"text": "string LowerCase(string s)\n{\n int dif='a'-'A';\n for(int i=0;i<s.length();i++)\n {\n if((s[i]>='A')&&(s[i]<='Z'))\n s[i]+=dif;\n }\n return s;\n}\n\nstring UpperCase(string s)\n{\n int dif='a'-'A';\n for(int i=0;i<s.length();i++)\n {\n if((s[i]>='a')&&(s[i]<='z'))\n s[i]-=dif;\n }\n return s;\n}\n"
},
{
"answer_id": 25573133,
"author": "Sandeep Datta",
"author_id": 39648,
"author_profile": "https://Stackoverflow.com/users/39648",
"pm_score": 2,
"selected": false,
"text": "strlwr // crt_strlwr.c\n// compile with: /W3\n// This program uses _strlwr and _strupr to create\n// uppercase and lowercase copies of a mixed-case string.\n#include <string.h>\n#include <stdio.h>\n\nint main( void )\n{\n char string[100] = \"The String to End All Strings!\";\n char * copy1 = _strdup( string ); // make two copies\n char * copy2 = _strdup( string );\n\n _strlwr( copy1 ); // C4996\n _strupr( copy2 ); // C4996\n\n printf( \"Mixed: %s\\n\", string );\n printf( \"Lower: %s\\n\", copy1 );\n printf( \"Upper: %s\\n\", copy2 );\n\n free( copy1 );\n free( copy2 );\n}\n"
},
{
"answer_id": 30796939,
"author": "Atul Rokade",
"author_id": 2823762,
"author_profile": "https://Stackoverflow.com/users/2823762",
"pm_score": 3,
"selected": false,
"text": "#include <algorithm>\n#include <iostream>\n#include <string>\nusing namespace std;\nint main(){\n string str;\n getline(cin,str);\n//------------function to convert string into lowercase---------------\n transform(str.begin(), str.end(), str.begin(), ::tolower);\n//--------------------------------------------------------------------\n cout<<str;\n return 0;\n}\n #include <algorithm>\n#include <iostream>\n#include <string>\nusing namespace std;\nint main(){\n string str;\n cin>>str;\n//------------function to convert string into lowercase---------------\n transform(str.begin(), str.end(), str.begin(), ::tolower);\n//--------------------------------------------------------------------\n cout<<str;\n return 0;\n}\n"
},
{
"answer_id": 35075839,
"author": "Sameer",
"author_id": 641622,
"author_profile": "https://Stackoverflow.com/users/641622",
"pm_score": 2,
"selected": false,
"text": "std::ctype::tolower() #include <locale>\n#include <iostream>\n\nint main () {\n std::locale::global(std::locale(\"en_US.utf8\"));\n std::wcout.imbue(std::locale());\n std::wcout << \"In US English UTF-8 locale:\\n\";\n auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());\n std::wstring str = L\"HELLo, wORLD!\";\n std::wcout << \"Lowercase form of the string '\" << str << \"' is \";\n f.tolower(&str[0], &str[0] + str.size());\n std::wcout << \"'\" << str << \"'\\n\";\n}\n"
},
{
"answer_id": 35107059,
"author": "Volomike",
"author_id": 105539,
"author_profile": "https://Stackoverflow.com/users/105539",
"pm_score": 2,
"selected": false,
"text": "#define STRTOLOWER(x) std::transform (x.begin(), x.end(), x.begin(), ::tolower)\n#define STRTOUPPER(x) std::transform (x.begin(), x.end(), x.begin(), ::toupper)\n#define STRTOUCFIRST(x) std::transform (x.begin(), x.begin()+1, x.begin(), ::toupper); std::transform (x.begin()+1, x.end(), x.begin()+1,::tolower)\n"
},
{
"answer_id": 41577237,
"author": "Gilson PJ",
"author_id": 2039094,
"author_profile": "https://Stackoverflow.com/users/2039094",
"pm_score": 5,
"selected": false,
"text": "string test = \"Hello World\";\nfor(auto& c : test)\n{\n c = tolower(c);\n}\n\ncout<<test<<endl;\n"
},
{
"answer_id": 42896335,
"author": "9T9",
"author_id": 1266018,
"author_profile": "https://Stackoverflow.com/users/1266018",
"pm_score": 1,
"selected": false,
"text": "// tolower example (C++)\n#include <iostream> // std::cout\n#include <string> // std::string\n#include <locale> // std::locale, std::tolower\n\nint main ()\n{\n std::locale loc;\n std::string str=\"Test String.\\n\";\n for (std::string::size_type i=0; i<str.length(); ++i)\n std::cout << std::tolower(str[i],loc);\n return 0;\n}\n"
},
{
"answer_id": 43331205,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": -1,
"selected": false,
"text": "#include<bits/stdc++.h>\nusing namespace std;\n\n\nint main ()\n{\n ios::sync_with_stdio(false);\n\n string str=\"String Convert\\n\";\n\n for(int i=0; i<str.size(); i++)\n {\n str[i] = tolower(str[i]);\n }\n cout<<str<<endl;\n\n return 0;\n}\n"
},
{
"answer_id": 43841933,
"author": "uol3c",
"author_id": 4705766,
"author_profile": "https://Stackoverflow.com/users/4705766",
"pm_score": 0,
"selected": false,
"text": "fplus::to_lower_case() to_lower_case fplus::to_lower_case(std::string(\"ABC\")) == std::string(\"abc\");\n"
},
{
"answer_id": 49877992,
"author": "goulashsoup",
"author_id": 5233188,
"author_profile": "https://Stackoverflow.com/users/5233188",
"pm_score": 1,
"selected": false,
"text": "string test = \"Hello World\";\nfor(auto& c : test)\n{\n c = tolower(c);\n}\n for(auto& c : test) for ( range_declaration : range_expression ) loop_statement range_declaration auto& c range_expression test test test c"
},
{
"answer_id": 50672861,
"author": "Praveer Kumar",
"author_id": 4064987,
"author_profile": "https://Stackoverflow.com/users/4064987",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\n\nint main()\n{\n std::string _input = \"lowercasetouppercase\";\n#if 0\n // My idea is to use the ascii value to convert\n char upperA = 'A';\n char lowerA = 'a';\n\n cout << (int)upperA << endl; // ASCII value of 'A' -> 65\n cout << (int)lowerA << endl; // ASCII value of 'a' -> 97\n // 97-65 = 32; // Difference of ASCII value of upper and lower a\n#endif // 0\n\n cout << \"Input String = \" << _input.c_str() << endl;\n for (int i = 0; i < _input.length(); ++i)\n {\n _input[i] -= 32; // To convert lower to upper\n#if 0\n _input[i] += 32; // To convert upper to lower\n#endif // 0\n }\n cout << \"Output String = \" << _input.c_str() << endl;\n\n return 0;\n}\n"
},
{
"answer_id": 55208216,
"author": "Mahipal",
"author_id": 3133106,
"author_profile": "https://Stackoverflow.com/users/3133106",
"pm_score": 2,
"selected": false,
"text": "tolower toupper std::string char #include<iostream>\n \nint main(){\n std::string str = std::string(\"How ARe You\");\n for(char &ch : str){\n ch = std::tolower(ch);\n }\n std::cout<<str<<std::endl;\n return 0;\n}\n"
},
{
"answer_id": 55686334,
"author": "L. F.",
"author_id": 9716597,
"author_profile": "https://Stackoverflow.com/users/9716597",
"pm_score": 2,
"selected": false,
"text": "range-v3 str |= action::transform([](unsigned char c){ return std::tolower(c); });\n auto new_string = original_string\n | view::transform([](unsigned char c){ return std::tolower(c); });\n #include <cctype> unsigned char <cctype> std::tolower unsigned char EOF char signed char unsigned char char my_tolower(char ch)\n{\n return static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));\n}\n char signed char unsigned char std::string str_tolower(std::string s) {\n std::transform(s.begin(), s.end(), s.begin(), \n // static_cast<int(*)(int)>(std::tolower) // wrong\n // [](int c){ return std::tolower(c); } // wrong\n // [](char c){ return std::tolower(c); } // wrong\n [](unsigned char c){ return std::tolower(c); } // correct\n );\n return s;\n}\n"
},
{
"answer_id": 56199972,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 3,
"selected": false,
"text": "#include <string>\n#include <algorithm>\n\n//\n// Lowercases string\n//\ntemplate <typename T>\nstd::basic_string<T> lowercase(const std::basic_string<T>& s)\n{\n std::basic_string<T> s2 = s;\n std::transform(s2.begin(), s2.end(), s2.begin(), tolower);\n return s2;\n}\n\n//\n// Uppercases string\n//\ntemplate <typename T>\nstd::basic_string<T> uppercase(const std::basic_string<T>& s)\n{\n std::basic_string<T> s2 = s;\n std::transform(s2.begin(), s2.end(), s2.begin(), toupper);\n return s2;\n}\n"
},
{
"answer_id": 60749613,
"author": "Bu Saeed",
"author_id": 4763511,
"author_profile": "https://Stackoverflow.com/users/4763511",
"pm_score": 1,
"selected": false,
"text": "string toLowerCase(string str) {\n\n int str_len = str.length();\n\n string final_str = \"\";\n\n for(int i=0; i<str_len; i++) {\n\n char character = str[i];\n\n if(character>=65 && character<=92) {\n\n final_str += (character+32);\n\n } else {\n\n final_str += character;\n\n }\n\n }\n\n return final_str;\n\n}\n"
},
{
"answer_id": 64128715,
"author": "A-Sharabiani",
"author_id": 4505446,
"author_profile": "https://Stackoverflow.com/users/4505446",
"pm_score": 3,
"selected": false,
"text": "#include <locale> // tolower\n\nstring to_lower(string s) { \n for(char &c : s)\n c = tolower(c);\n return s;\n}\n string s = \"TEST\";\ncout << to_lower(\"HELLO WORLD\"); // output: \"hello word\"\ncout << to_lower(s); // won't change the original variable.\n"
},
{
"answer_id": 68081322,
"author": "prehistoricpenguin",
"author_id": 1292791,
"author_profile": "https://Stackoverflow.com/users/1292791",
"pm_score": -1,
"selected": false,
"text": "void toLowerAscii(char* str, size_t length)\n void AsciiStrToLower(std::string* s);\n"
},
{
"answer_id": 70969360,
"author": "The Oathman",
"author_id": 10860215,
"author_profile": "https://Stackoverflow.com/users/10860215",
"pm_score": -1,
"selected": false,
"text": "#include <type_traits> // std::decay\n#include <ctype.h> // std::toupper & std::tolower\n\n\ntemplate <class T = void> struct farg_t { using type = T; };\ntemplate <template<typename ...> class T1, \nclass T2> struct farg_t <T1<T2>> { using type = T2*; };\n//---------------\n\ntemplate<class T, class T2 = \ntypename std::decay< typename farg_t<T>::type >::type>\nvoid ToUpper(T& str) { T2 t = &str[0]; \nfor (; *t; ++t) *t = std::toupper(*t); }\n\n\ntemplate<class T, class T2 = typename std::decay< typename \nfarg_t<T>::type >::type>\nvoid Tolower(T& str) { T2 t = &str[0]; \nfor (; *t; ++t) *t = std::tolower(*t); }\n #include <iostream>\n#include \"upove_code.h\"\n\nint main()\n{\n\n std::string str1 = \"hEllo \";\n char str2 [] = \"wOrld\";\n\n ToUpper(str1);\n ToUpper(str2);\n std::cout << str1 << str2 << '\\n'; \n Tolower(str1);\n Tolower(str2);\n std::cout << str1 << str2 << '\\n'; \n return 0;\n}\n >HELLO WORLD\n>\n>hello world\n"
},
{
"answer_id": 72000243,
"author": "Edward Gaere",
"author_id": 14641282,
"author_profile": "https://Stackoverflow.com/users/14641282",
"pm_score": 0,
"selected": false,
"text": "\n#include <exception>\n#include <iostream>\n#include <codecvt>\n\n// cpp-unicodelib, downloaded from GitHub\n#include \"unicodelib.h\"\n#include \"unicodelib_encodings.h\"\n\nusing namespace std;\nusing namespace unicode;\n\n// converter that allows displaying a Unicode32 string\nwstring_convert<codecvt_utf8<char32_t>, char32_t> converter;\n\nstd::u32string in = U\"Je suis là!\";\ncout << converter.to_bytes(in) << endl;\n\nstd::u32string lc = to_lowercase(in);\ncout << converter.to_bytes(lc) << endl;\n\n Je suis là!\nje suis là!\n"
},
{
"answer_id": 72401086,
"author": "SHAYAK",
"author_id": 11947631,
"author_profile": "https://Stackoverflow.com/users/11947631",
"pm_score": 0,
"selected": false,
"text": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n string a = \"sssAAAAAAaaaaDas\";\n transform(a.begin(),a.end(),a.begin(),::tolower);\n cout<<a;\n}\n\n"
},
{
"answer_id": 72402768,
"author": "DimanNe",
"author_id": 758986,
"author_profile": "https://Stackoverflow.com/users/758986",
"pm_score": 0,
"selected": false,
"text": "absl absl::AsciiStrToLower absl::AsciiStrToUpper"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
313,998 | <p>In <strong>classic ASP</strong> there is a global object called <strong>"Application"</strong> that is accessed simultaniously by all sessions.</p>
<p>As the "Application" object is a shared resource, can it cause <strong>dead locks?</strong></p>
<p>EDIT: If not, why does it has <strong>lock</strong> and <strong>unlock</strong> methods for? <a href="http://www.w3schools.com/asp/asp_ref_application.asp" rel="nofollow noreferrer">Reference</a></p>
| [
{
"answer_id": 314588,
"author": "dariom",
"author_id": 12389,
"author_profile": "https://Stackoverflow.com/users/12389",
"pm_score": 2,
"selected": false,
"text": "Application Application <%\nApplication(\"Count\") = Application(\"Count\") + 1\n%>\n Application <%\nApplication.Lock\nApplication(\"Count\") = Application(\"Count\") + 1\nApplication.Unlock\n%>\n Application"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/313998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
314,008 | <p>This is a contrived example, but lets say I have declared objects:</p>
<pre><code>CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;
</code></pre>
<p>And I have an string array:</p>
<pre><code>string[] stringarray = new string[] {"foo","bar","baz"};
</code></pre>
<p>How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach:</p>
<pre><code>foreach (string i in stringarray) {
`i`Obj = new CustomObj(i);
}
</code></pre>
<p>Hope the idea I'm trying to get across is clear. Is this possible in C#?</p>
| [
{
"answer_id": 314010,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "Dictionary<string, CustomObj> Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>();\n\nforeach (string name in stringArray)\n{\n map[name] = new CustomObj(name);\n}\n"
},
{
"answer_id": 314011,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "Dictionary<String, CustomObj> objs = new Dictionary<String, CustomObj>();\n\nforeach (string i in stringarray)\n{\n objs[i] = new CustomObj(i);\n}\n public class SomeClass\n{\n private CustomObj fooObj;\n private CustomObj barObj;\n private CustomObj bazObj;\n}\n"
},
{
"answer_id": 1019442,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " public static Control FindControl(string controlId, Control container)\n {\n if (container.ID == controlId)\n return container;\n\n foreach (Control control in container.Controls)\n {\n Control c = FindControl(controlId, control);\n if (c != null)\n return c;\n }\n return null;\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35463/"
] |
314,012 | <p>I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?</p>
<p>Function:</p>
<pre><code>std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
</code></pre>
<p>Error:</p>
<pre><code>error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
</code></pre>
| [
{
"answer_id": 314018,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": true,
"text": "std::vector< CClass >::const_iterator std::vector< CClass >::iterator std::vector< CClass >::iterator it;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
314,024 | <p>My understanding is that you have to write unit tests that isolate functionality. So given a repository class that has this method:</p>
<pre><code>Entity GetById(Guid id)
</code></pre>
<p>and a <em>fake</em> implementation (using a Dictionary for storage), how would you write a test without first <em>adding</em> an entity? Is it ok to use a known set of guids for testing? Then in the fake repository constructor I could fill the dictionary with a couple of entities where the guids follow a pattern, so that I can test the GetById() method with a guid that I know will return an entity. </p>
<p>Thanks for reading!</p>
<p>PS. This is my first time writing unit tests.</p>
| [
{
"answer_id": 314041,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": "Expect.Call(repository.GetById(\"someObject\")).Return(new RepositoryThing());\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830/"
] |
314,054 | <p>I'm looking for a way to query the ink level for my Epson DX 4050 on Mac OS X. There is some UI called EPSON StatusMonitor to display cartridges levels graphically, but I'd like to get it from the command-line so it can feed a robot.</p>
<p>Any idea ?</p>
| [
{
"answer_id": 43123592,
"author": "tseeling",
"author_id": 919085,
"author_profile": "https://Stackoverflow.com/users/919085",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\nme=\"${0##*/}\"\n\nhost=\"${1:-wp4535}\"\n\nbase=1.3.6.1.2.1.43.11.1.1\n\nname=\"WP-4535\"\n\ntype=$(snmpget -v1 -c public ${host} SNMPv2-MIB::sysDescr.0)\n\ncase \"$type\" in\n\"SNMPv2-MIB::sysDescr.0 = STRING: EPSON\"*)\n type=epson\n ofs=1\n;;\n*)\n echo \"! unknown printer type\" 1>&2\n exit 1\n;;\nesac\necho \"# $host $type $name\"\n\n# get current ink levels\neval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.6.${ofs} |\nperl -ne 'print \"c[\",++$c,\"]=$1\\n\" if(m!\"(\\w+) ink!i);')\n\n# get max ink level per cartridge\neval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.8.${ofs} |\nperl -ne 'print \"max[\",++$c,\"]=$1\\n\" if(m!(\\d+)!i);')\n\nsnmpwalk -v1 -Ov -OQ -c public ${host} ${base}.9.${ofs} |\nperl -ne '\n my @c=(\"\",\"'${c[1]}'\",\"'${c[2]}'\",\"'${c[3]}'\",\"'${c[4]}'\");\n my @max=(\"\",\"'${max[1]}'\",\"'${max[2]}'\",\"'${max[3]}'\",\"'${max[4]}'\");\n my $v=$c[++$c];\n printf\"# $v=$1 (%.0f)\\n\",$1/$max[$c]*100 if(m!(\\d+)!i);'\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20302/"
] |
314,055 | <p>I know there is <a href="https://stackoverflow.com/questions/63546/vs2005-c-programmatically-change-connection-string-contained-in-appconfig">some similar issue</a>.</p>
<p>But, still the question is not answered! I need to <strong>modify</strong> the connection string not add a new one.</p>
| [
{
"answer_id": 314060,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 3,
"selected": false,
"text": " /// <summary>\n /// Add a connection string to the connection\n /// strings section and store it in the\n /// configuration file. \n /// </summary>\n /// <param name=\"csName\">The name of the property.</param>\n /// <param name=\"connectionString\">The connectionstring as specified.</param>\n public static void AddConnectionStrings(string csName, string connectionString)\n {\n\n // Get the configuration file.\n System.Configuration.Configuration config =\n ConfigurationManager.OpenExeConfiguration(\n ConfigurationUserLevel.None);\n\n // Add the connection string.\n ConnectionStringsSection csSection = config.ConnectionStrings;\n csSection.ConnectionStrings.Add(\n new ConnectionStringSettings(csName,\n connectionString, \"System.Data.SqlClient\"));\n\n // Save the configuration file.\n config.Save(ConfigurationSaveMode.Full); \n }\n /// <summary>\n /// First remove the old connectionstring and after that\n /// add a connection string to the connectionstrings\n /// section and store it in the configuration file. \n /// </summary>\n /// <param name=\"csName\">The name of the property.</param>\n /// <param name=\"connectionString\">The connectionstring as specified.</param>\n public static void UpdateConnectionStrings(string csName, string connectionString)\n {\n // Get the configuration file\n System.Configuration.Configuration config =\n ConfigurationManager.OpenExeConfiguration(\n ConfigurationUserLevel.None);\n\n // Remove the existing connectionstring.\n config.ConnectionStrings.ConnectionStrings.Remove(csName);\n // Add the connectionstring\n ConnectionStringsSection csSection = config.ConnectionStrings;\n csSection.ConnectionStrings.Add(\n new ConnectionStringSettings(csName, \n connectionString, \"System.Data.SqlClient\"));\n\n // Save the configuration file\n config.Save(ConfigurationSaveMode.Full);\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,058 | <p>Is there a way to get MVEL 2.0 ( <a href="http://mvel.codehaus.org/" rel="nofollow noreferrer">http://mvel.codehaus.org/</a> ) to work with functions with optional parameters?</p>
<p>I would like to be able to eval this:</p>
<p>trunc('blahblah',2)</p>
<p>but also</p>
<p>trunc('blahblah',2,'[...]');</p>
<p>Now i have tried: </p>
<p>def trunc(param1,param2,param3) { ... impl ... }</p>
<p>That gives an exception if i try to call it with only 3 parameters.
I also tried:</p>
<p>def trunc(param1,param2,param3) { ... impl ... }
def trunc(param1,param2) { ... impl ... }</p>
<p>But the second one seems to completely overwrite the first definition.</p>
<p>Thanks</p>
| [
{
"answer_id": 4429797,
"author": "Kr1z",
"author_id": 513690,
"author_profile": "https://Stackoverflow.com/users/513690",
"pm_score": 1,
"selected": false,
"text": "private void method(Object obj1) {\n Object obj2 = new Object(\"Default\");\n method(obj1, obj2);\n}\n\nprivate void method(Object obj1, Object obj2) {\n doStuff(...);\n}\n"
},
{
"answer_id": 5792181,
"author": "Frederik",
"author_id": 231298,
"author_profile": "https://Stackoverflow.com/users/231298",
"pm_score": 0,
"selected": false,
"text": "parserContext = new ParserContext();\nparserContext.addImport(\"color\", MyImplementation.class.getMethod(\"color\", double[].class));\n // This one is used for lookup, but never called.\npublic static Color color(double... values) {} \n\npublic static Color color(double gray) {}\npublic static Color color(double red, double green, double blue) {}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40254/"
] |
314,068 | <p>Even before telling my question, will tell you that this is a very vague question. But please let me know if you have any similar ideas. </p>
<p>I am actually trying to write a website of my own locally using ASP.Net. I actually wanted to try and simulate a website with trading and stock details. I wanted to actually fetch the details from some were. Please let me know if it is possible to fetch data from another website or is there any site where i can fetch such details. Also please let me know of what all parameters i need to keep in mind before and while designing a website. Please let me know any such ideas which i can make use of. Thank you one and all very very much. Any comment from you is appreciated.</p>
| [
{
"answer_id": 314403,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 1,
"selected": false,
"text": " // Create an HttpWebRequest using WebRequest.Create (see .NET docs)!\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);\n\n\n // Execute the request and obtain the response\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
314,085 | <p>I know questions of this kind <a href="https://stackoverflow.com/questions/24298/best-solution-for-authentication-in-ruby-on-rails">have</a> <a href="https://stackoverflow.com/questions/13254/open-id-authentication-in-ruby-on-rails">been</a> <a href="https://stackoverflow.com/questions/38901/strange-rails-authentication-issue">asked</a> before, but my situation differs a little.</p>
<p>On my rails app I have to validate the user login against an existing repository and then control authorization to given modules. So, I don't want the solution I go for to generate a model for my users and rely on that. The authetication per se needs to be customized.</p>
<p>Under that scenario, what would be the best plugin to use?</p>
| [
{
"answer_id": 316418,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 2,
"selected": false,
"text": "SecureSessions::Password.validate_proc = proc do |ctrl| \n # define any proc here which validates username/password etc, and returns a unique ID\n return nil unless User.authenticate(ctrl.params[:login], ctrl.params[:password])\n User.find_by_login(ctrl.params[:login]).id\nend\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
] |
314,095 | <p><strong>Is there a way that I can configure Visual Studio 2008 to understand CamelCase?</strong> Specifically, I'd like to be able to get <code>Ctrl + right</code> or <code>left</code> cursor to take me to a subsection of a variable or type name.</p>
<p>i.e., if my cursor was at the start of this line:</p>
<pre class="lang-cs prettyprint-override"><code>LongNamedExampleClass longNamed = new LongNamedExampleClass();
</code></pre>
<p>and I hit <code>Ctrl + right</code>, I'd like to jump to "<code>Named</code>" in the class name, rather than the start of the variable name. If I hit it again, I'd like to go to "<code>Example</code>". I hope that makes sense.</p>
<p>I used this navigational feature in Eclipse quite a lot, and find it difficult to unlearn something so ingrained.</p>
| [
{
"answer_id": 29357666,
"author": "jsea",
"author_id": 1682070,
"author_profile": "https://Stackoverflow.com/users/1682070",
"pm_score": 7,
"selected": false,
"text": "Visual Studio 2019 Use new shortcut in Show commands containing Step 4 Alt + Right Arrow Alt + Left Arrow Alt + Shift + Right Arrow Alt + Shift + Left Arrow Alt + Delete Alt + Backspace Press shortcut keys Assign"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
314,098 | <p>Is the following scenario possible in SQL Server using a single active connection?</p>
<p>Inside a READCOMMITED transaction I need to update one table without locking it. For example each time I execute a statement I increase a field in that table. This operation doesn't need to be rolled back in case the transaction fails. Also, this update shouldn't block other concurrent users which try to update the same position.</p>
| [
{
"answer_id": 29357666,
"author": "jsea",
"author_id": 1682070,
"author_profile": "https://Stackoverflow.com/users/1682070",
"pm_score": 7,
"selected": false,
"text": "Visual Studio 2019 Use new shortcut in Show commands containing Step 4 Alt + Right Arrow Alt + Left Arrow Alt + Shift + Right Arrow Alt + Shift + Left Arrow Alt + Delete Alt + Backspace Press shortcut keys Assign"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,100 | <p>I'm working with LINQ to objects and have a function where in some cases I need to modify the underlying collection before calling <code>Aggregate(...)</code> and then return it to its original state before the funciton returns the results of <code>Aggregate(...)</code>. My current code looks something like this:</p>
<pre><code>bool collectionModified = false;
if(collectionNeedsModification)
{
modifyCollection();
collectionModified = true;
}
var aggregationResult = from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue;
if(collectionModified)
modifyCollection();
return aggregationResult;
</code></pre>
<p>However, as written, if I modify the collection, I will get the wrong result because I'm putting the collection back in its original state before <code>aggregationResult</code> is enumerated and LINQ results are lazy-evaluated. My current solution is to use <code>.ToArray()</code> on my LINQ query like this:</p>
<pre><code>var aggregationResult = (from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue).ToArray();
</code></pre>
<p>The size of the resulting array will always be small (< 100 items) so memory / processing time is not a concern. Is this the best way to handle my problem, or is there a better way to force the evaluation of a LINQ query?</p>
| [
{
"answer_id": 314122,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 2,
"selected": false,
"text": "var modifiedCollection = ModifyCollection(collection, collectionNeedsModification);\n\nvar aggregationResult = from a in\n (from b in modifiedCollection\n where b.SatisfysCondition)\n .Aggregate(aggregationFunction)\n select a.NeededValue;\n"
},
{
"answer_id": 314130,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "foreach (var result in aggregationResult)\n{\n // Deliberately empty; simply forcing evaluation of the sequence.\n}\n IList<T>"
},
{
"answer_id": 3371703,
"author": "Markus Johnsson",
"author_id": 199822,
"author_profile": "https://Stackoverflow.com/users/199822",
"pm_score": 4,
"selected": false,
"text": "aggregationResult.Run();\n public static MyLinqExtensions \n{\n public static void Run<T>(this IEnumerable<T> e)\n {\n foreach (var _ in e);\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
] |
314,108 | <p>How can I make this java generic cast ?</p>
<pre><code>public interface IField {
}
class Field implements IField { // package private class
}
public class Form {
private List<Field> fields;
public List<IField> getFields() {
return this.fields;
}
}
</code></pre>
<p>The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code.</p>
<p>If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class .</p>
<p>Can I force that damn compiler to bend it's rules and compile that return statement ?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 314112,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 4,
"selected": false,
"text": "return (List<IField>)(Object)this.fields;\n List<T> IField"
},
{
"answer_id": 314127,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 0,
"selected": false,
"text": "List<Field> fields List<IField> IField"
},
{
"answer_id": 314138,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "public List<? extends IField> getFields()\n"
},
{
"answer_id": 314149,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 3,
"selected": false,
"text": "List<Field> List<IField> List<Field> List<IField> List<Field>"
},
{
"answer_id": 2855436,
"author": "Nicolas Barbier",
"author_id": 343775,
"author_profile": "https://Stackoverflow.com/users/343775",
"pm_score": 2,
"selected": false,
"text": "return Collections.<IField>unmodifiableList(this.fields);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
] |
314,109 | <p>With PHP, I can make numerous PHP websites locally and then upload each of them to its own sub-directory of my PHP hosting service. </p>
<p>However, with ASP.NET, it seems that I can only upload my ASP.NET to the root of my hosting service. If I upload to a sub-directory, I get an error in </p>
<pre><code>section registered as allowDefinition='MachineToApplication' beyond application level
<authentication mode="Windows"/>
</code></pre>
<ul>
<li>is there a way to get around this so I can have numerous ASP.NET websites each in its own directory?</li>
<li>if not, would using ASP.NET MVC be able to get around this problem?</li>
<li>or is it generally not possible to FTP multiple ASP.NET sites to a shared hosting provider?</li>
</ul>
| [
{
"answer_id": 314112,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 4,
"selected": false,
"text": "return (List<IField>)(Object)this.fields;\n List<T> IField"
},
{
"answer_id": 314127,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 0,
"selected": false,
"text": "List<Field> fields List<IField> IField"
},
{
"answer_id": 314138,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "public List<? extends IField> getFields()\n"
},
{
"answer_id": 314149,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 3,
"selected": false,
"text": "List<Field> List<IField> List<Field> List<IField> List<Field>"
},
{
"answer_id": 2855436,
"author": "Nicolas Barbier",
"author_id": 343775,
"author_profile": "https://Stackoverflow.com/users/343775",
"pm_score": 2,
"selected": false,
"text": "return Collections.<IField>unmodifiableList(this.fields);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
314,110 | <p>Having a fully internationalised application is a necessity if you want to sell worldwide.
In Java we're using resource bundles and that solves things for static text codeside.</p>
<p>But what do you do about text that is stored in the database? Starting with static definitions, to user modifiable objects, ending with user entered data.</p>
<p>Assuming you have a database used by users with different Locales - how do you handle this? How far do you internationalise? Where do you draw the line?
What workaround can keep users from receiving text in a language they don't understand?</p>
| [
{
"answer_id": 314244,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 2,
"selected": false,
"text": "SELECT * CREATE TABLE ProductType (\n Id int primary key,\n NamePhraseId int, -- link to the Phrase containing the name of this product type.\n DescriptionPhraseId int\n)\n CREATE TABLE LocalizedPhrase (\n PhraseId int primary key,\n CultureCode varchar(8) primary key,\n Content nvarchar(255) -- the actual localized content\n)\n CREATE TABLE GenderedLocalizedPhrase (\n PhraseId int primary key,\n CultureCode varchar(8) primary key,\n GenderCode char(1) primary key, -- 'm', 'f' or '?' - links to Gender table\n Content nvarchar(255)\n)\n -- assume @MyCulture contains the culture code ('ca-FR') that we are looking for:\nSELECT \n Product.Id, \n Product.Name, \n\n COALESCE(ProductStatusLocalizedPhrase.Content, ProductStatusPhrase.Content) as ProductStatus, \n COALESCE(ProductTypeLocalizedPhrase.Content, ProductTypePhrase.Content) as ProductType, \n FROM Product\n\n INNER JOIN ProductStatus ON Product.StatusId = ProductStatus.Id\n INNER JOIN Phrase as ProductStatusPhrase ON ProductStatus.NamePhraseId = Phrase.Id\n LEFT JOIN LocalizedPhrase as ProductStatusLocalizedPhrase \n ON ProductStatus.NamePhraseId = ProductStatusLocalizedPhrase.Id and CultureCode = @MyCulture\n\n INNER JOIN ProductType ON Product.TypeId = ProductType.Id\n INNER JOIN Phrase as ProductTypePhrase ON ProductType.NamePhraseId = Phrase.Id\n LEFT JOIN LocalizedPhrase as ProductTypeLocalizedPhrase \n ON ProductType.NamePhraseId = ProductTypeLocalizedPhrase.Id and CultureCode = @MyCulture\n"
},
{
"answer_id": 21948179,
"author": "Neil McGuigan",
"author_id": 223478,
"author_profile": "https://Stackoverflow.com/users/223478",
"pm_score": 1,
"selected": false,
"text": "create table countries (\n country_id int primary key,\n short_name text not null unique,\n official_name text not null unique,\n iso_code char(2) not null unique\n);\n\ninsert into countries values (12, 'Algeria', 'The People''s Democratic Republic of Algeria' 'DZ');\n create table countries_t (\n country_id int not null references countries(country_id),\n short_name text not null,\n official_name text not null,\n locale varchar(5) not null,\n\n primary key (country_id, locale)\n);\n\ninsert into countries_t values\n(12, 'Algérie', 'la République algérienne démocratique et populaire', 'fr'),\n(12, 'Algerien', 'Demokratische Volksrepublik Algerien', 'de-DE');\n create view countries_i18n as \n select \n a.country_id,\n coalesce(c.short_name, b.short_name, a.short_name) as short_name, --default to countries.name if translation not found\n coalesce(c.official_name, b.official_name, a.official_name) as official_name\n countries.iso_code\n from countries a\n left join countries_t b on b.id = a.id and b.locale = current_setting('my_custom_guc.locale')\n left join countries_t c on c.id = a.id and c.locale = left(current_setting('my_custom_guc.locale'), 2); --fall-back to 2-letter locale\n SET my_custom_guc.language_code = 'de-DE';\n\nselect country_id, iso_code, short_name, official_name from countries_i18n;\n\ncountry_id iso_code short_name official_name\n-----------------------------------------------\n12 DZ Algerien Demokratische ...\n SET my_custom_guc.locale= 'fr-CA';\n\nselect country_id, iso_code, short_name, official_name from countries_i18n;\n\ncountry_id iso_code short_name official_name\n-----------------------------------------------\n12 DZ Algérie la République ...\n SET my_custom_guc.language_code = 'es';\n\nselect country_id, iso_code, short_name, official_name from countries_i18n;\n\ncountry_id iso_code short_name official_name\n-----------------------------------------------\n12 DZ Algeria The People's D ...\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23428/"
] |
314,152 | <p>Consider the following use of template template parameters...</p>
<pre><code>#include <iostream>
template <typename X>
class A
{
X _t;
public:
A(X t)
:_t(t)
{
}
X GetValue()
{
return _t;
}
};
template <typename T, template <typename T> class C >
class B
{
C<T> _c;
public:
B(T t)
:_c(t)
{
}
T GetValue()
{
return _c.GetValue();
}
};
using namespace std;
int main()
{
B<int, A> b(10);
cout<<b.GetValue();
return 0;
}
</code></pre>
<p>Is there a way by which the template parameter T can be removed? For example is there a way to make the following work?</p>
<pre><code>//Does not compile
template <template <typename T> class C >
class B
{
C _c;
public:
B(T t)
:_c(t)
{
}
T GetValue()
{
return _c.GetValue();
}
};
int main()
{
B< A<int> > b(10);
cout<<b.GetValue();
return 0;
}
</code></pre>
| [
{
"answer_id": 314177,
"author": "coryan",
"author_id": 33325,
"author_profile": "https://Stackoverflow.com/users/33325",
"pm_score": 1,
"selected": false,
"text": "template <typename C >\nstruct B\n{\n C c;\n};\n\nint main()\n{\n B< A<int> > b;\n return 0;\n}\n"
},
{
"answer_id": 314179,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "A<int> template<typename C>\nstruct B {\n C c;\n};\n\nB< A<int> > b;\n A<int> template<typename T>\nstruct A {\n template<typename U>\n struct rebind {\n typedef A<U> type;\n };\n};\n\ntemplate<typename C>\nstruct B {\n typename C::template rebind<float>::type c;\n};\n\nB< A<int> > b;\n B< A<int> >::c A<float> typename C:: ::type template C:: rebind<float>"
},
{
"answer_id": 314180,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 4,
"selected": true,
"text": "template<typename C>\nstruct B\n{\n C c;\n};\n template<typename X>\nclass A\n{\n typedef X type_name;\n X t;\n};\n C::type_name"
},
{
"answer_id": 314217,
"author": "mxg",
"author_id": 11157,
"author_profile": "https://Stackoverflow.com/users/11157",
"pm_score": 1,
"selected": false,
"text": "template <typename X>\nstruct A\n{\n X t;\n};\n\ntemplate <typename C>\nstruct B\n{\n C c;\n};\n\nint main()\n{\n B< A<int> > b;\n return 0;\n}\n b main() A int B A<int> B C A<int>"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
314,164 | <p>I am not familiar with this website but I am desperately seeking help with the website I am building. I'm sorry if I'm not in the right place or asking my question incorrectly, so please tell me if I do something wrong!</p>
<p>I have built a simple website, consisting of four pages (index.html plus three others). In FF everything seems to work fine, but in IE it doesn't. I know there are a lot of similar problems, but after hours of searching I cannot find a solution. I have a sidebar on the left, which in FF appears in place, but in IE comes up below the content. The strange thing is that on the fourth page it does work, so I'm lost as to if it is a css or html error on my account. For the time being the website is to be found at <a href="http://www.kids2move.nl/djctapas" rel="nofollow noreferrer">http://www.kids2move.nl/djctapas</a></p>
<p>I hope there is anyone out there that sees what I have done wrong and how I can fix it. I will check this page regularly so I can add additional information if needed, like my css-file or the htmlcode. Thanks in advance!!</p>
| [
{
"answer_id": 314271,
"author": "mike nvck",
"author_id": 36531,
"author_profile": "https://Stackoverflow.com/users/36531",
"pm_score": 0,
"selected": false,
"text": "<div id=page>\n <div id=content></div>\n</div>\n<div id=sidebar></div>\n <div id=page>\n <div id=sidebar></div> \n <div id=content></div>\n</div>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,165 | <p>I would like to do the following:</p>
<p>when a Sales person assigns a custom entity (let's call it 'Primary Expertise') to an Opportunity in MS CRM 4.0, the system would share the Opportunity with the user that is defined as the Owner of the associated 'Primary Expertise' record.</p>
<p>I would like to do it automatically via workflow but cannot find the workflow step that would accomplish that. Yes, and I read on some forums that it's actually not possible yet, only via a .NET assembly.</p>
<p>Experience, anyone?</p>
| [
{
"answer_id": 16037613,
"author": "shytikov",
"author_id": 1047741,
"author_profile": "https://Stackoverflow.com/users/1047741",
"pm_score": 2,
"selected": false,
"text": "var rights = AccessRights.ReadAccess | AccessRights.WriteAccess;\n\nvar principalAccess = new PrincipalAccess\n{\n // Gives the principal read write access\n AccessMask = rights,\n\n // Set the PrincipalAccess Object's Properties\n Principal = sharingTarget.Key\n};\n\n// Create the Request Object\nvar grantAcessRequest = new GrantAccessRequest();\n// Set the Request Object's properties\ngrantAcessRequest.PrincipalAccess = principalAccess;\n// Set the Target. In my case it is account record\nvar entityReference = new EntityReference(localContext.PluginExecutionContext.PrimaryEntityName,\n localContext.PluginExecutionContext.PrimaryEntityId);\n//throw new InvalidPluginExecutionException(\"EntityReference\");\ngrantAcessRequest.Target = entityReference;\n\n// Execute the Request\nlocalContext.OrganizationService.Execute(grantAcessRequest);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2706/"
] |
314,176 | <p>A cancer CT picture is stored inside a unsigned short array (1-dimensional).</p>
<p>I have the location information of the cancer region inside the picture, but the coordinates (x,y) are in superpixel (128x128 unsigned short). My task is to highlight this region. </p>
<p>I already solved this one by converting superpixel coordinates into a offset a can use for the unsigned short array. It works fine but i wonder if there is a smarter way to solve this problem, since my solution needs 3 nested for-loops.</p>
<p>Is it possible to access the ushort array "superpixelwise", so i can navigate the ushort array in superpixels.</p>
<p>I know this does not work. To give you an idea what I was thinking of:</p>
<pre><code>typedef struct
{
unsigned short[128x128]
}
spix;
spix *spixptr;
unsigned short * bufptr = img->getBuf();
spixptr = bufptr;
</code></pre>
<p><strong>Update 1:</strong></p>
<p>Yep its vague, let me try again with a picture:</p>
<pre><code>[0][1][2] ... [127]| ... [x] |
[1] | |
[2] | |
. | |
. | <-- this is a superpixel
. | |
[127] | |
-------------------- |
. |
. |
. |
[y] |<--whole picture stored in a ushort* buf = new ushort[x*y]
------------------------------
</code></pre>
<p>I like to access the 128x128 <code>ushorts</code> at once with a pointer, so I can <code>memcpy</code> data into the 128x128 field. </p>
<p><strong>Update 2:</strong></p>
<p>The bitblit transfer hint helped a lot.</p>
| [
{
"answer_id": 314204,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "typedef struct\n{\n unsigned short data[128 * 128]; // This was broken in the question.\n} spix;\n\n\nvoid spix_set_pixel(spix *s, unsigned int x, unsigned int y, unsigned short value)\n{\n s->data[y * 128 + x] = value;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40260/"
] |
314,181 | <p>Is there a way of automatically generating a HTML-Map compatible list of coordinates of polygon-like objects (e.g. countries on a map) with very distinctive borders?</p>
<p>Example image:</p>
<p><a href="http://www.bankaustria.at/landkarten/CEE_2007_w524.jpg">Map of CEE countries http://www.bankaustria.at/landkarten/CEE_2007_w524.jpg</a></p>
<p>Final output:</p>
<pre><code><map id ="ceemap" name="ceemap">
<area shape="poly" coords="149,303,162,301,162,298,171,293,180,299,169,309,159,306,148,306,149,303" href="austria.html" target ="_blank" alt="Austria" />
<!-- ... -->
</map>
</code></pre>
<p>Any tools/scripts extracting the coordinates of a polygon-like selection would be helpful.</p>
| [
{
"answer_id": 323703,
"author": "Gerhard Dinhof",
"author_id": 898,
"author_profile": "https://Stackoverflow.com/users/898",
"pm_score": 3,
"selected": false,
"text": "// input format: M 166,362.27539 C 163.525,360.86029 161.3875,359.43192 161.25,359.10124 C ...\nprivate static void Svg2map(string svg_input)\n{\n StringBuilder stringToFile = new StringBuilder();\n\n // get rid of some spaces and characters\n var workingString = svg_input.Replace(\"z\", \"\").Replace(\" M \", \"M\").Replace(\" C \", \"C\");\n // split into seperate polygons\n var polygons = workingString.Split('M');\n foreach (var polygon in polygons)\n {\n if (!polygon.Equals(String.Empty))\n {\n // each polygon is a clickable area\n stringToFile.Append(\"<area shape=\\\"poly\\\" coords=\\\"\");\n // split into point information\n var positionInformation = polygon.Split('C');\n foreach (var position in positionInformation)\n {\n var noise = position.Trim().Split(' ');\n // only the first x/y-coordinates after C are relevant\n var point = noise[0].Split(',');\n foreach (var value in point)\n {\n var valueParts = value.Split('.');\n // remove part after comma - we don't need this accurancy in HTML\n stringToFile.Append(valueParts[0]);\n // comma for seperation - don't worry, we'll clean the last ones within an area out later\n stringToFile.Append(\",\");\n }\n }\n stringToFile.AppendLine(\"\\\" href=\\\"targetpage.html\\\" alt=\\\"Description\\\" />\");\n }\n }\n // clean obsolete commas - not pretty nor efficient\n stringToFile = stringToFile.Replace(\",\\\"\", \"\\\"\");\n\n var fs = new StreamWriter(new FileStream(\"output.txt\", FileMode.Create));\n fs.Write(stringToFile.ToString());\n fs.Close();\n}\n"
},
{
"answer_id": 7858591,
"author": "njmu83",
"author_id": 1006060,
"author_profile": "https://Stackoverflow.com/users/1006060",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n/**\n * $str SVG coordinates string\n * $factor number that multiply every coordinate (0-1)\n * $x translation on the x-axis\n * $y translation on the y-axis\n */\nfunction svg2imap($str, $factor=1, $x=0, $y=0) {\n\n $res = \"\";\n\n $str = str_replace(array(\" M \",\"M \", \" C \",\" z \",\" z\"),array(\"M\",\"M\",\"C\",\"\",\"\"), $str);\n\n $polygons = explode(\"M\", $str);\n\n for($i=0; $i<count($polygons); $i++) {\n\n if($polygons[$i]!=\"\") {\n\n $res .= \"<area shape=\\\"poly\\\" coords=\\\"\";\n\n $coordinates = explode(\"C\", $polygons[$i]);\n\n foreach( $coordinates as $position ) {\n\n $noise = explode(\" \", trim($position));\n $point = explode(\",\", $noise[0]);\n\n for($j=0; $j<2; $j++) {\n\n $val = round( $point[$j]*$factor, 0);\n\n if($j==0)\n $res .= ($val + $x).\",\";\n else\n $res .= ($val + $y).\",\";\n }\n }\n $res .= \"\\\" href=\\\"link.html\\\" alt=\\\"desc\\\" />\";\n }\n }\n\n return $res = str_replace(\",\\\"\",\"\\\"\", $res);;\n}\n?>\n\n\n<?php\n\n$svg = \"M 6247.5037,5935.0511 C 6246.0707,5940.7838 6247.5037,5947.9495 C 6243.2043,5959.4149 z\";\n\nhighlight_string( svg2imap($svg, $factor=0.33, $x=0, $y=0) );\n\n?>\n"
},
{
"answer_id": 25972839,
"author": "Amir Dashti",
"author_id": 958838,
"author_profile": "https://Stackoverflow.com/users/958838",
"pm_score": 0,
"selected": false,
"text": " // Sample file contents:\n // <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n // <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n // <svg width=\"739pt\" height=\"692pt\" viewBox=\"0 0 739 692\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n // <path fill=\"#fefefe\" d=\" M 0.00 0.00 L 190.18 0.00 C 188.15 2.70 186.03 5.53 185.30 8.90 L 0.00 0.00 Z\" />\n // </svg>\n private string Svg2map(string svg_file_path)\n {\n string[] svgLines = File.ReadAllLines(svg_file_path);\n string svg = string.Join(\"\", svgLines).ToLower();\n\n int temp;\n int w = int.Parse(ExtractData(svg,0,out temp, \"<svg\", \"width\").Replace(\"pt\", \"\").Replace(\"px\", \"\"));\n int h = int.Parse(ExtractData(svg, 0, out temp, \"<svg\", \"height\").Replace(\"pt\", \"\").Replace(\"px\", \"\"));\n\n StringBuilder stringToFile = new StringBuilder();\n stringToFile.AppendLine(string.Format(\"<img id=\\\"image1\\\" src=\\\"image1.jpg\\\" border=\\\"0\\\" width=\\\"{0}\\\" height=\\\"{1}\\\" orgwidth=\\\"{0}\\\" orgheight=\\\"{1}\\\" usemap=\\\"#map1\\\" alt=\\\"\\\" />\", w, h));\n stringToFile.AppendLine(\"<map name=\\\"map1\\\" id=\\\"map1\\\">\");\n\n byte dataKey1 = (byte)'a';\n byte dataKey2 = (byte)'a';\n\n int startIndex = 0;\n int endIndex = 0;\n while (true)\n {\n string color = ExtractData(svg, startIndex, out endIndex, \"<path\", \"fill\");\n string svg_input = ExtractData(svg, startIndex, out endIndex, \"<path\", \"d=\");\n if (svg_input == null)\n break;\n\n startIndex = endIndex;\n\n /// Start..\n stringToFile.Append(string.Format(\"<area data-key=\\\"{0}{1}\\\" shape=\\\"poly\\\" href=\\\"targetpage.html\\\" alt=\\\"Description\\\" coords=\\\"\", (char)dataKey1, (char)dataKey2));\n dataKey1 += 1;\n if (dataKey1 > (byte)'z')\n {\n dataKey2 += 1;\n dataKey1 = (byte)'a';\n }\n\n bool bFinished = false;\n while (!bFinished)\n {\n string[] points = new string[0];\n string pattern = \"\";\n svg_input = svg_input.ToUpper().Trim();\n char code = svg_input[0];\n switch (code)\n {\n case 'M':\n case 'L':\n pattern = svg_input.Substring(0, svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \") + 1) + 1));\n svg_input = svg_input.Remove(0, pattern.Length);\n points = pattern.Trim().Substring(1).Trim().Split(' ');\n break;\n case 'C':\n pattern = svg_input.Substring(0, svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \", svg_input.IndexOf(\" \") + 1) + 1) + 1) + 1) + 1) + 1));\n svg_input = svg_input.Remove(0, pattern.Length);\n points = pattern.Trim().Substring(1).Trim().Split(' ');\n break;\n case 'Z':\n bFinished = true;\n continue;\n default:\n throw new Exception(\"Invalid pattern\");\n }\n\n int count = points.Length;\n if (count > 4)\n count = 4;\n for (int i = 0; i < count; i++)\n {\n var valueParts = points[i].Split('.');\n // remove part after comma - we don't need this accurancy in HTML\n stringToFile.Append(valueParts[0]);\n // comma for seperation - don't worry, we'll clean the last ones within an area out later\n stringToFile.Append(\",\");\n }\n }\n stringToFile.AppendLine(\"\\\" />\");\n }\n\n // clean obsolete commas - not pretty nor efficient\n stringToFile.AppendLine(\"</map>\");\n stringToFile = stringToFile.Replace(\",\\\"\", \"\\\"\");\n\n\n return stringToFile.ToString();\n }\n\n private string ExtractData(string data, int startIndex, out int endIndex, string key, string param)\n {\n try\n {\n endIndex = 0;\n int a = data.IndexOf(key, startIndex);\n int a2 = data.IndexOf(key, a + key.Length);\n if (a2 == -1)\n a2 = data.IndexOf(\">\", a + key.Length);\n int b = data.IndexOf(param, a + key.Length);\n int start = data.IndexOf(\"\\\"\", b + param.Length) + 1;\n int end = data.IndexOf(\"\\\"\", start + 1);\n if (b > a2 || start > a2 || end > a2)\n return null;\n int len = end - start;\n endIndex = end;\n string t = data.Substring(start, len);\n return t;\n }\n catch\n {\n endIndex = 0;\n return null;\n }\n }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898/"
] |
314,187 | <p>Here's a simplified version of my scenario:</p>
<ul>
<li>I have a table named <strong>Project</strong> that I reference via an 'id' field.</li>
<li>I have a table named <strong>Photo</strong> that has a field named 'project_id' which I use to relate multiple photos to a single project. The Photo table also has an auto-incrementing 'id' field that I use for ordering, amongst other things.</li>
</ul>
<p>Here's what I want to accomplish: <em>For a collection of Project id values, I wish to retrieve the last 5 photos added to each project</em> -- ideally in a single query, of course. :-)</p>
<p>Put another way, instead of imposing a single query limit, I would ideally like to specify a per project limit on the number of photos returned.</p>
<p>I am currently implementing this as one-query per project, so N projects = N queries (a good caching strategy will certainly reduce the hurt, but that'll come later).</p>
<p>Anyone have a solution?</p>
<p>Thanks.</p>
| [
{
"answer_id": 314207,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "Projects"
},
{
"answer_id": 314231,
"author": "philistyne",
"author_id": 16597,
"author_profile": "https://Stackoverflow.com/users/16597",
"pm_score": 0,
"selected": false,
"text": "SELECT project.*, photo.* \n FROM photo \n LEFT JOIN project USING project_id \nWHERE photo.project_id = '{$id}' \nORDER BY photo_id DESC \nLIMIT project.project_photos_limit\n"
},
{
"answer_id": 314291,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "SELECT project.*, photo.* \n FROM photo \n LEFT JOIN project USING(project_id)\nWHERE photo.project_id IN (comma separated list of project ids)\nORDER BY photo_id DESC \nLIMIT project.project_photos_limit\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40123/"
] |
314,203 | <p>Can I collapse those two "getFields" methods into one using generics (the second method is intended to package private access) or should I rename the second one into something ugly like "getFieldPackagePrivate"?</p>
<pre><code>public interface IField {
}
class Field implements IField { // package private class
}
public class IForm {
public List<IField> getFields();
}
public class Form {
private List<Field> fields;
public List<IField> getFields() {
return this.fields;
}
List<Field> getFields() { // package visible
return this.fields;
}
}
</code></pre>
<p>the basic usage would be like this</p>
<pre><code>// by interfece - from client code
IForm form;
List<IField> list = form.getFields();
// by class - from other classes in the same package
Form form2;
List<Field> list2 = forms2.getFields();
</code></pre>
<p>The idea is to have a clean, save interface for an outside world and a convenient access (without downcasts) from package visible implementation clacces. My Field Class has a few methods that I don't want do be seen by a client but need to invoke from other classes in the same packege (like for example setLabel etc.)</p>
| [
{
"answer_id": 314208,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "public List<? extends IField> getFields()\n"
},
{
"answer_id": 314365,
"author": "Łukasz Bownik",
"author_id": 24028,
"author_profile": "https://Stackoverflow.com/users/24028",
"pm_score": 0,
"selected": false,
"text": "public interface IField {\n\n}\n\n\nclass Field implements IField { // package private class\n\n}\n\n\n public class IForm {\n\n\n public List<? extends IField> getFields();\n\n }\n\n\n\npublic class Form {\n private List<Field> fields;\n\n\n List<? extends Field> getFields() { // package visible - please note \"extends Field\" not \"extends IField\"\n return this.fields;\n\n }\n\n}\n IForm form;\n List<IField> list = form.getFields();\n\n// by class - from other classes in the same package\n Form form2;\n List<Field> list2 = forms2.getFields();\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
] |
314,213 | <p>How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the 'My' structure.
Thank you.</p>
| [
{
"answer_id": 314261,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse(\"IP TO CHECK\"), YOUR_PORT_INTEGER);\nSocket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\nserver.Connect(ipep);\n Ping netMon = new Ping();\nPingResponse response = netMon.PingHost(hostname, 4);\nif (response != null)\n{\n ProcessResponse(response);\n}\n"
},
{
"answer_id": 314294,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Net;\n\nclass Program {\n\n static void Main () {\n HttpWebRequest req = WebRequest.Create(\n \"http://www.oberon.ch/\") as HttpWebRequest;\n HttpWebResponse rsp;\n try {\n rsp = req.GetResponse() as HttpWebResponse;\n } catch (WebException e) {\n if (e.Response is HttpWebResponse) {\n rsp = e.Response as HttpWebResponse;\n } else {\n rsp = null;\n }\n }\n if (rsp != null) {\n Console.WriteLine(rsp.StatusCode);\n }\n }\n\n}\n"
},
{
"answer_id": 314322,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 6,
"selected": true,
"text": "bool networkUp\n = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();\n NetworkInterface[] networkCards\n = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();\n"
},
{
"answer_id": 1227079,
"author": "CCrawford",
"author_id": 149411,
"author_profile": "https://Stackoverflow.com/users/149411",
"pm_score": 4,
"selected": false,
"text": "System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged NetworkChange.NetworkAvailabilityChanged \n += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);\n_isNetworkOnline = NetworkInterface.GetIsNetworkAvailable();\n\n\n// ...\nvoid NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)\n{\n _isNetworkOnline = e.IsAvailable;\n}\n"
},
{
"answer_id": 27591022,
"author": "akuma6099",
"author_id": 4382901,
"author_profile": "https://Stackoverflow.com/users/4382901",
"pm_score": -1,
"selected": false,
"text": "Imports System.Net\n\nPublic Module Network_Monitor\n\nPrivate InsideWorkNet As Boolean = vbFalse\nPrivate Online_Status As Boolean = vbFalse\nPrivate CurrentWorkIPAddress As New IPHostEntry\nPrivate WithEvents Timer_Online_Check As New Timers.Timer With {.Interval = 5000, .Enabled = True, .AutoReset = True}\n\n\nPublic ReadOnly Property GetOnlineStatus() As String\n\n Get\n Return Online_Status\n End Get\n\nEnd Property\n\n\nPublic Sub Initialize()\n\n Set_Online_Status()\n Timer_Online_Check.Start()\n\nEnd Sub\n\n\nPublic Sub Set_Online_Status()\n\n If My.Computer.Network.IsAvailable Then\n Try\n Dim DNSTest As IPHostEntry = Dns.GetHostEntry(\"google.com\")\n If DNSTest.AddressList.Length > 0 Then\n Online_Status = True\n Else : Online_Status = False\n\n End If\n\n Catch ex As System.Net.Sockets.SocketException\n\n Online_Status = False\n\n End Try\n End If\n\nEnd Sub\n\n\nPrivate Sub Timer_Online_Check_Elaspsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs) Handles Timer_Online_Check.Elapsed\n Set_Online_Status()\nEnd Sub\n\nPublic Sub Detect_Work_Network()\n\n If Online_Status = True Then\n\n Dim WorkIP As IPHostEntry = New IPHostEntry()\n\n Try\n WorkIP = Dns.GetHostEntry(\"serverA.myworkdomain.local\")\n If WorkIP.AddressList.Length > 0 Then\n\n InsideWorkNet = True\n CurrentWorkIPAddress = WorkIP\n 'MessageBox.Show(WorkIP.HostName.ToString(), \"WorkIP\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n End If\n Catch ex As Sockets.SocketException\n\n Try\n WorkIP = Dns.GetHostEntry(\"serverA.myworkdomain.com\")\n If WorkIP.AddressList.Length > 0 Then\n\n InsideWorkNet = False\n CurrentWorkIPAddress = WorkIP\n ' MessageBox.Show(WorkIP.HostName.ToString(), \"WorkIP\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n End If\n Catch ey As Sockets.SocketException\n\n End Try\n End Try\n End If\n\nEnd Sub\n\nPublic Function GetWorkServerName() As String\n If InsideWorkNet = True Then\n Return \"serverA.myworkdomain.local\"\n Else : Return \"serverA.myworkdomain.com\"\n End If\n\n\nEnd Function\n\n\n\nEnd Module\n"
},
{
"answer_id": 34494351,
"author": "Amit Kumawat",
"author_id": 4140166,
"author_profile": "https://Stackoverflow.com/users/4140166",
"pm_score": 2,
"selected": false,
"text": "if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())\n{\n //Do your stuffs when network available\n\n}\nelse\n{\n //Do stuffs when network not available\n\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37350/"
] |
314,232 | <p>I have a DateTime object that I need to print in a custom gridlike control.
The type of the data I want to print is a date in the format dd-mm-yyyy.
This value can be either filled or blank.
If it's filled it will be parsed into a <code>DateTime</code> and then printed as the default <code>ToString</code>.</p>
<p>For each row, I can use</p>
<pre><code><CellTemplate>
<asp:Literal ID="Literal2" runat="server" Text="<%# Container.Value %>"></asp:Literal>
</CellTemplate>
</code></pre>
<p>But this prints the default long version of the date. I'd like the format from <code>ToShortDateString()</code>.</p>
<p>So I tried modifying to:</p>
<pre><code><CellTemplate>
<asp:Literal ID="Literal2" runat="server" Text="<%# Convert.ToDateTime(Container.Value).ToShortTimeString()%>"></asp:Literal>
</CellTemplate>
</code></pre>
<p>This works as intended.</p>
<p>Now I have a problem with empty dates,</p>
<pre><code>Convert.ToDateTime()
</code></pre>
<p>On an empty string, it will print the default DateTime.</p>
<p>Is there a way that I can fashion an If-Statement in my aspx code, to only perform <code>Convert.ToDateTime</code>, if it's not an empty string?</p>
| [
{
"answer_id": 314263,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": true,
"text": "Container.Value.Length > 0 ? Convert.ToDateTime(Container.Value).ToShortTimeString() : \"\"\n Container.Value"
},
{
"answer_id": 314266,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 0,
"selected": false,
"text": "protected static string ConvertDate(object date) {\n if (date == null)\n return string.Empty;\n return Convert.ToDateTime(date).ToShortTimeString();\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40274/"
] |
314,245 | <p>I have this code:</p>
<pre><code>db = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\baywotch.db5"
TextExportFile = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblAuction1"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
</code></pre>
<p>Which is meant to connect to an access database and produce a tab delimited text file. tblAuction1 is a query in the database, and definitly exists and is not misspelt in any way, but I get an error that it cannot be found or does not exist. When I change it to tblAuction which is the name of the table, I get an error stating f.WriteLine a has been called incorrectly.</p>
<p>edit: I now only get a problem with f.writeline a, saying an incorrect argument has been supplied. I no longer have a problem with tblAuction1</p>
<p>edit: the sql code used for my query:</p>
<pre><code>SELECT tblAuction.article_no, tblAuction.article_name, tblAuction.subtitle, tblAuction.current_bid, tblAuction.start_price, tblAuction.bid_count, tblAuction.quant_total, tblAuction.quant_sold, tblAuction.start, tblAuction.ends, tblAuction.origin_end, tblUser.user_name, tblAuction.best_bidder_id, tblAuction.finished, tblAuction.watch, tblAuction.buyitnow_price, tblAuction.pic_url, tblAuction.private_auction, tblAuction.auction_type, tblAuction.insert_date, tblAuction.update_date, tblAuction.cat_1_id, tblAuction.cat_2_id, tblAuction.article_desc, tblAuction.countrycode, tblAuction.location, tblAuction.condition, tblAuction.revised, tblAuction.paypal_accept, tblAuction.pre_terminated, tblAuction.shipping_to, tblAuction.fee_insertion, tblAuction.fee_final, tblAuction.fee_listing, tblAuction.pic_xxl, tblAuction.pic_diashow, tblAuction.pic_count, tblAuction.item_site_id
FROM tblUser INNER JOIN tblAuction ON tblUser.id = tblAuction.seller_id;
</code></pre>
| [
{
"answer_id": 314285,
"author": "Daniel Kreiseder",
"author_id": 31406,
"author_profile": "https://Stackoverflow.com/users/31406",
"pm_score": 0,
"selected": false,
"text": "cn.Provider = \"Microsoft.Jet.OLEDB.4.0\"\ncn.ConnectionString = db\ncn.Open\n"
},
{
"answer_id": 315291,
"author": "Tester101",
"author_id": 38695,
"author_profile": "https://Stackoverflow.com/users/38695",
"pm_score": 0,
"selected": false,
"text": "\ncn.Open _\n \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Persist Security Info=False;\" & _\n \"Data Source=\" & db\n"
},
{
"answer_id": 318765,
"author": "KeesDijk",
"author_id": 6434,
"author_profile": "https://Stackoverflow.com/users/6434",
"pm_score": 3,
"selected": true,
"text": "Set f = fs.CreateTextFile(TextExportFile, True, True)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
314,254 | <p>I'm looking for way to grab the content of my opengl (as UIImage) and then save it into a file. I'm now giving glReadPixels a try though I'm not sure I'm doing the right thing as of what kind of malloc I should be doing. I gather that on OSX it's GL_BGRA but on the iPhone that doesn't work...</p>
| [
{
"answer_id": 314337,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": "GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES \n"
},
{
"answer_id": 3333682,
"author": "Alastair Stuart",
"author_id": 102793,
"author_profile": "https://Stackoverflow.com/users/102793",
"pm_score": 1,
"selected": false,
"text": "-(UIImage *) snapshot {\n NSInteger myDataLength = backingWidth * backingHeight * 4;\n // allocate array and read pixels into it.\n GLubyte *buffer = (GLubyte *) malloc(myDataLength);\n glReadPixels(0, 0, backingWidth, backingHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);\n // gl renders \"upside down\" so swap top to bottom into new array.\n // there's gotta be a better way, but this works.\n GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);\n for(int y = 0; y <backingHeight; y++)\n {\n for(int x = 0; x <backingWidth * 4; x++)\n {\n buffer2[((backingHeight - 1) - y) * backingWidth * 4 + x] = buffer[y * 4 * backingWidth + x];\n }\n }\n free(buffer);\n // make data provider with data.\n CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);\n // prep the ingredients\n int bitsPerComponent = 8;\n int bitsPerPixel = 32;\n int bytesPerRow = 4 * backingWidth;\n CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();\n CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;\n CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;\n // make the cgimage\n CGImageRef imageRef = CGImageCreate(backingWidth, backingHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);\n // then make the uiimage from that\n UIImage *myImage = [UIImage imageWithCGImage:imageRef];\n return myImage;\n}\n -(void) saveImage:(UIImage *)image {}\n // Create paths to output images\n NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@\"Documents/Test.png\"];\n NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@\"Documents/Test.jpg\"];\n\n // Write a UIImage to JPEG with minimum compression (best quality)\n // The value 'image' must be a UIImage object\n // The value '1.0' represents image compression quality as value from 0.0 to 1.0\n [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];\n\n // Write image to PNG\n [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,256 | <p>My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?</p>
<p>This is my non-working attempt so far. I see no result whatsoever.</p>
<pre><code>NSRect frame = NSMakeRect(0, 0, 200, 200);
NSUInteger styleMask = NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window = [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window display];
</code></pre>
| [
{
"answer_id": 314308,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 2,
"selected": false,
"text": "NSRect frame = NSMakeRect(100, 100, 200, 200);\nNSUInteger styleMask = NSBorderlessWindowMask;\nNSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];\nNSWindow * window = [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered defer:false];\n[window setBackgroundColor:[NSColor blueColor]];\n[window makeKeyAndOrderFront: window];\n"
},
{
"answer_id": 314310,
"author": "Rich Catalano",
"author_id": 4103,
"author_profile": "https://Stackoverflow.com/users/4103",
"pm_score": 3,
"selected": false,
"text": "[window makeKeyAndOrderFront:self]; \n [window display];\n"
},
{
"answer_id": 314311,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 8,
"selected": true,
"text": "display makeKeyAndOrderFront orderFront NSBackingStoreBuffered NSRect frame = NSMakeRect(0, 0, 200, 200);\nNSWindow* window = [[[NSWindow alloc] initWithContentRect:frame\n styleMask:NSBorderlessWindowMask\n backing:NSBackingStoreBuffered\n defer:NO] autorelease];\n[window setBackgroundColor:[NSColor blueColor]];\n[window makeKeyAndOrderFront:NSApp];\n\n//Don't forget to assign window to a strong/retaining property!\n//Under ARC, not doing so will cause it to disappear immediately;\n// without ARC, the window will be leaked.\n makeKeyAndOrderFront orderFront"
},
{
"answer_id": 5972566,
"author": "johndpope",
"author_id": 284895,
"author_profile": "https://Stackoverflow.com/users/284895",
"pm_score": 5,
"selected": false,
"text": "#import \"AppDelegate.h\":\n\nint main(int argc, char *argv[])\n{\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n [NSApplication sharedApplication];\n\n AppDelegate *appDelegate = [[AppDelegate alloc] init];\n [NSApp setDelegate:appDelegate];\n [NSApp run];\n [pool release];\n return 0;\n}\n"
},
{
"answer_id": 59137260,
"author": "Jeff Younker",
"author_id": 956269,
"author_profile": "https://Stackoverflow.com/users/956269",
"pm_score": 3,
"selected": false,
"text": "var mainWindow: NSWindow!\n\n...\n\nmainWindow = NSWindow(\n contentRect: NSMakeRect(0, 0, 200, 200),\n styleMask: [.titled, .resizable, .miniaturizable, .closable],\n backing: .buffered,\n defer: false)\nmainWindow.backgroundColor = .blue\nmainWindow.makeKeyAndOrderFront(mainWindow)\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
] |
314,258 | <p>I'm creating some big files (DB exports) with Java and I need to put them somewhere on our SharePoint server. Right now, I'm doing this with IE but I'd like to automate this step, too.</p>
<p>I searched the web and I found some hints to use SOAP but I don't really see to the ground of all this, yet. Can someone provide me with some sample code or a recipe what I need to do?</p>
<p>Please note: the SharePoint server asks for NT domain authentication. I can't even login with Firefox :(</p>
<p><strong>EDIT</strong></p>
<ul>
<li>How do I convert the scary URL in IE into a WebDAV path?</li>
<li>Is there a WebDAV "explorer" which I can use before I ruin the production system with my code? I tried "DAV Explorer 0.91" from <a href="http://www.davexplorer.org/" rel="noreferrer">http://www.davexplorer.org/</a> but that can't connect (probably because of NT domain auth).</li>
</ul>
| [
{
"answer_id": 314477,
"author": "dariom",
"author_id": 12389,
"author_profile": "https://Stackoverflow.com/users/12389",
"pm_score": 3,
"selected": false,
"text": "http://<Site>/_vti_bin/ http://<Site>/_vti_bin/Lists.asmx http://<Site>/_vti_bin/Lists.asmx?WSDL UpdateListItems AddAttachment http://<Site>/Foo/BarDocs/Forms/AllItems.aspx \\\\<Site>\\Foo\\BarDocs"
},
{
"answer_id": 16188830,
"author": "DMEx38",
"author_id": 584142,
"author_profile": "https://Stackoverflow.com/users/584142",
"pm_score": 2,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.httpcomponents</groupId>\n <artifactId>httpclient</artifactId>\n <version>4.2.3</version>\n</dependency>\n <dependency>\n <groupId>jcifs</groupId>\n <artifactId>jcifs</artifactId>\n <version>1.3.17</version>\n</dependency>\n public final class JCIFSEngine implements NTLMEngine {\n\n private static final int TYPE_1_FLAGS =\n NtlmFlags.NTLMSSP_NEGOTIATE_56\n | NtlmFlags.NTLMSSP_NEGOTIATE_128\n | NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2\n | NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n | NtlmFlags.NTLMSSP_REQUEST_TARGET;\n\n @Override\n public String generateType1Msg(final String domain, final String workstation)\n throws NTLMEngineException {\n final Type1Message type1Message = new Type1Message(TYPE_1_FLAGS, domain, workstation);\n return Base64.encode(type1Message.toByteArray());\n }\n\n @Override\n public String generateType3Msg(final String username, final String password,\n final String domain, final String workstation, final String challenge)\n throws NTLMEngineException {\n Type2Message type2Message;\n try {\n type2Message = new Type2Message(Base64.decode(challenge));\n } catch (final IOException exception) {\n throw new NTLMEngineException(\"Invalid NTLM type 2 message\", exception);\n }\n final int type2Flags = type2Message.getFlags();\n final int type3Flags = type2Flags\n & (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));\n final Type3Message type3Message = new Type3Message(type2Message, password, domain,\n username, workstation, type3Flags);\n return Base64.encode(type3Message.toByteArray());\n }\n}\n try {\n\n HttpParams params = new BasicHttpParams();\n HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);\n DefaultHttpClient httpclient = new DefaultHttpClient(params);\n\n //Register JCIF NTLMv2 to manage ntlm auth.\n httpclient.getAuthSchemes().register(\"ntlm\", new AuthSchemeFactory() {\n @Override\n public AuthScheme newInstance(HttpParams hp) {\n return new NTLMScheme(new JCIFSEngine());\n }\n });\n\n //Provide login/password\n httpclient.getCredentialsProvider().setCredentials(\n AuthScope.ANY,\n new NTCredentials([LOGIN], [PASSWORD], \"\", [DOMAIN]));\n //Create HTTP PUT Request \n HttpPut request = new HttpPut(\"http://[server]/[site]/[folder]/[fileName]\");\n request.setEntity(new FileEntity([File])); \n\n return httpclient.execute(request);\n\n } catch (IOException ex) {\n //...\n }\n"
},
{
"answer_id": 46325262,
"author": "Monkey D. Luffy",
"author_id": 6623509,
"author_profile": "https://Stackoverflow.com/users/6623509",
"pm_score": 2,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.httpcomponents</groupId>\n <artifactId>httpclient</artifactId>\n <version>4.5</version>\n</dependency>\n /* OAuth2 authentication to get access token */\npublic String getSharePointAccessToken() throws ClientProtocolException, IOException\n{\n /* Initializing variables */\n String grant_type = RcConstants.GRANT_TYPE;\n String client_id = RcConstants.CLIENT_ID;\n String client_secret = RcConstants.CLIENT_SECRET;\n String resource = RcConstants.RESOURCE;\n String url = RcConstants.OAUTH_URL + RcConstants.URL_PARAMETER + \"/tokens/OAuth/2\";\n\n /*\n * NOTE: RcConstants.OAUTH_URL =\n * https://accounts.accesscontrol.windows.net/ RcConstants.URL_PARAMETER\n * = Bearer Realm from\n * (http://www.ktskumar.com/2017/01/access-sharepoint-online-using-\n * postman/) Figure 6.\n */\n\n /* Building URL */\n HttpClient client = HttpClientBuilder.create().build();\n HttpPost post = new HttpPost(url);\n post.setHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n /* Adding URL Parameters */\n List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();\n urlParameters.add(new BasicNameValuePair(\"grant_type\", grant_type));\n urlParameters.add(new BasicNameValuePair(\"client_id\", client_id));\n urlParameters.add(new BasicNameValuePair(\"client_secret\", client_secret));\n urlParameters.add(new BasicNameValuePair(\"resource\", resource));\n post.setEntity(new UrlEncodedFormEntity(urlParameters));\n\n /* Executing the post request */\n HttpResponse response = client.execute(post);\n logger.debug(\"Response Code : \" + response.getStatusLine().getStatusCode());\n\n String json_string = EntityUtils.toString(response.getEntity());\n JSONObject temp1 = new JSONObject(json_string); \n if (temp1 != null)\n {\n /* Returning access token */\n return temp1.get(\"access_token\").toString();\n }\n return RcConstants.OAUTH_FAIL_MESSAGE;\n}\n public String putRecordInSharePoint(File file) throws ClientProtocolException, IOException\n{\n /* Token variable declaration */\n String token = getSharePointAccessToken();\n /* Null or fail check */\n if (!token.equalsIgnoreCase(RcConstants.OAUTH_FAIL_MESSAGE))\n { \n /* Upload path and file name declaration */\n String Url_parameter = \"Add(url='\" + file.getName() + \"',overwrite=true)\";\n String url = RcConstants.UPLOAD_FOLDER_URL + Url_parameter;\n /*\n * NOTE: RcConstants.UPLOAD_FOLDER_URL =\n * https://<your_domain>.sharepoint.com/_api/web/\n * GetFolderByServerRelativeUrl('/Shared%20Documents/<FolderName>')/\n * Files/\n */\n\n /* Building URL */\n HttpClient client = HttpClientBuilder.create().build();\n HttpPost post = new HttpPost(url);\n post.setHeader(\"Authorization\", \"Bearer \" + token);\n post.setHeader(\"accept\", \"application/json;odata=verbose\");\n /* Declaring File Entity */\n post.setEntity(new FileEntity(file));\n\n /* Executing the post request */\n HttpResponse response = client.execute(post);\n logger.debug(\"Response Code : \" + response.getStatusLine().getStatusCode());\n\n if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()|| response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value())\n {\n /* Returning Success Message */\n return RcConstants.UPLOAD_SUCCESS_MESSAGE;\n }\n else\n {\n /* Returning Failure Message */\n return RcConstants.UPLOAD_FAIL_MESSAGE;\n }\n }\n return token;\n}\n"
},
{
"answer_id": 50742679,
"author": "go4X",
"author_id": 9908845,
"author_profile": "https://Stackoverflow.com/users/9908845",
"pm_score": 2,
"selected": false,
"text": "public class HttpClient { \n HttpClient() { }\n\n public static void download(final String source, final File resultingFile) {\n CloseableHttpClient client = WinHttpClients.createSystem();\n HttpGet httpRequest = new HttpGet(source);\n\n CloseableHttpResponse httpResponse = null; \n try {\n httpResponse = client.execute(httpRequest);\n HttpEntity entity = httpResponse.getEntity();\n\n if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {\n LOGGER.warn(httpResponse.getStatusLine());\n }else { \n LOGGER.debug(httpResponse.getStatusLine());\n FileUtils.touch(resultingFile);\n InputStream is = entity.getContent(); \n File outFile = new File(resultingFile.getAbsolutePath());\n FileOutputStream fos = new FileOutputStream(outFile);\n\n int inByte;\n while ((inByte = is.read()) != -1) {\n fos.write(inByte);\n }\n is.close();\n fos.close(); \n client.close();\n }\n } catch (ClientProtocolException e) {\n LOGGER.warn(e);\n } catch (UnsupportedOperationException e) {\n LOGGER.warn(e);\n } catch (IOException e) {\n LOGGER.warn(e);\n }\n }\n\n\n public static void upload(final File source, final String destination) { \n CloseableHttpClient httpclient = WinHttpClients.createSystem();\n HttpPut httpRequest = new HttpPut(destination);\n httpRequest.setEntity(new FileEntity(new File(source.getPath())));\n\n CloseableHttpResponse httpResponse = null;\n try {\n httpResponse = httpclient.execute(httpRequest);\n EntityUtils.consume(httpResponse.getEntity());\n\n if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {\n LOGGER.debug(httpResponse.getStatusLine());\n LOGGER.info(\"Upload of \" + source.getName() + \" via HTTP-Client succeeded.\");\n } else if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {\n LOGGER.debug(httpResponse.getStatusLine());\n }else {\n LOGGER.warn(\"Uploading \" + source.getName() + \" failed.\");\n LOGGER.warn(httpResponse.getStatusLine().getStatusCode() + \": \" + httpResponse.getStatusLine().getReasonPhrase());\n }\n } catch (IOException e) {\n LOGGER.warn(e);\n LOGGER.warn(e.getMessage());\n } \n return;\n }\n}\n <dependency>\n <groupId>org.apache.httpcomponents</groupId>\n <artifactId>httpclient-win</artifactId>\n <version>4.4</version>\n </dependency> \n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34088/"
] |
314,268 | <p>I have an application that needs to send a moderately high volume of messages between a number of AppDomains. I know that I could implement this using remoting, but I have also noticed that there are cross-domain delegates. Has anyone looked at this kind of problem?</p>
| [
{
"answer_id": 11071232,
"author": "notmii",
"author_id": 1260962,
"author_profile": "https://Stackoverflow.com/users/1260962",
"pm_score": 3,
"selected": false,
"text": "static void RunInChildDomain()\n{\n AppDomain childDomain = AppDomain.CreateDomain(\"friendlyName\");\n string parameterValue = \"notmii\";\n childDomain.SetData(\"parameter\", parameterValue);\n childDomain.DoCallBack(PrintName);\n}\n\nstatic void PrintName()\n{\n string Name = Convert.ToString(AppDomain.CurrentDomain.GetData(\"parameter\"));\n Console.WriteLine(Name);\n}\n"
},
{
"answer_id": 51641532,
"author": "V. S.",
"author_id": 10014202,
"author_profile": "https://Stackoverflow.com/users/10014202",
"pm_score": 3,
"selected": false,
"text": " CallContext.LogicalSetData(\"Key\", \"My value\");\n Console.WriteLine(\"{0} from {1}\", CallContext.LogicalGetData(\"Key\"), \n AppDomain.CurrentDomain.FriendlyName);\n\n var appDomain = AppDomain.CreateDomain(\"Worker\");\n appDomain.DoCallBack(() => Console.WriteLine(\"{0} from {1}\", \n CallContext.LogicalGetData(\"Key\"), \n AppDomain.CurrentDomain.FriendlyName));\n AppDomain.Unload(appDomain);\n\n CallContext.FreeNamedDataSlot(\"Key\");\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21686/"
] |
314,275 | <p>I am running a java program that sets up a database connection to an SQL database. It works fine on Mac OS X, but when I try to run the same code on Linux, I get a Exception in thread "main" java.lang.NoClassDefFoundError: java/sql/SQLClientInfoException.</p>
<p>I am using jdk-1.6.0_02 - if I unzip src.zip, it turns out that SQLClientInfoException.java is not contained therein.</p>
<p>Also, the API documentation shows that there are exactly two methods that use this exception, both in java.sql.Connection. However, if I look at both methods in the source code, both of them seem to throw the more general SQLException instead.</p>
<p>Is that a bug in my java version or am I doing something wrong?</p>
| [
{
"answer_id": 314325,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 2,
"selected": true,
"text": "jdk1.6.0_03 jdk1.6.0_06"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,277 | <p>I am getting an vba error 3271; Invalid property value. This happens when trying to append a memo field in a querydef. Any ideas on how to get around this?</p>
<p>Example:</p>
<pre><code>public sub TestMemoField
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("AppendRecord")
qdf.Parameters("@SomeBigText").value = string(1000,"A")
qdf.Execute
end sub
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 314486,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "qdf.SQL=\"INSERT INTO Sometable (SomeField) Values('\" & String(1000, \"A\") & \"')\"\n"
},
{
"answer_id": 316217,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": -1,
"selected": false,
"text": "Public Sub TestMemoField\n Dim strSQL As String\n\n strSQL = \"UPDATE MyTable SET MyField='\" & String(1000,\"A\") & \"'\"\n CurrentDb.Execute strSQL, dbFailOnError\nEnd Sub\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37797/"
] |
314,300 | <p>I would like to upload files from java application/applet using POST http event. I would like to avoid to use any library not included in SE, unless there is no other (feasible) option. <br>
So far I come up only with very simple solution. <br>
- Create String (Buffer) and fill it with compatible header (<a href="http://www.ietf.org/rfc/rfc1867.txt" rel="nofollow noreferrer">http://www.ietf.org/rfc/rfc1867.txt</a>)<br>
- Open connection to server URL.openConnection() and write content of this file to OutputStream. <br>
I also need to manually convert binary file into POST event. <br><br>
I hope there is some better, simpler way to do this?</p>
| [
{
"answer_id": 324046,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "java.net.URL java.net.URLConnection public void post(String url) throws Exception {\n URL u = new URL(url);\n URLConnection c = u.openConnection();\n\n c.setDoOutput(true);\n if (c instanceof HttpURLConnection) {\n ((HttpURLConnection)c).setRequestMethod(\"POST\");\n }\n\n OutputStreamWriter out = new OutputStreamWriter(\n c.getOutputStream());\n\n // output your data here\n\n out.close();\n\n BufferedReader in = new BufferedReader(\n new InputStreamReader(\n c.getInputStream()));\n\n String s = null;\n while ((s = in.readLine()) != null) {\n System.out.println(s);\n }\n in.close();\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40271/"
] |
314,301 | <p>I am creating a large table dynamically using Javascript.
I have realised the time taken to add a new row grows exponentially as the number of rows increase.</p>
<p>I suspect the Page is getting refreshed in each loop per row (I am also adding input elements of type text on each cell)</p>
<p>Is there a way to stop the page "refreshing" until I am done with the whole table?</p>
<p>Any suggestion on how to do this or go around it?</p>
<hr>
<p>I have tried all the suggestions above, but I am still getting the performance bottlenecks.</p>
<p>I tried to analyse line after line, and I have noted that document.getElementById() is one of the lines taking a lot of time to execute when the table is very large.
I am using getElementById() to dynamically access an HTML input of type text loaded on each cell of the table.</p>
<p>Any ideas on which DOM method I should use instead of getElementById()?</p>
| [
{
"answer_id": 314326,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 2,
"selected": false,
"text": "var theTable = document.createElement(\"table\");\n// ... \n// add all the rows to theTable\n// ...\ndocument.body.appendChild(theTable);\n"
},
{
"answer_id": 316714,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 0,
"selected": false,
"text": "table-layout:fixed"
},
{
"answer_id": 325737,
"author": "Julius A",
"author_id": 13370,
"author_profile": "https://Stackoverflow.com/users/13370",
"pm_score": 1,
"selected": true,
"text": "E.g.\nthisTable = document.getElementByID('mytable');//get the table\noneRow = thisTable.rows[0].cells; //for instance the first row\nfor (var colCount = 0; colCount <totalCols; colCount ++)\n{\n oneCell =oneRow[colCount];\n oneCell.childNodes[0].value = 'test';//if your cell contains an input element\n oneCell.innerHTML = 'test'; // simply write on the cell directly\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
314,305 | <p>I am using Oracle BPEL Process manager and have a task assigned to a group of users.
I try to mark it approved using Java class oracle.bpel.services.workflow.task.ITaskService.updateTaskOutcome(). This works if the task is assigned to an individual user, but if the task is assigned to a group of users, I get an error message about the task not being acquired. </p>
<p>If I acquire the task using oracle.bpel.services.workflow.task.ITaskService.acquireTask(), I get an error message when trying to mark it approved: "The task has been acquired by some other user".</p>
<p>Can anybody point to sample code that changes status of an Oracle BPEL task <em>assigned to a group</em> programmatically?</p>
| [
{
"answer_id": 1558200,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "updateTaskOutcomes() updateTaskOutcome()"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9363/"
] |
314,307 | <p>I have two tables: a source table and a target table. The target table will have a subset of the columns of the source table. I need to update a single column in the target table by joining with the source table based on another column. The update statement is as follows:</p>
<pre><code>UPDATE target_table tt
SET special_id = ( SELECT source_special_id
FROM source_table st
WHERE tt.another_id = st.another_id )
</code></pre>
<p>For some reason, this statement seems to run indefinitely. The inner select happens almost immediately when executed by itself. The table has roughly 50,000 records and its hosted on a powerful machine (resources are not an issue). </p>
<p>Am I doing this correctly? Any reasons the above wouldn't work in a timely manner? Any better way to do this?</p>
| [
{
"answer_id": 314330,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 4,
"selected": true,
"text": "UPDATE target_table \nSET special_id = st.source_special_id\nFROM \n target_table tt\n INNER JOIN\n source_table st\n WHERE tt.another_id = st.another_id \n UPDATE target_table \nSET special_id = st.source_special_id\nFROM \n target_table tt, source_table st\nWHERE tt.another_id = st.another_id \n"
},
{
"answer_id": 314439,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "UPDATE target_table tt\nSET special_id = ( SELECT source_special_id\n FROM source_table st\n WHERE tt.another_id = st.another_id )\nWHERE EXISTS( SELECT NULL\n FROM source_table st\n WHERE tt.another_id = st.another_id );\n UPDATE\n ( SELECT tt.primary_key, tt.special_id, st.source_special_id\n FROM tatget_table tt\n JOIN source_table st ON st.another_id = tt.another_id\n )\nSET special_id = source_special_id;\n"
},
{
"answer_id": 4472365,
"author": "Martin McNulty",
"author_id": 4507,
"author_profile": "https://Stackoverflow.com/users/4507",
"pm_score": 0,
"selected": false,
"text": "MERGE MERGE INTO target_table tt\nUSING source_table st\nON (tt.another_id = st.another_id)\nWHEN MATCHED THEN\n UPDATE SET tt.special_id = st.special_id;\n another_id source_table WHEN NOT MATCHED THEN"
},
{
"answer_id": 14484324,
"author": "Matt McPeak",
"author_id": 2004636,
"author_profile": "https://Stackoverflow.com/users/2004636",
"pm_score": 0,
"selected": false,
"text": "UPDATE ( SELECT tt.rowid tt_rowid, tt.another_id, tt.special_id, st.source_special_id\n FROM target_table tt, source_table st\n WHERE tt.another_id = st.other_id\n ORDER BY tt.rowid ) \nSET special_id = source_special_id\n ROWID"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
] |
314,313 | <p>I use Jasper reports with the <a href="http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatView.html" rel="nofollow noreferrer">JasperReportsMultiFormatView</a> class provided by the Spring framework. This class takes care of compiling the source .jrxml files to their compiled .jasper format when the Spring application context is created.</p>
<p>However, this compilation process is really slowing down the application startup time. Is it possible for the reports to be lazily compiled instead of compiled at startup time, i.e. a report is only compiled the first time it is requested?</p>
<p>If this is not possible, alternative suggestions for how I can reduce/eliminate the report compilation time would be welcome. Of course, I could mandate that the compiled reports must be checked into SVN along with the .jrxml files, but it's only a matter of time, before someone (most likely me) forgets.</p>
<p>Cheers,
Don</p>
| [
{
"answer_id": 14611708,
"author": "andrewps",
"author_id": 2022484,
"author_profile": "https://Stackoverflow.com/users/2022484",
"pm_score": 1,
"selected": false,
"text": "import net.sf.jasperreports.engine.JasperReport;\nimport org.apache.log4j.Logger;\nimport org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView;\n\npublic class DynamicJasperReportsMultiFormatView extends JasperReportsMultiFormatView {\n\nprivate static final Logger LOG = Logger.getLogger(DynamicJasperReportsMultiFormatView.class);\n\n/**\n * The JasperReport that is used to render the view.\n */\nprivate JasperReport jasperReport;\n\n/**\n * The last modified time of the jrxml resource file, used to force compilation.\n */\nprivate long jrxmlTimestamp;\n\n@Override\nprotected void onInit() {\n jasperReport = super.getReport();\n\n try {\n String url = getUrl();\n if (url != null) {\n jrxmlTimestamp = getApplicationContext().getResource(url).getFile().lastModified();\n }\n } catch (Exception e) {\n e = null;\n }\n}\n\n@Override\nprotected JasperReport getReport() {\n if (this.isDirty()) {\n LOG.info(\"Forcing recompilation of jasper report as the jrxml has changed\");\n this.jasperReport = this.loadReport();\n }\n return this.jasperReport;\n}\n\n/**\n * Determines if the jrxml file is dirty by checking its timestamp.\n *\n * @return true to force recompilation because the report xml has changed, false otherwise\n */\nprivate boolean isDirty() {\n long curTimestamp = 0L;\n try {\n String url = getUrl();\n if (url != null) {\n curTimestamp = getApplicationContext().getResource(url).getFile().lastModified();\n if (curTimestamp > jrxmlTimestamp) {\n jrxmlTimestamp = curTimestamp;\n return true;\n }\n }\n } catch (Exception e) {\n e = null;\n }\n return false;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
314,314 | <p>I have a rather large (many gigabytes) table of data in SQL Server that I wish to move to a table in another database on the same server.</p>
<p>The tables are the same layout.</p>
<p>What would be the most effecient way of going about doing this?</p>
<p>This is a one off operation so no automation is required.</p>
<p>Many thanks.</p>
| [
{
"answer_id": 314338,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "SELECT * INTO OtherDatabase..NewTable FROM ThisDatabase..OldTable\n INSERT OtherDatabase..NewTable\nSELECT * FROM ThisDatabase..OldTable\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770/"
] |
314,321 | <p>I've looked this up a thousand times, and I always forget it, so, here for eternity:</p>
<p>Solaris has a bit of an awkward syntax for <code>tail</code>.</p>
<p>How do I do the equivalent of BSD's <code>tail -n<i>N</i></code>?</p>
<p>What I want are the last N lines from tail's input.</p>
| [
{
"answer_id": 314341,
"author": "Ulf Lindback",
"author_id": 30354,
"author_profile": "https://Stackoverflow.com/users/30354",
"pm_score": 5,
"selected": true,
"text": "tail -100\n"
},
{
"answer_id": 314367,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "/usr/xpg4/bin/tail\n tail -nN"
},
{
"answer_id": 50397907,
"author": "Sasha Golikov",
"author_id": 6788478,
"author_profile": "https://Stackoverflow.com/users/6788478",
"pm_score": 0,
"selected": false,
"text": "tail -n 10 sed -e :a -e '$q;N;11,$D;ba' file\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] |
314,329 | <p>OK, this is my own fault, but I can't seem to rescue myself.</p>
<p>Whenever I try to step into a class that has fields with assignments calling into .NET code, I get a dialog box that contains the text "There is no source code available for the current location.":</p>
<p><img src="https://i.stack.imgur.com/3pfTr.png" alt="Screenshot of error message"></p>
<p>For instance, stepping into the constructor of the following class would give me the above message:</p>
<pre><code>public class Test
{
private Stack<String> _Dummy = new Stack<String>();
public Test() { }
}
</code></pre>
<p>I assume this is because at some point I fiddled with the settings for the symbol server, but no matter what I fiddle with now, I can't seem to get rid of that message.</p>
<p>Where has my stupidity forgotten what it did?</p>
<hr>
<p>Summary of my current <a href="https://stackoverflow.com/questions/4649093/visual-studio-2010-debugger-steps-over-methods-and-doesnt-stop-at-breakpoints/4649220#4649220">options</a>:</p>
<ul>
<li>[ ] Enable address-level debugging</li>
<li>[x] Enable Just My Code (Managed Only)</li>
<li>[ ] Enable .NET framework source stepping</li>
<li>[ ] Enable source server support</li>
<li>Symbol file .pdb locations - empty</li>
<li>Cache symbols from symbol servers to this directory: C:\temp (empty)</li>
</ul>
| [
{
"answer_id": 10750386,
"author": "psur",
"author_id": 1113539,
"author_profile": "https://Stackoverflow.com/users/1113539",
"pm_score": 2,
"selected": false,
"text": "main"
},
{
"answer_id": 21388966,
"author": "Peter Mortensen",
"author_id": 63550,
"author_profile": "https://Stackoverflow.com/users/63550",
"pm_score": 2,
"selected": false,
"text": ".suo .sln .suo"
},
{
"answer_id": 50377963,
"author": "HarshWombat",
"author_id": 9577917,
"author_profile": "https://Stackoverflow.com/users/9577917",
"pm_score": 0,
"selected": false,
"text": "Common Language Runtime Exceptions Exception Settings Exception Settings"
},
{
"answer_id": 71097694,
"author": "tttony",
"author_id": 453348,
"author_profile": "https://Stackoverflow.com/users/453348",
"pm_score": 0,
"selected": false,
"text": "wntdll.pdb not loaded this answer There is no source code available for the current location app.exe has triggered a breakpoint Right click Go to Disassembly int 3 GetEnvironmentStrings() Treat this memory as read-only; do not modify it directly"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
314,332 | <p>Which is a better way to force GC on ThreadLocal instance?</p>
| [
{
"answer_id": 314785,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 2,
"selected": false,
"text": "System.gc();\n System.gc()"
},
{
"answer_id": 6915168,
"author": "shams",
"author_id": 356645,
"author_profile": "https://Stackoverflow.com/users/356645",
"pm_score": 1,
"selected": false,
"text": " /**\n * This method guarantees that garbage collection is\n * done unlike <code>{@link System#gc()}</code>\n */\n public static void gc() {\n Object obj = new Object();\n WeakReference ref = new WeakReference<Object>(obj);\n obj = null;\n while(ref.get() != null) {\n System.gc();\n }\n }\n"
},
{
"answer_id": 11424699,
"author": "yonran",
"author_id": 471341,
"author_profile": "https://Stackoverflow.com/users/471341",
"pm_score": 1,
"selected": false,
"text": "ThreadLocal<Object> Thread ThreadLocal Object Object ThreadLocal null Thread ThreadLocalMap Object Object ThreadLocal ThreadLocal set() ThreadLocal ThreadLocalMap WeakHashMap ThreadLocalMap set() get() Object ThreadLocal.remove() Thread"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26365/"
] |
314,334 | <p>Say I have a file with any number of lines, say, 125. I want to get all the lines except the first n, say, 20. So, I want lines 21–125.</p>
<p>Is there a way to do this with with <code>tail</code>/<code>head</code>, or some other tool?</p>
| [
{
"answer_id": 314352,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 6,
"selected": true,
"text": "tail -n +21 myfile.txt\n"
},
{
"answer_id": 314362,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "awk -- 'NR > 20' /etc/passwd\n"
},
{
"answer_id": 314371,
"author": "Vijay Dev",
"author_id": 27474,
"author_profile": "https://Stackoverflow.com/users/27474",
"pm_score": 3,
"selected": false,
"text": "sed -i 1,20d filename"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] |
314,336 | <p>How to generate the Symbols file of a PowerBuilder program for dump analysis?</p>
| [
{
"answer_id": 314352,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 6,
"selected": true,
"text": "tail -n +21 myfile.txt\n"
},
{
"answer_id": 314362,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "awk -- 'NR > 20' /etc/passwd\n"
},
{
"answer_id": 314371,
"author": "Vijay Dev",
"author_id": 27474,
"author_profile": "https://Stackoverflow.com/users/27474",
"pm_score": 3,
"selected": false,
"text": "sed -i 1,20d filename"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
314,357 | <p>I am using an Infragistics UltraGrid in a WinForms application.<br>
Which event is raised on "check change" of checkbox in Infragistics UltraGrid?</p>
| [
{
"answer_id": 314378,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 3,
"selected": true,
"text": "Private Sub YourGridcontrol_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseDown\n YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode)\nEnd Sub\n\nPrivate Sub YourGridcontrol_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseUp\n YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode)\nEnd Sub\n"
},
{
"answer_id": 314381,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 3,
"selected": false,
"text": "CellChange UltraGrid.PerformAction(UltraGridAction.ExitEditMode) AfterCellUpdate"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
314,382 | <p>My application is pretty simple: it starts up with a view controller that holds a table view (in grouped view layout) with a few options. When the user taps on one of the options, I push another view controller onto my navigation controller.</p>
<p>This second view controller simply displays a UIImageView, and the user can change the screen orientation on this view controller between portrait/landscape modes. This works just fine, and all is happy.</p>
<p>However, if the user taps on the "Back" button on my navigation bar while on the landscape mode, the first controller's layout is all messed up. See below for before/after screenshots:</p>
<p><a href="https://i.stack.imgur.com/HCftn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HCftn.jpg" alt="before"></a><br>
<sub>(source: <a href="http://pessoal.org/shot1.jpg" rel="nofollow noreferrer">pessoal.org</a>)</sub><br>
<a href="https://i.stack.imgur.com/D0qzp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D0qzp.jpg" alt="after"></a><br>
<sub>(source: <a href="http://pessoal.org/shot2.jpg" rel="nofollow noreferrer">pessoal.org</a>)</sub> </p>
<p>Any clues on how to force the first view controller (second screenshot in this post) to stay within the portrait screen orientation?</p>
| [
{
"answer_id": 431974,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{\n // don't let user press \"back\" button in landscape - otherwise previous view and the rest of the application\n // will also be in landscape which we did not feel like testing yet\n self.navigationController.navigationBarHidden = (UIInterfaceOrientationPortrait != self.interfaceOrientation);\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
314,384 | <p>How do you parse a CSV file using gawk? Simply setting <code>FS=","</code> is not enough, as a quoted field with a comma inside will be treated as multiple fields.</p>
<p>Example using <code>FS=","</code> which does not work:</p>
<p>file contents:</p>
<pre><code>one,two,"three, four",five
"six, seven",eight,"nine"
</code></pre>
<p>gawk script:</p>
<pre><code>BEGIN { FS="," }
{
for (i=1; i<=NF; i++) printf "field #%d: %s\n", i, $(i)
printf "---------------------------\n"
}
</code></pre>
<p>bad output:</p>
<pre><code>field #1: one
field #2: two
field #3: "three
field #4: four"
field #5: five
---------------------------
field #1: "six
field #2: seven"
field #3: eight
field #4: "nine"
---------------------------
</code></pre>
<p>desired output:</p>
<pre><code>field #1: one
field #2: two
field #3: "three, four"
field #4: five
---------------------------
field #1: "six, seven"
field #2: eight
field #3: "nine"
---------------------------
</code></pre>
| [
{
"answer_id": 314421,
"author": "MCS",
"author_id": 1094969,
"author_profile": "https://Stackoverflow.com/users/1094969",
"pm_score": 0,
"selected": false,
"text": "BEGIN { FS=\",\" }\n{\n for (i=1; i<=NF; i++) {\n f[++n] = $i\n if (substr(f[n],1,1)==\"\\\"\") {\n while (substr(f[n], length(f[n]))!=\"\\\"\" || substr(f[n], length(f[n])-1, 1)==\"\\\\\") {\n f[n] = sprintf(\"%s,%s\", f[n], $(++i))\n }\n }\n }\n for (i=1; i<=n; i++) printf \"field #%d: %s\\n\", i, f[i]\n print \"----------------------------------\\n\"\n}\n"
},
{
"answer_id": 314820,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "awk sed a2p s2p awk sed"
},
{
"answer_id": 322812,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "# csv2delim.awk converts comma delimited files with optional quotes to delim separated file\n# delim can be any character, defaults to tab\n# assumes no repl characters in text, any delim in line converts to repl\n# repl can be any character, defaults to ~\n# changes two consecutive quotes within quotes to '\n\n# usage: gawk -f csv2delim.awk [-v delim=d] [-v repl=`\"] input-file > output-file\n# -v delim delimiter, defaults to tab\n# -v repl replacement char, defaults to ~\n\n# e.g. gawk -v delim=; -v repl=` -f csv2delim.awk test.csv > test.txt\n\n# abe 2-28-7\n# abe 8-8-8 1.0 fixed empty fields, added replacement option\n# abe 8-27-8 1.1 used split\n# abe 8-27-8 1.2 inline rpl and \"\" = '\n# abe 8-27-8 1.3 revert to 1.0 as it is much faster, split most of the time\n# abe 8-29-8 1.4 better message if delim present\n\nBEGIN {\n if (delim == \"\") delim = \"\\t\"\n if (repl == \"\") repl = \"~\"\n print \"csv2delim.awk v.m 1.4 run at \" strftime() > \"/dev/stderr\" ###########################################\n}\n\n{\n #if ($0 ~ repl) {\n # print \"Replacement character \" repl \" is on line \" FNR \":\" lineIn \";\" > \"/dev/stderr\"\n #}\n if ($0 ~ delim) {\n print \"Temp delimiter character \" delim \" is on line \" FNR \":\" lineIn \";\" > \"/dev/stderr\"\n print \" replaced by \" repl > \"/dev/stderr\"\n }\n gsub(delim, repl)\n\n $0 = gensub(/([^,])\\\"\\\"/, \"\\\\1'\", \"g\")\n# $0 = gensub(/\\\"\\\"([^,])/, \"'\\\\1\", \"g\") # not needed above covers all cases\n\n out = \"\"\n #for (i = 1; i <= length($0); i++)\n n = length($0)\n for (i = 1; i <= n; i++)\n if ((ch = substr($0, i, 1)) == \"\\\"\")\n inString = (inString) ? 0 : 1 # toggle inString\n else\n out = out ((ch == \",\" && ! inString) ? delim : ch)\n print out\n}\n\nEND {\n print NR \" records processed from \" FILENAME \" at \" strftime() > \"/dev/stderr\"\n}\n \"first\",\"second\",\"third\"\n\"fir,st\",\"second\",\"third\"\n\"first\",\"sec\"\"ond\",\"third\"\n\" first \",sec ond,\"third\"\n\"first\" , \"second\",\"th ird\"\n\"first\",\"sec;ond\",\"third\"\n\"first\",\"second\",\"th;ird\"\n1,2,3\n,2,3\n1,2,\n,2,\n1,,2\n1,\"2\",3\n\"1\",2,\"3\"\n\"1\",,\"3\"\n1,\"\",3\n\"\",\"\",\"\"\n\"\",\"\"\"aiyn\",\"oh\"\"\"\n\"\"\"\",\"\"\"\",\"\"\"\"\n11,2~2,3\n rem test csv2delim\nrem default is: -v delim={tab} -v repl=~\ngawk -f csv2delim.awk test.csv > test.txt\ngawk -v delim=; -f csv2delim.awk test.csv > testd.txt\ngawk -v delim=; -v repl=` -f csv2delim.awk test.csv > testdr.txt\ngawk -v repl=` -f csv2delim.awk test.csv > testr.txt\n"
},
{
"answer_id": 8845032,
"author": "BCoates",
"author_id": 314988,
"author_profile": "https://Stackoverflow.com/users/314988",
"pm_score": 4,
"selected": false,
"text": "FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")\" FPAT FS"
},
{
"answer_id": 9774542,
"author": "kbulgrien",
"author_id": 856172,
"author_profile": "https://Stackoverflow.com/users/856172",
"pm_score": 1,
"selected": false,
"text": "{\n ColumnCount = 0\n $0 = $0 \",\" # Assures all fields end with comma\n while($0) # Get fields by pattern, not by delimiter\n {\n match($0, / *\"[^\"]*\" *,|[^,]*,/) # Find a field with its delimiter suffix\n Field = substr($0, RSTART, RLENGTH) # Get the located field with its delimiter\n gsub(/^ *\"?|\"? *,$/, \"\", Field) # Strip delimiter text: comma/space/quote\n Column[++ColumnCount] = Field # Save field without delimiter in an array\n $0 = substr($0, RLENGTH + 1) # Remove processed text from the raw data\n }\n}\n FPAT patsplit()"
},
{
"answer_id": 16379949,
"author": "D Bro",
"author_id": 2350656,
"author_profile": "https://Stackoverflow.com/users/2350656",
"pm_score": 2,
"selected": false,
"text": "gawk -f mypgoram.awk input.csv\n csvquote input.csv | gawk -f mypgoram.awk | csvquote -u\n"
},
{
"answer_id": 33380831,
"author": "Chris Koknat",
"author_id": 251947,
"author_profile": "https://Stackoverflow.com/users/251947",
"pm_score": 0,
"selected": false,
"text": "perl -MText::CSV_XS -ne 'BEGIN{$csv=Text::CSV_XS->new()} if($csv->parse($_)){@f=$csv->fields();for $n (0..$#f) {print \"field #$n: $f[$n]\\n\"};print \"---\\n\"}' file.csv field #0: one\nfield #1: two\nfield #2: three, four\nfield #3: five\n---\nfield #0: six, seven\nfield #1: eight\nfield #2: nine\n---\n #!/usr/bin/perl\nuse warnings;\nuse strict;\nuse Text::CSV_XS;\nmy $csv = Text::CSV_XS->new();\nopen(my $data, '<', $ARGV[0]) or die \"Could not open '$ARGV[0]' $!\\n\";\nwhile (my $line = <$data>) {\n if ($csv->parse($line)) {\n my @f = $csv->fields();\n for my $n (0..$#f) {\n print \"field #$n: $f[$n]\\n\";\n }\n print \"---\\n\";\n }\n}\n Can't locate Text/CSV_XS.pm in @INC (@INC contains: /home/gnu/lib/perl5/5.6.1/i686-linux /home/gnu/lib/perl5/5.6.1 /home/gnu/lib/perl5/site_perl/5.6.1/i686-linux /home/gnu/lib/perl5/site_perl/5.6.1 /home/gnu/lib/perl5/site_perl .).\nBEGIN failed--compilation aborted.\n sudo apt-get install cpanminus sudo cpanm Text::CSV_XS"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094969/"
] |
314,397 | <p>More detail to my question:</p>
<p>HTML and JavaScript are called "client-side code".</p>
<p>C# and VB in the code behind files are termed "server-side code".</p>
<p>So what is inline-asp, and 'runat=server' code blocks called?</p>
<pre><code><!-- This is called "client-side" -->
<p>Hello World</p>
<script>alert("Hello World");</script>
</code></pre>
<p>...</p>
<pre><code>// This is called "server-side"
public void Page_Load(object sender, EventArgs e)
{
Response.Write("Hello World");
}
</code></pre>
<p>...</p>
<pre><code><%-- What is this called ??? --%>
<asp:Label ID="MyLabel" runat="server" />
<% Response.Write("Hello World"); %>
</code></pre>
<p>The best term I can come up with is "Web Forms Code".</p>
| [
{
"answer_id": 314420,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<% %> <% %> <% %>"
},
{
"answer_id": 314434,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<% %> <script> runat=server <%@ <%= writer.Write() Page.Render()"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11917/"
] |
314,401 | <p>What is the simplest way to read a full line in a C console program
The text entered might have a variable length and we can't make any assumption about its content.</p>
| [
{
"answer_id": 314422,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": true,
"text": "fgets char * getline(void) {\n char * line = malloc(100), * linep = line;\n size_t lenmax = 100, len = lenmax;\n int c;\n\n if(line == NULL)\n return NULL;\n\n for(;;) {\n c = fgetc(stdin);\n if(c == EOF)\n break;\n\n if(--len == 0) {\n len = lenmax;\n char * linen = realloc(linep, lenmax *= 2);\n\n if(linen == NULL) {\n free(linep);\n return NULL;\n }\n line = linen + (line - linep);\n linep = linen;\n }\n\n if((*line++ = c) == '\\n')\n break;\n }\n *line = '\\0';\n return linep;\n}\n"
},
{
"answer_id": 314427,
"author": "Paul Kapustin",
"author_id": 38325,
"author_profile": "https://Stackoverflow.com/users/38325",
"pm_score": 5,
"selected": false,
"text": "#include <stdio.h>\n\nint main()\n{\n char string [256];\n printf (\"Insert your full address: \");\n gets (string);\n printf (\"Your address is: %s\\n\",string);\n return 0;\n}\n"
},
{
"answer_id": 314525,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 5,
"selected": false,
"text": "getline() stdin"
},
{
"answer_id": 314541,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 1,
"selected": false,
"text": "/*\n * Initial size of the read buffer\n */\n#define DEFAULT_BUFFER 1024\n\n/*\n * Standard boolean type definition\n */\ntypedef enum{ false = 0, true = 1 }bool;\n\n/*\n * Flags errors in pointer returning functions\n */\nbool has_err = false;\n\n/*\n * Reads the next line of text from file and returns it.\n * The line must be free()d afterwards.\n *\n * This function will segfault on binary data.\n */\nchar *readLine(FILE *file){\n char *buffer = NULL;\n char *tmp_buf = NULL;\n bool line_read = false;\n int iteration = 0;\n int offset = 0;\n\n if(file == NULL){\n fprintf(stderr, \"readLine: NULL file pointer passed!\\n\");\n has_err = true;\n\n return NULL;\n }\n\n while(!line_read){\n if((tmp_buf = malloc(DEFAULT_BUFFER)) == NULL){\n fprintf(stderr, \"readLine: Unable to allocate temporary buffer!\\n\");\n if(buffer != NULL)\n free(buffer);\n has_err = true;\n\n return NULL;\n }\n\n if(fgets(tmp_buf, DEFAULT_BUFFER, file) == NULL){\n free(tmp_buf);\n\n break;\n }\n\n if(tmp_buf[strlen(tmp_buf) - 1] == '\\n') /* we have an end of line */\n line_read = true;\n\n offset = DEFAULT_BUFFER * (iteration + 1);\n\n if((buffer = realloc(buffer, offset)) == NULL){\n fprintf(stderr, \"readLine: Unable to reallocate buffer!\\n\");\n free(tmp_buf);\n has_err = true;\n\n return NULL;\n }\n\n offset = DEFAULT_BUFFER * iteration - iteration;\n\n if(memcpy(buffer + offset, tmp_buf, DEFAULT_BUFFER) == NULL){\n fprintf(stderr, \"readLine: Cannot copy to buffer\\n\");\n free(tmp_buf);\n if(buffer != NULL)\n free(buffer);\n has_err = true;\n\n return NULL;\n }\n\n free(tmp_buf);\n iteration++;\n }\n\n return buffer;\n}\n"
},
{
"answer_id": 318799,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "char line[1024];\n\nscanf(\"%[^\\n]\", line);\n char line[1024];\n\nscanf(\"%1023[^\\n]\", line);\n"
},
{
"answer_id": 319028,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n\nchar line[1024]; /* Generously large value for most situations */\n\nchar *eof;\n\nline[0] = '\\0'; /* Ensure empty line if no input delivered */\nline[sizeof(line)-1] = ~'\\0'; /* Ensure no false-null at end of buffer */\n\neof = fgets(line, sizeof(line), stdin);\n"
},
{
"answer_id": 30419689,
"author": "wonder.mice",
"author_id": 506566,
"author_profile": "https://Stackoverflow.com/users/506566",
"pm_score": 0,
"selected": false,
"text": "fgetln #include <stdio.h>\n\nchar *\nfgetln(FILE *stream, size_t *len);\n size_t line_len;\nconst char *line = fgetln(stdin, &line_len);\n line \\n"
},
{
"answer_id": 35695762,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "getline getline #define _XOPEN_SOURCE 700\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(void) {\n char *line = NULL;\n size_t len = 0;\n ssize_t read = 0;\n while (1) {\n puts(\"enter a line\");\n read = getline(&line, &len, stdin);\n if (read == -1)\n break;\n printf(\"line = %s\", line);\n printf(\"line length = %zu\\n\", read);\n puts(\"\");\n }\n free(line);\n return 0;\n}\n gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c\n./main.out\n enter a line\n asdf\n line = asdf\nline length = 5\n enter a line\n printf 'asdf\\nqwer\\n' | ./main.out\n enter a line\nline = asdf\nline length = 5\n\nenter a line\nline = qwer\nline length = 5\n\nenter a line\n getdelim getline"
},
{
"answer_id": 38506144,
"author": "Cherubim",
"author_id": 5281962,
"author_profile": "https://Stackoverflow.com/users/5281962",
"pm_score": 2,
"selected": false,
"text": "getchar() '\\n' EOF //the function to read lines of variable length\n\nchar* scan_line(char *line)\n{\n int ch; // as getchar() returns `int`\n long capacity = 0; // capacity of the buffer\n long length = 0; // maintains the length of the string\n char *temp = NULL; // use additional pointer to perform allocations in order to avoid memory leaks\n\n while ( ((ch = getchar()) != '\\n') && (ch != EOF) )\n {\n if((length + 1) >= capacity)\n {\n // resetting capacity\n if (capacity == 0)\n capacity = 2; // some initial fixed length \n else\n capacity *= 2; // double the size\n\n // try reallocating the memory\n if( (temp = realloc(line, capacity * sizeof(char))) == NULL ) //allocating memory\n {\n printf(\"ERROR: unsuccessful allocation\");\n // return line; or you can exit\n exit(1);\n }\n\n line = temp;\n }\n\n line[length] = (char) ch; //type casting `int` to `char`\n length++;\n }\n line[length + 1] = '\\0'; //inserting null character at the end\n\n // remove additionally allocated memory\n if( (temp = realloc(line, (length + 1) * sizeof(char))) == NULL )\n {\n printf(\"ERROR: unsuccessful allocation\");\n // return line; or you can exit\n exit(1);\n }\n\n line = temp;\n return line;\n}\n char *line = NULL;\n line = scan_line(line);\n scan_line() #include <stdio.h>\n#include <stdlib.h> //for dynamic allocation functions\n\nchar* scan_line(char *line)\n{\n ..........\n}\n\nint main(void)\n{\n char *a = NULL;\n\n a = scan_line(a); //function call to scan the line\n\n printf(\"%s\\n\",a); //printing the scanned line\n\n free(a); //don't forget to free the malloc'd pointer\n}\n Twinkle Twinkle little star.... in the sky!\n Twinkle Twinkle little star.... in the sky!\n"
},
{
"answer_id": 44181504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "unsigned int getConsoleInput(char **pStrBfr) //pass in pointer to char pointer, returns size of buffer\n{\n char * strbfr;\n int c;\n unsigned int i;\n i = 0;\n strbfr = (char*)malloc(sizeof(char));\n if(strbfr==NULL) goto error;\n while( (c = getchar()) != '\\n' && c != EOF )\n {\n strbfr[i] = (char)c;\n i++;\n strbfr = (void*)realloc((void*)strbfr,sizeof(char)*(i+1));\n //on realloc error, NULL is returned but original buffer is unchanged\n //NOTE: the buffer WILL NOT be NULL terminated since last\n //chracter came from console\n if(strbfr==NULL) goto error;\n }\n strbfr[i] = '\\0';\n *pStrBfr = strbfr; //successfully returns pointer to NULL terminated buffer\n return i + 1; \n error:\n *pStrBfr = strbfr;\n return i + 1;\n}\n"
},
{
"answer_id": 62383723,
"author": "Aaron nevalinz",
"author_id": 11522511,
"author_profile": "https://Stackoverflow.com/users/11522511",
"pm_score": 0,
"selected": false,
"text": "{\nchar message[N]; /* character array for the message, you can always change the character length */\nint i = 0; /* loop counter */\n\nprintf( \"Enter a message: \" );\nmessage[i] = getchar(); /* get the first character */\nwhile( message[i] != '\\n' ){\n message[++i] = getchar(); /* gets the next character */\n}\n\nprintf( \"Entered message is:\" );\nfor( i = 0; i < N; i++ )\n printf( \"%c\", message[i] );\n\nreturn ( 0 );\n"
},
{
"answer_id": 66807123,
"author": "Antonin GAVREL",
"author_id": 3161139,
"author_profile": "https://Stackoverflow.com/users/3161139",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <errno.h>\n\nint sc_gets(char *buf, int n)\n{\n int count = 0;\n char c;\n\n if (__glibc_unlikely(n <= 0))\n return -1;\n\n while (--n && (c = fgetc(stdin)) != '\\n')\n buf[count++] = c;\n buf[count] = '\\0';\n\n return (count != 0 || errno != EAGAIN) ? count : -1;\n}\n #define BUFF_SIZE 10\n\nint main (void) {\n char buff[BUFF_SIZE];\n\n sc_gets(buff, sizeof(buff));\n printf (\"%s\\n\", buff);\n\n return 0;\n}\n"
},
{
"answer_id": 72846401,
"author": "THUNDER 07",
"author_id": 15149644,
"author_profile": "https://Stackoverflow.com/users/15149644",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%[^\\n]%*c\", str); #include <stdio.h>\nint main()\n{\n char S[101];\n scanf(\"%[^\\n]%*c\", S);\n printf(\"%s\", S);\n return 0;\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011/"
] |
314,408 | <p>I am building a Facebook App which is heavy on Javascript. For this I have multiple Javascript files. Since in Facebook development, the page is served over a tunnel, there is excessive latency added while requesting multiple javascript files. Is it possible to combine the contents of multiple javascript files at runtime? Having multiple files makes it easy to develop, and hence I am avoiding having to combine it while development itself.</p>
| [
{
"answer_id": 314462,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 4,
"selected": false,
"text": ":cache javascript_include_tag <%= javascript_include_tag :all, :cache => true %>\n ActionController::Base.perform_caching"
},
{
"answer_id": 14175203,
"author": "Kristian",
"author_id": 680578,
"author_profile": "https://Stackoverflow.com/users/680578",
"pm_score": 3,
"selected": false,
"text": "/config/environments development.rb config.assets.debug = false"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29653/"
] |
314,412 | <p>If you were to build a badge system similiar to how SO does it, would you put the logic/business layer in the database directly (via stored procedure, scheduled sql jobs) or put it in the server side?</p>
<p>From what I can think of, you have to:</p>
<ol>
<li>list badges that pertain to the current user action</li>
<li>check if the user has a badge already or not</li>
<li>insert badge for user </li>
</ol>
<p><b>Potential options</b></p>
<ol>
<li>business logic in the web application that calls stored procedures etc.</li>
<li>stored procedures ONLY</li>
<li>sql server job that runs every x minutes</li>
<li>windows service that runs every x minutes</li>
</ol>
<p>Would a combination of these be required? I think it would since some badges are based on milestones for a given question, maybe a batch job is better?</p>
<p><b>Update</b></p>
<p>A system where you can modify the badge system, then re-run the entire badge linking for everyone would be even better. i.e. say you change the logic for some badges, now you have to re-apply it to all the questions/answers/votes/etc.</p>
<p><b>interesting problem to solve!!</b></p>
| [
{
"answer_id": 314453,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 1,
"selected": false,
"text": "IF eligible for <new badge> THEN\n INSERT INTO user_badges\n SELECT <new_badge>\n WHERE NOT EXISTS (SELECT NULL FROM user_badges\n WHERE badge = <new_badge>);\nEND IF;\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
314,415 | <p>Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?</p>
<pre><code>public static string strUserName
{
get { return m_globalVar; }
set { m_globalVar = value; }
}
</code></pre>
<p>Used later as:</p>
<pre><code>GlobalClass.strUserName
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 314429,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 0,
"selected": false,
"text": "ClassName.MemberName"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,423 | <p>I've been tasked with integration testing of a large system. Presently, I have a COM dll that I'm testing useing a UI that I created that kicks off a series of unit tests that call into the dll. This works, but I'm wanting to migrate this over to MbUnit. When I start the first test in MbUnit, it seems to hang at "Found 1 tests". I end up having to close the IDE. Could someone please point me in the right direction?</p>
<p>Thanks.</p>
| [
{
"answer_id": 448702,
"author": "Craigger",
"author_id": 18924,
"author_profile": "https://Stackoverflow.com/users/18924",
"pm_score": 1,
"selected": false,
"text": "namespace UnitTest\n{\n class Program\n {\n static void Main(string[] args_)\n {\n // run unit test\n AutoRunner auto = new AutoRunner();\n auto.Load();\n auto.Run();\n\n HtmlReport report = new HtmlReport();\n\n string fileName;\n // generate report results\n fileName = report.Render(auto.Result);\n\n // launch results in user's browser\n System.Diagnostics.Process.Start(fileName);\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,424 | <p>I have a report reading records out of a DMS system and I thought it would be nice to have a link to the documents that it is listing so that the users could view the actual documents. </p>
<p>However when it displays a Word doc it allows you to make changes and then save them, which rather undermines the DMS system. </p>
<p>I don't think there is a parameter (/r) in Word that does this so do any of you clever people out there have a solution please?</p>
| [
{
"answer_id": 448702,
"author": "Craigger",
"author_id": 18924,
"author_profile": "https://Stackoverflow.com/users/18924",
"pm_score": 1,
"selected": false,
"text": "namespace UnitTest\n{\n class Program\n {\n static void Main(string[] args_)\n {\n // run unit test\n AutoRunner auto = new AutoRunner();\n auto.Load();\n auto.Run();\n\n HtmlReport report = new HtmlReport();\n\n string fileName;\n // generate report results\n fileName = report.Render(auto.Result);\n\n // launch results in user's browser\n System.Diagnostics.Process.Start(fileName);\n }\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
314,426 | <p>How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?</p>
<pre><code>For Each entry as String in myObject
' Do stuff here...
Next
</code></pre>
<p>There are string, integer and boolean properties in my object.</p>
| [
{
"answer_id": 314436,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 7,
"selected": true,
"text": "PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();\n Dim info() As PropertyInfo = myobject.GetType().GetProperties()\n"
},
{
"answer_id": 314443,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "using System.Reflection;\n\nType type = job.GetType();\n foreach ( MemberInfo memInfo in type.GetMembers() )\n if (memInfo is PropertyInfo)\n {\n // Do Something\n }\n"
},
{
"answer_id": 314458,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 6,
"selected": false,
"text": "For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()\n If p.CanRead Then\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, Nothing))\n End If\nNext\n"
},
{
"answer_id": 8167167,
"author": "NicoJuicy",
"author_id": 209555,
"author_profile": "https://Stackoverflow.com/users/209555",
"pm_score": 3,
"selected": false,
"text": "if (item is IEnumerable) {\n foreach (object o in item as IEnumerable) {\n //do function\n }\n} else {\n foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {\n if (p.CanRead) {\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, null)); //possible function\n }\n }\n}\n If TypeOf item Is IEnumerable Then\n\n For Each o As Object In TryCast(item, IEnumerable)\n 'Do Function\n Next\n Else\n For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()\n If p.CanRead Then\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, Nothing)) 'possible function\n End If\n Next\n End If\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
314,432 | <p>I am using Visual Studio 2005 and StarTeam 2008 (cross-platform client and VS integration). At some point, I added an 'App.config' to a project. I notice now that this file will not check-in.</p>
<ol>
<li><p>The 'StarTeam Pending Checkins' window in VS reports the file 'Not in View'. Selecting it for check in and clicking 'Check In Files' causes a dialog to appear - 'Any operation... requires completing the pending renames/deletes'. I click 'Yes' to proceed and nothing happens.</p></li>
<li><p>The StarTeam client reports this file as 'Modified'. If I check-in from the client, I get no 'complete pending renames/deletes' dialog and the file quickly appears with a 'Current' status.</p></li>
<li><p>Refreshing StarTeam from VS, I still see the file as 'Not in View'.</p></li>
</ol>
<p>I have tried forcing the check-in. I completely removed my working files and pulled the solution fresh in hopes that the StarTeam status ('Current') would apply in VS.</p>
| [
{
"answer_id": 314436,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 7,
"selected": true,
"text": "PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();\n Dim info() As PropertyInfo = myobject.GetType().GetProperties()\n"
},
{
"answer_id": 314443,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "using System.Reflection;\n\nType type = job.GetType();\n foreach ( MemberInfo memInfo in type.GetMembers() )\n if (memInfo is PropertyInfo)\n {\n // Do Something\n }\n"
},
{
"answer_id": 314458,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 6,
"selected": false,
"text": "For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()\n If p.CanRead Then\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, Nothing))\n End If\nNext\n"
},
{
"answer_id": 8167167,
"author": "NicoJuicy",
"author_id": 209555,
"author_profile": "https://Stackoverflow.com/users/209555",
"pm_score": 3,
"selected": false,
"text": "if (item is IEnumerable) {\n foreach (object o in item as IEnumerable) {\n //do function\n }\n} else {\n foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {\n if (p.CanRead) {\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, null)); //possible function\n }\n }\n}\n If TypeOf item Is IEnumerable Then\n\n For Each o As Object In TryCast(item, IEnumerable)\n 'Do Function\n Next\n Else\n For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()\n If p.CanRead Then\n Console.WriteLine(\"{0}: {1}\", p.Name, p.GetValue(obj, Nothing)) 'possible function\n End If\n Next\n End If\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] |
314,433 | <p>If you call a web service from Silverlight like this:</p>
<pre><code>MyServiceClient serviceClient = new MyServiceClient();
void MyMethod()
{
serviceClient.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(serviceClient_GetDataCompleted);
serviceClient.GetDataAsync();
// HOW DO I WAIT/JOIN HERE ON THE ASYNC CALL, RATHER THAN BEING FORCE TO LEAVE THIS METHOD?
}
</code></pre>
<p>I would rather wait/join with the asych service thread inside "MyMethod" rather than leaving "MyMethod" after calling "GetDataAsync", what is the best way to do this?</p>
<p>Thanks,
Jeff</p>
| [
{
"answer_id": 314854,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 1,
"selected": true,
"text": "void MyMethod()\n{\n wait = new ManualResetEvent(false);\n // call your service\n wait.WaitOne();\n // finish working\n}\n void serviceClient_GetDataCompleted(...)\n{\n // Set values you need from service\n wait.Set();\n}\n"
},
{
"answer_id": 330868,
"author": "Shawn Wildermuth",
"author_id": 40125,
"author_profile": "https://Stackoverflow.com/users/40125",
"pm_score": 0,
"selected": false,
"text": "serviceClient.GetDataCompleted += (s,e) =>\n{\n // Your code here\n};\nserviceClient.GetDataAsync();\n"
},
{
"answer_id": 2237749,
"author": "Rus",
"author_id": 134294,
"author_profile": "https://Stackoverflow.com/users/134294",
"pm_score": 0,
"selected": false,
"text": "public class ServiceFooCoordinator : CoordinatorBase<IServiceFoo>\n{\n public IAsyncResult BeginMethodFoo ()\n {\n IAsyncResult ar = null;\n IServiceFoo channel = null;\n channel = _factory.GetChannel();\n\n Begin( channel, () => ar = channel.BeginMethodFoo( null, channel ) );\n return ar;\n }\n\n public Bar[] EndMethodFoo ( IAsyncResult ar )\n {\n IServiceFoo channel = null;\n channel = _factory.GetChannel();\n return channel.EndMethodFoo( ar );\n }\n}\n ServiceFooCoordinator _coordinator;\n\n var asyncResult = _coordinator.BeginMethodFoo();\n try\n {\n var result = _coordinator.EndMethodFoo( asyncResult );\n }\n catch ( Exception )\n { }\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
314,437 | <p>I have a list of images that i’ve loaded with the Loader class, but I’m having a tough time assigning them unique names.
I need unique names because I want to remove certain images after a while.
Is there a way to assign loaders a name or some unique tag so i can remove them later? thanks.</p>
<p>Here's part of my code</p>
<pre><code>for (var i = startnum; i < endnum; i++){
var thumb = panels[i].@THUMB;
var thumb_loader = new Loader();
thumb_loader.load(new URLRequest(thumb));
thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);
thumb_loader.name = i;
thumb_loader.x = (thumb_width + 20)*i;
}
</code></pre>
<p>I tried to use getChildByName in another function..</p>
<pre><code>var myLoader:Loader = getChildByName( "1" ) as Loader;
myLoader.unload();
</code></pre>
<p>But it's giving me
Error #1009: Cannot access a property or method of a null object reference.</p>
<p>I tried to put thumb_loader as global variable, and do this</p>
<pre><code>var myLoader:Loader = thumb_loader.getChildByName( "1" ) as Loader;
</code></pre>
<p>But it's still not working.
Thanks.</p>
| [
{
"answer_id": 314476,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "var img:Image;\nvar img_map:Object = new Object();\nvar last_added:int = 0;\nfor each (img in yourListOfImages)\n{\n img_map[\"img_\"+last_added] = img;\n last_added++;\n}\n"
},
{
"answer_id": 314482,
"author": "vanhornRF",
"author_id": 1945,
"author_profile": "https://Stackoverflow.com/users/1945",
"pm_score": 0,
"selected": false,
"text": "package \n{\n import flash.display.Loader;\n\n public dynamic class DynamicLoader extends Loader \n {\n public function DynamicLoader()\n {\n super();\n }\n }\n}\n"
},
{
"answer_id": 314712,
"author": "Matt W",
"author_id": 32396,
"author_profile": "https://Stackoverflow.com/users/32396",
"pm_score": 3,
"selected": true,
"text": "var myLoader:Loader = new Loader();\nmyLoader.name = \"myUniqueName\";\nmyLoader.load( .... );\naddChild( myLoader );\n var myLoader:Loader = getChildByName( \"myUniqueName\" ) as Loader;\nmyLoader.unload();\n loadersArr[\"uniqueName\"] = thumb_loader;\n var loaderToUnload:Loader = loadersArr[\"uniqueName\"];\nloaderToUnload.unload();\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34797/"
] |
314,457 | <p>Usually, I've seen it with forms, but I've found it helpful to group related sets of data (eg when you have multiple tables on a page, using a fieldset around each table or group of related tables to define a visible meaning and a group name (legend)). Is this abusing the fieldset tag to the point where, in my uses, it no longer has semantic meaning?</p>
| [
{
"answer_id": 314496,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": ".fieldset {\nborder-right: 1px solid #75736E;\nborder-bottom: 1px solid #75736E;\nborder-left: 1px solid #F2F0EE;\nborder-top: 1px solid #F2F0EE;\npadding: 10px 3px 3px 3px;\n\n}\n\n.outer {\nborder-left: 1px solid #75736E;\nborder-top: 1px solid #75736E;\nborder-right: 1px solid #F2F0EE;\nborder-bottom: 1px solid #F2F0EE;\nwidth: 200px; /* CHANGE THIS FOR BOX SIZE */\n} \n\n.legend {\nfloat: left;\nmargin-left: 15px;\nmargin-top: -8px;\npadding-left: 5px;\npadding-right: 5px;\nfont-weight: bold;\nbackground: #FFF;\n} \n\n<div class=\"legend\">Lipsum.com Is The Best</div>\n<div class=\"outer\">\n<div class=\"fieldset\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \nDonec congue fermentum metus. Quisque vel ante. \nCras purus metus, dignissim at, luctus et, sollicitudin eget, urna. \nMaecenas eget lacus. Aenean bibendum risus non erat mattis semper. \nAliquam placerat nibh eget lacus. Sed blandit eleifend justo. Nam elit. \nFusce feugiat orci id eros facilisis laoreet. \nInteger vestibulum condimentum purus. \nProin vehicula congue lacus. Quisque placerat diam nec enim. \nNunc lorem. Maecenas nec sem sed nulla tristique faucibus.</div></div>\n"
},
{
"answer_id": 315147,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 3,
"selected": false,
"text": "fieldset <form> fieldset form"
},
{
"answer_id": 1816290,
"author": "William",
"author_id": 220937,
"author_profile": "https://Stackoverflow.com/users/220937",
"pm_score": 2,
"selected": true,
"text": "<h1>The Big Book about Everything</h1>\n<fieldset>\n <legend>Jokes</legend>\n <h2>30 pages of humorous Jokes</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>\n <p>Cras nec diam eu lectus condimentum faucibus in et odio.</p>\n</fieldset>\n<fieldset>\n <legend>Poems</legend>\n <h2>20 pages of well written poems</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>\n <p>Cras nec diam eu lectus condimentum faucibus in et odio.</p>\n</fieldset>\n<fieldset>\n <legend>Horror</legend>\n <h2>3 Short and scary stories</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>\n <p>Cras nec diam eu lectus condimentum faucibus in et odio.</p>\n</fieldset>\n<fieldset>\n <legend>Mystery</legend>\n <h2>3 Short and mysterious stories</h2>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>\n <p>Cras nec diam eu lectus condimentum faucibus in et odio.</p>\n</fieldset>\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
314,459 | <p>I´m using <code>Transaction Binding=Explicit Unbind</code> in the connection string as recommended <a href="http://weblogs.asp.net/ryangaraygay/archive/2008/04/14/issue-with-system-transactions-sqlconnection-and-timeout.aspx" rel="noreferrer">here</a> since I´m also using TransactionScope with timeout. The problem is that the connections does not seem to close after being disposed and eventually there are no more connections available in the connection pool. I got the same result when I modified the TransactionTimeoutIssueDemo (see the link) and ran TransactionScopeTest() (with the explicit unbind connection string) enough times in a loop to use up all available connections in the connection pool. Default value for connections in the pool is 100 but this can be changed by using the setting <code>Max Pool Size =10</code> for instance. It seems that the connections will not be released when using explicit unbind even though both the SqlConnection and the TransactionScope are used with the <code>using</code> clause. Anyone know how to handle this?</p>
| [
{
"answer_id": 315109,
"author": "Magnus Lindhe",
"author_id": 966,
"author_profile": "https://Stackoverflow.com/users/966",
"pm_score": 3,
"selected": true,
"text": "using (SqlConnection con = new SqlConnection(connectionString))\n{\n con.Open();\n try\n {\n Console.WriteLine(\"Server is {0}\", con.ServerVersion);\n Console.WriteLine(\"Clr is {0}\", Environment.Version);\n for (int i = 0; i < 5; i++)\n {\n using (SqlCommand cmd = con.CreateCommand())\n {\n cmd.CommandText = \"insert into TXTEST values ( \" + i + \" )\";\n cmd.ExecuteNonQuery();\n }\n Console.WriteLine(\"Row inserted\");\n }\n Thread.Sleep(TimeSpan.FromSeconds(1));\n }\n catch\n {\n SqlConnection.ClearPool(con);\n throw;\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30790/"
] |
314,463 | <p>In Team Build 2008, the Drop Location for a build is no longer specified in the .proj file, and instead is stored in the database and maintained in the GUI tool.</p>
<p>The GUI tool only accepts a network path as a drop location (i.e. \\server\share) and will not accept a local path.</p>
<p>Our build server also hosts the dropped files, so it seems that forcing a file copy operation to go through the network share introduces a lot of lag time when copying a large number of files. I would like to override this feature so that I can specify a local directory for drop location, but I can't figure out how.</p>
| [
{
"answer_id": 315109,
"author": "Magnus Lindhe",
"author_id": 966,
"author_profile": "https://Stackoverflow.com/users/966",
"pm_score": 3,
"selected": true,
"text": "using (SqlConnection con = new SqlConnection(connectionString))\n{\n con.Open();\n try\n {\n Console.WriteLine(\"Server is {0}\", con.ServerVersion);\n Console.WriteLine(\"Clr is {0}\", Environment.Version);\n for (int i = 0; i < 5; i++)\n {\n using (SqlCommand cmd = con.CreateCommand())\n {\n cmd.CommandText = \"insert into TXTEST values ( \" + i + \" )\";\n cmd.ExecuteNonQuery();\n }\n Console.WriteLine(\"Row inserted\");\n }\n Thread.Sleep(TimeSpan.FromSeconds(1));\n }\n catch\n {\n SqlConnection.ClearPool(con);\n throw;\n }\n}\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34409/"
] |
314,465 | <p>I have a MasterPage and a Content Page</p>
<p>My Content Page has a number of controls, - dropdownlist, text boxes, radio buttons.</p>
<p>I want to loop through all the control and if its one of the controls above then i want to obtain the selectedvalue, text etc</p>
<p>I know I can access the control directly by name, but as this is my learning experience on asp.net, I want to be able to go through the Controls collection</p>
<p>I tried</p>
<pre><code>foreach(Controls ctrl in Master.Controls)
{
}
</code></pre>
<p>but I wasnt able to get to the controls I needed.</p>
<p>Edit:: I guess i drew the gun a bit too quick as my intellisense kept failing on me. I solved my issue with this in code behind on my content page</p>
<pre><code>protected void btnSearch_Click(object sender, EventArgs e)
{
foreach (Control ctrl in Master.Controls)
{
if (ctrl is HtmlForm)
{
foreach(Control formControl in ctrl.Controls)
{
if (formControl is ContentPlaceHolder)
{
foreach (Control placeHolderControl in formControl.Controls)
{
if (placeHolderControl is DropDownList)
{
string test = "AA";
}
}
}
}
}
}
}
</code></pre>
<p>Now to build a recursive routine</p>
| [
{
"answer_id": 314548,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 0,
"selected": false,
"text": "foreach (Control c in ContentPlaceHolder1.Controls)\n{\n Response.Write(c.ID );\n}\n"
},
{
"answer_id": 314559,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "<form> <p runat=\"server\"> <p> <form runat=\"server\">\n <p runat=\"server\">\n <asp:Label runat=\"server\" />\n <asp:TextBox runat=\"server\" />\n </p>\n <p runat=\"server\">\n <asp:Button runat=\"server\" />\n </p>\n</form>\n form\n - p\n - label\n - textbox\n - p\n - button\n // This is the recursive version\npublic void LoopControl(Control parent) {\n foreach (Control control in parent) {\n // do stuff\n LoopControl(control);\n }\n}\n\n// And then\nLoopControl(Page);\n"
}
] | 2008/11/24 | [
"https://Stackoverflow.com/questions/314465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38230/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.