id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
9,204,287
How to return a PNG image from Jersey REST service method to the browser
<p>I have a web server running with Jersey REST resources up and I wonder how to get an image/png reference for the browsers img tag; after submitting a Form or getting an Ajax response. The image processing code for adding graphics is working, just need to return it somehow.</p> <p>Code:</p> <pre><code>@POST @Path("{fullsize}") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("image/png") // Would need to replace void public void getFullImage(@FormDataParam("photo") InputStream imageIS, @FormDataParam("submit") String extra) { BufferedImage image = ImageIO.read(imageIS); // .... image processing //.... image processing return ImageIO. .. ? } </code></pre> <p>Cheers</p>
9,204,824
4
2
null
2012-02-09 01:38:45.227 UTC
32
2022-01-26 10:48:54.323 UTC
2014-12-08 10:47:35.477 UTC
null
991,191
null
991,191
null
1
59
java|image|glassfish|jersey|javax.imageio
120,291
<p>I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.</p> <p>Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:</p> <pre><code>@Path("/whatever") @Produces("image/png") public Response getFullImage(...) { BufferedImage image = ...; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); byte[] imageData = baos.toByteArray(); // uncomment line below to send non-streamed // return Response.ok(imageData).build(); // uncomment line below to send streamed // return Response.ok(new ByteArrayInputStream(imageData)).build(); } </code></pre> <p>Add in exception handling, etc etc.</p>
16,556,968
How to check if text fields are empty on form submit using jQuery?
<p>How could I use jQuery to check if text-fields are empty when submitting without loading <code>login.php</code>?</p> <pre><code>&lt;form action="login.php" method="post"&gt; &lt;label&gt;Login Name:&lt;/label&gt; &lt;input type="text" name="email" id="log" /&gt; &lt;label&gt;Password:&lt;/label&gt; &lt;input type="password" name="password" id="pwd" /&gt; &lt;input type="submit" name="submit" value="Login" /&gt; &lt;/form&gt; </code></pre> <p>Thanks.</p>
16,556,991
8
2
null
2013-05-15 04:37:32.317 UTC
12
2020-05-02 15:44:17.43 UTC
2020-05-02 15:41:22.76 UTC
null
1,823,841
null
939,990
null
1
27
jquery|form-submit
171,150
<p>You can bind an event handler to the "submit" JavaScript event using jQuery <a href="https://api.jquery.com/submit/" rel="noreferrer"><code>.submit</code></a> method and then get trimmed <code>#log</code> text field value and check if empty of not like:</p> <pre><code>$('form').submit(function () { // Get the Login Name value and trim it var name = $.trim($('#log').val()); // Check if empty of not if (name === '') { alert('Text-field is empty.'); return false; } }); </code></pre> <p><a href="http://jsfiddle.net/LHZXw/1/" rel="noreferrer"><strong>FIDDLE DEMO</strong></a></p>
16,260,285
D3: Removing Elements
<p>I have a bar chart that creates positive and negative bars. I'm trying to remove the negative bars later on but for now, even after appending the bars, if I try to immediately remove the negative bars, they still appear.</p> <pre><code>var margin = {top: 30, right: 10, bottom: 10, left: 10}, width = 750 - margin.left - margin.right, height = data.length * 20 //500 - margin.top - margin.bottom; var x = d3.scale.linear() .range([0, width*.85]) //chart1.x =x //chart1.y = y var y = d3.scale.ordinal() .rangeRoundBands([0, height], 0); var xAxis = d3.svg.axis() .scale(x) .orient("top"); var svg = d3.select("#barchart").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //d3.tsv("data.tsv", type, function(error, data) { x.domain(d3.extent(data, function(d) { return +d.netdonations_over_population_to_gdppercap_percentage; })).nice(); y.domain(data.map(function(d) { return d.name; })); bar = svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", function(d) { return +d.netdonations_over_population_to_gdppercap_percentage &lt; 0 ? "bar negative" : "bar positive"; }) .attr("x", function(d) { return x(Math.min(0, +d.netdonations_over_population_to_gdppercap_percentage)); }) .attr("y", function(d) { return y(d.name); }) .attr("width", function(d) { return Math.abs(x(+d.netdonations_over_population_to_gdppercap_percentage) - x(0)); }) .attr("height", y.rangeBand()).style("stroke","white") bar.selectAll(".negative").data([]).exit().remove() </code></pre> <p>The remove statement is the last one. The rest of the code:</p> <pre><code>svg.selectAll("text") .data(data) .enter().append("text").text(function(d) { return d; }).attr("y", function(d, i) { return y(d.name)+ y.rangeBand(); //return i * (height / data.length)+30; }).attr("x", function(d) { return x(0) //x(Math.min(0, +d.netdonations_over_population_to_gdppercap_percentage)); }).text(function(d) { //return y(d) + y.rangeBand() / 2; return d.name + " " + d.netdonations_over_population_to_gdppercap_percentage; }).style("font-size","14px").attr("dx", 3).attr("dy", "-0.45em") svg.append("g") .attr("class", "x axis") .call(xAxis); svg.append("g") .attr("class", "y axis") .append("line") .attr("x1", x(0)) .attr("x2", x(0)) .attr("y2", height); </code></pre>
16,260,615
1
0
null
2013-04-28 06:33:06.063 UTC
9
2014-04-29 07:44:13.49 UTC
null
null
null
null
994,165
null
1
46
javascript|d3.js
111,116
<p>try switching your selectAll statement to:</p> <pre><code>svg.selectAll("rect.negative").remove() </code></pre> <p>This should select the tags <code>rect</code> with class <code>negative</code>although I'm not 100% sure it will find it because the <code>attr</code> <code>class</code> is written as <code>bar negative</code>. If it doesn't work I might try changing your <code>class</code> attribute to something like <code>negative bar</code> or just <code>negative</code>.</p> <p>Sorry if this doesn't help!</p>
16,044,514
What is decltype with two arguments?
<blockquote> <p><strong>Edit, in order to avoid confusion: <code>decltype</code> does <em>not</em> accept two arguments. See answers.</strong></p> </blockquote> <p>The following two structs can be used to check for the existance of a member function on a type <code>T</code> during compile-time:</p> <pre><code>// Non-templated helper struct: struct _test_has_foo { template&lt;class T&gt; static auto test(T* p) -&gt; decltype(p-&gt;foo(), std::true_type()); template&lt;class&gt; static auto test(...) -&gt; std::false_type; }; // Templated actual struct: template&lt;class T&gt; struct has_foo : decltype(_test_has_foo::test&lt;T&gt;(0)) {}; </code></pre> <p>I think the idea is to use SFINAE when checking for the existance of a member function, so in case <code>p-&gt;foo()</code> isn't valid, only the ellipses version of <code>test</code>, which returns the <code>std::false_type</code> is defined. Otherwise the first method is defined for <code>T*</code> and will return <code>std::true_type</code>. The actual "switch" happens in the second class, which inherits from the type returned by <code>test</code>. This seems clever and "lightweight" compared to different approaches with <code>is_same</code> and stuff like that.</p> <p>The <code>decltype</code> with two arguments first looked surprising to me, as I thought it just gets the type of an expression. When I saw the code above, I thought it's something like "try to compile the expressions and always return the type of the second. Fail if the expressions fail to compile" (so hide this specialization; SFINAE).</p> <p>But:</p> <p>Then I thought I could use this method to write any "is valid expression" checker, as long as it depends on some type <code>T</code>. Example:</p> <pre><code>... template&lt;class T&gt; static auto test(T* p) -&gt; decltype(bar(*p), std::true_type()); ... </code></pre> <p><a href="http://ideone.com/dJkLPF">http://ideone.com/dJkLPF</a></p> <p>This, so I thought, will return a <code>std::true_type</code> if and only if <code>bar</code> is defined accepting a <code>T</code> as the first parameter (or if <code>T</code> is convertible, etc...), i.e.: if <code>bar(*p)</code> would compile if it was written in some context where <code>p</code> is defined of type <code>T*</code>.</p> <p>However, the modification above evaluates <em>always</em> to <code>std::false_type</code>. <strong>Why is this?</strong> I don't want to fix it with some complicated different code. I just want to know why it doesn't work as I expected it to. Clearly, <strong><code>decltype</code> with two arguments</strong> works different than I thought. I couldn't find any documentation; it's only explained with one expression everywhere.</p>
16,044,573
2
3
null
2013-04-16 18:31:57 UTC
17
2013-05-03 00:37:37.753 UTC
2013-05-03 00:37:37.753 UTC
null
636,019
null
592,323
null
1
53
c++|c++11|sfinae|typetraits|decltype
10,574
<p>It's an comma-separated list of expressions, the type is identical to the type of the last expression in the list. It's usually used to verify that the <em>first</em> expression is valid (compilable, think SFINAE), the second is used to specify that <code>decltype</code> should return in case the first expression is valid.</p>
16,421,033
Lazy sequence generation in Rust
<p>How can I create what other languages call a lazy sequence or a "generator" function?</p> <p>In Python, I can use <code>yield</code> as in the following example (from Python's docs) to lazily generate a sequence that is iterable in a way that does not use the memory of an intermediary list:</p> <pre class="lang-py prettyprint-override"><code># a generator that yields items instead of returning a list def firstn(n): num = 0 while num &lt; n: yield num num += 1 sum_of_first_n = sum(firstn(1000000)) </code></pre> <p>How can I do something similar in Rust?</p>
16,421,232
4
0
null
2013-05-07 14:02:22.957 UTC
11
2022-01-21 16:13:33.027 UTC
2017-04-21 18:55:57.43 UTC
null
155,423
null
30,544
null
1
57
rust|lazy-sequences
23,472
<p>Rust 1.0 does not have generator functions, so you'd have to do it manually with <a href="https://doc.rust-lang.org/rust-by-example/trait/iter.html" rel="nofollow noreferrer">explicit iterators</a>.</p> <p>First, rewrite your Python example as a class with a <code>next()</code> method, since that is closer to the model you're likely to get in Rust. Then you can rewrite it in Rust with a struct that implements the <code>Iterator</code> trait.</p> <p>You might also be able to use a function that returns a closure to achieve a similar result, but I don't think it would be possible to have that implement the <code>Iterator</code> trait (since it would require being called to generate a new result).</p>
16,077,971
git produces Gtk-WARNING: cannot open display
<p>I've been working on my project remotely through the command line on a machine to which I don't have admin rights and after running <code>git push origin master</code> I get the following error message:</p> <pre><code>(gnome-ssh-askpass:29241): Gtk-WARNING **: cannot open display: </code></pre> <p>My <code>.git/config</code> file has the following contents:</p> <blockquote> <pre><code> [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = https://[email protected]/username/repository.git [branch "master"] remote = origin merge = refs/heads/master </code></pre> </blockquote> <p>I was getting the 403 error earlier. Following the comment <a href="https://stackoverflow.com/questions/7438313/pushing-to-git-returning-error-code-403-fatal-http-request-failed/9575906#9575906">here</a>, I put my username before the @ sign in the remote url and since then, I've been getting the Gtk error.</p> <p>When I login to the machine using <code>ssh -X</code> and try to push, I get the following error:</p> <pre><code>X11 connection rejected because of wrong authentication. (gnome-ssh-askpass:31922): Gtk-WARNING **: cannot open display:localhost:10.0 </code></pre> <p>If I change the url of the remote to <code>[email protected]:username/repository.git</code>, then the error is:</p> <pre><code>ssh: connect to host github.com port 22: Connection timed out fatal: The remote end hung up unexpectedly </code></pre> <p>Do you know how to fix this?</p>
16,104,473
4
9
null
2013-04-18 08:25:18.42 UTC
46
2019-04-14 07:38:04.643 UTC
2017-05-23 12:03:04.477 UTC
null
-1
null
265,289
null
1
141
git|version-control|github|ssh
89,016
<p>I have finally discovered a solution to the problem. As it was described <a href="http://kartzontech.blogspot.it/2011/04/how-to-disable-gnome-ssh-askpass.html">here</a>, I ran the following command in the terminal:</p> <pre><code> unset SSH_ASKPASS </code></pre> <p>and then running <code>git push origin master</code> works the way it should. You can also add the line to your <code>.bashrc</code> file.</p>
58,399,123
UIHostingController should expand to fit contents
<p>I have a custom <code>UIViewControllerRepresentable</code> (layout-related code shown below). This tries to replicate the native SwiftUI <code>ScrollView</code>, except it scrolls from the bottom except the top.</p> <h3>View hierarchy</h3> <pre><code>view: UIView | \- scrollView: UIScrollView | \- innerView: UIView | \- hostingController.view: SwiftUI hosting view </code></pre> <p>This all works as intended when the view is initialized. The hosting view is populated with its contents, and the constraints make sure that the scroll view's <code>contentSize</code> is set properly.</p> <p>However, when the contents of the hosting view changes, the <code>hostingController.view</code> doesn't resize to fit its contents.</p> <p><a href="https://i.stack.imgur.com/oAk9F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oAk9F.png" alt="Screenshot of UI capture from app in Xcode. Shows contents of hosting controller expanding behind the bounds of the hosting view itself, without properly resizing." /></a></p> <blockquote> <p>Green: As intended, the scroll view matches the size of the hosting view controller.</p> <p>Blue: The hosting view itself. It keeps the size it had when it was first loaded, and doesn't expend as it should.</p> <p>Red: A stack view within the hosting view. In this screenshot, content was been added to the stack, causing it to expand. You can see the difference in size as a result.</p> </blockquote> <h3>The UIHostingController (blue) should expand to fit its contents (red).</h3> <p>The scroll view's content size is <em>not</em> explicitly set, because this is handled by auto layout.</p> <p>Constraint code is shown below, if it helps.</p> <pre><code>class UIBottomScrollViewController&lt;Content: View&gt;: UIViewController, UIScrollViewDelegate { var hostingController: UIHostingController&lt;Content&gt;! = nil init(rootView: Content) { self.hostingController = UIHostingController&lt;Content&gt;(rootView: rootView) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } var scrollView: UIScrollView = UIScrollView() var innerView = UIView() override func loadView() { self.view = UIView() self.addChild(hostingController) view.addSubview(scrollView) scrollView.addSubview(innerView) innerView.addSubview(hostingController.view) scrollView.delegate = self scrollView.scrollsToTop = true scrollView.isScrollEnabled = true scrollView.clipsToBounds = false scrollView.layoutMargins = .zero scrollView.preservesSuperviewLayoutMargins = true scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true innerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true innerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true innerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true innerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true innerView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true innerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true hostingController.view.topAnchor.constraint(equalTo: innerView.topAnchor).isActive = true hostingController.view.leftAnchor.constraint(equalTo: innerView.leftAnchor).isActive = true hostingController.view.rightAnchor.constraint(equalTo: innerView.rightAnchor).isActive = true hostingController.view.bottomAnchor.constraint(equalTo: innerView.bottomAnchor).isActive = true hostingController.view.autoresizingMask = [] hostingController.view.layoutMargins = .zero hostingController.view.insetsLayoutMarginsFromSafeArea = false hostingController.view.translatesAutoresizingMaskIntoConstraints = false scrollView.autoresizingMask = [] scrollView.layoutMargins = .zero scrollView.insetsLayoutMarginsFromSafeArea = false scrollView.translatesAutoresizingMaskIntoConstraints = false innerView.autoresizingMask = [] innerView.layoutMargins = .zero innerView.insetsLayoutMarginsFromSafeArea = false innerView.translatesAutoresizingMaskIntoConstraints = false hostingController.didMove(toParent: self) scrollView.keyboardDismissMode = .interactive } } struct BottomScrollView&lt;Content: View&gt;: UIViewControllerRepresentable { var content: () -&gt; Content init(@ViewBuilder content: @escaping () -&gt; Content) { self.content = content } func makeUIViewController(context: Context) -&gt; UIBottomScrollViewController&lt;Content&gt; { let vc = UIBottomScrollViewController(rootView: self.content()) return vc } func updateUIViewController(_ viewController: UIBottomScrollViewController&lt;Content&gt;, context: Context) { viewController.hostingController.rootView = self.content() } } </code></pre>
62,263,294
5
4
null
2019-10-15 16:33:44.307 UTC
7
2022-01-04 22:37:05.26 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,694,431
null
1
29
ios|swift|swiftui|ios-autolayout|uihostingcontroller
10,696
<p>I encountered the same issue with a similar-ish view hierarchy involving <code>UIHostingController</code> and scroll views, and found an ugly hack to make it work. Basically, I add a height constraint and update the constant manually:</p> <pre><code>private var heightConstraint: NSLayoutConstraint? ... override func viewDidLoad() { ... heightConstraint = viewHost.view.heightAnchor.constraint(equalToConstant: 0) ... } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // viewHost.view.sizeToFit() heightConstraint?.constant = viewHost.view.bounds.height heightConstraint?.isActive = true } </code></pre> <p>This is horrible code, but it's the only thing I found that made it work.</p>
17,662,210
SSIS Package: convert between unicode and non-unicode string data types
<p>I am connecting to an Oracle DB and the connection works, but I get the following error for some of the columns:</p> <pre><code>Description: Column "RESOURCE_NAME" cannot convert between unicode and non-unicode string data types. </code></pre> <p>Value for RESOURCE_NAME:</p> <ul> <li>For Oracle: <code>VARCHAR2(200 BYTE)</code> </li> <li>For SQL Server: <code>VARCHAR(200 BYTE)</code></li> </ul> <p>I can connect to the Oracle DB via Oracle SQL Developer without any issues. Also, I have the SSIS package setting <code>Run64BitRuntime = False</code>.</p>
17,662,710
8
0
null
2013-07-15 19:26:14.103 UTC
1
2020-08-24 22:18:14.123 UTC
2014-12-22 17:19:41.78 UTC
null
122,139
null
538,029
null
1
7
sql-server|oracle|unicode|ssis
94,733
<p>The Oracle data type <code>VARCHAR2</code> appears to be equivalent to <code>NVARCHAR</code> in SQL Server, or <code>DT_WSTR</code> in SSIS. <a href="http://msdn.microsoft.com/en-us/library/ms141036.aspx" rel="nofollow noreferrer" title="Integration Services Data Types">Reference</a></p> <p>You will have to convert using the <strong><em>Data Conversion Transformation</em></strong>, or <code>CAST</code> or <code>CONVERT</code> functions in SQL Server.</p>
17,156,143
How to Create a R TimeSeries for Hourly data
<p>I have hourly snapshot of an event starting from 2012-05-15-0700 to 2013-05-17-1800. How can I create a Timeseries on this data and perform HoltWinters to it?</p> <p>I tried the following</p> <pre><code>EventData&lt;-ts(Eventmatrix$X20030,start=c(2012,5,15),frequency=8000) HoltWinters(EventData) </code></pre> <p>But I got Error in decompose(ts(x[1L:wind], start = start(x), frequency = f), seasonal) : time series has no or less than 2 periods</p> <p>What value should I put from Frequency?</p>
17,156,401
2
1
null
2013-06-17 20:21:26.633 UTC
10
2015-07-23 15:13:55.02 UTC
null
null
null
null
30,546
null
1
12
r
27,967
<p>I think you should consider using <code>ets</code> from the package <code>forecast</code> to perform exponential smoothing. Read <a href="http://robjhyndman.com/hyndsight/estimation2/">this post</a> to have a comparison between <code>HoltWinters</code> and <code>ets</code> .</p> <pre><code>require(xts) require(forecast) time_index &lt;- seq(from = as.POSIXct("2012-05-15 07:00"), to = as.POSIXct("2012-05-17 18:00"), by = "hour") set.seed(1) value &lt;- rnorm(n = length(time_index)) eventdata &lt;- xts(value, order.by = time_index) ets(eventdata) </code></pre> <p>Now if you want to know more about the syntax of <code>ets</code> check the help of this function and the online book of Rob Hyndman (<a href="http://otexts.com/fpp/7/6/">Chap 7 section 6</a>)</p>
17,648,179
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
<p>I am trying to insert values into my comments table and I am getting a error. Its saying that I can not add or update child row and I have no idea what that means. My schema looks something like this:</p> <pre><code>-- -- Baza danych: `koxu1996_test` -- -- -------------------------------------------------------- -- -- Struktura tabeli dla tabeli `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` int(8) NOT NULL AUTO_INCREMENT, `username` varchar(32) COLLATE utf8_bin NOT NULL, `password` varchar(64) COLLATE utf8_bin NOT NULL, `password_real` char(32) COLLATE utf8_bin NOT NULL, `email` varchar(32) COLLATE utf8_bin NOT NULL, `code` char(8) COLLATE utf8_bin NOT NULL, `activated` enum('0','1') COLLATE utf8_bin NOT NULL DEFAULT '0', `activation_key` char(32) COLLATE utf8_bin NOT NULL, `reset_key` varchar(32) COLLATE utf8_bin NOT NULL, `name` varchar(32) COLLATE utf8_bin NOT NULL, `street` varchar(32) COLLATE utf8_bin NOT NULL, `house_number` varchar(32) COLLATE utf8_bin NOT NULL, `apartment_number` varchar(32) COLLATE utf8_bin NOT NULL, `city` varchar(32) COLLATE utf8_bin NOT NULL, `zip_code` varchar(32) COLLATE utf8_bin NOT NULL, `phone_number` varchar(16) COLLATE utf8_bin NOT NULL, `country` int(8) NOT NULL, `province` int(8) NOT NULL, `pesel` varchar(32) COLLATE utf8_bin NOT NULL, `register_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `authorised_time` datetime NOT NULL, `edit_time` datetime NOT NULL, `saldo` decimal(9,2) NOT NULL, `referer_id` int(8) NOT NULL, `level` int(8) NOT NULL, PRIMARY KEY (`id`), KEY `country` (`country`), KEY `province` (`province`), KEY `referer_id` (`referer_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=83 ; </code></pre> <p>and the mysql statement I am trying to do looks something like this:</p> <pre><code>INSERT INTO `user` (`password`, `code`, `activation_key`, `reset_key`, `register_time`, `edit_time`, `saldo`, `referer_id`, `level`) VALUES (:yp0, :yp1, :yp2, :yp3, NOW(), NOW(), :yp4, :yp5, :yp6). Bound with :yp0='fa1269ea0d8c8723b5734305e48f7d46', :yp1='F154', :yp2='adc53c85bb2982e4b719470d3c247973', :yp3='', :yp4='0', :yp5=0, :yp6=1 </code></pre> <p>the error I get looks like this:</p> <blockquote> <p>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (<code>koxu1996_test</code>.<code>user</code>, CONSTRAINT <code>user_ibfk_1</code> FOREIGN KEY (<code>country</code>) REFERENCES <code>country_type</code> (<code>id</code>) ON DELETE NO ACTION ON UPDATE NO ACTION)</p> </blockquote>
17,648,380
10
1
null
2013-07-15 06:44:42.323 UTC
1
2022-09-19 10:13:18.433 UTC
null
null
null
null
2,582,462
null
1
15
mysql|sql
93,315
<p>It just simply means that the value for column country on table comments you are inserting doesn't exist on table <strong>country_type</strong> or you are not inserting value for country on table <strong>user</strong>. Bear in mind that the values of column country on table comments is dependent on the values of ID on table <strong>country_type</strong>.</p>
19,681,642
Grep a Log file for the last occurrence of a string between two strings
<p>I have a log file <code>trace.log</code>. In it I need to grep for the content contained within the strings <code>&lt;tag&gt;</code> and <code>&lt;/tag&gt;</code>. There are multiple sets of this pair of strings, and I just need to return the content between last set (in other words, from the <code>tail</code> of the log file).</p> <p>Extra Credit: Any way I can return the content contained within the two strings only if the content contains "testString"? </p> <p>Thanks for looking.</p> <p>EDIT: The search parameters and are contained on different lines with about 100 lines of content separating them. The content is what I'm after...</p>
19,681,732
5
3
null
2013-10-30 11:59:29.857 UTC
7
2015-06-15 14:56:47.79 UTC
2013-10-30 12:20:25.587 UTC
null
349,268
null
349,268
null
1
26
unix|grep|tail
47,313
<p>Use <code>tac</code> to print the file the other way round and then <code>grep -m1</code> to just print one result. The look behind and look ahead checks text in between <code>&lt;tag&gt;</code> and <code>&lt;/tag&gt;</code>.</p> <pre><code>tac a | grep -m1 -oP '(?&lt;=tag&gt;).*(?=&lt;/tag&gt;)' </code></pre> <h3>Test</h3> <p>Given this file</p> <pre><code>$ cat a &lt;tag&gt; and &lt;/tag&gt; aaa &lt;tag&gt; and &lt;b&gt; other things &lt;/tag&gt; adsaad &lt;tag&gt;and last one&lt;/tag&gt; $ tac a | grep -m1 -oP '(?&lt;=tag&gt;).*(?=&lt;/tag&gt;)' and last one </code></pre> <hr> <h1>Update</h1> <blockquote> <p>EDIT: The search parameters and are contained on different lines with about 100 lines of content separating them. The content is what I'm after...</p> </blockquote> <p>Then it is a bit more tricky:</p> <pre><code>tac file | awk '/&lt;\/tag&gt;/ {p=1; split($0, a, "&lt;/tag&gt;"); $0=a[1]}; /&lt;tag&gt;/ {p=0; split($0, a, "&lt;tag&gt;"); $0=a[2]; print; exit}; p' | tac </code></pre> <p>The idea is to reverse the file and use a flag <code>p</code> to check if the <code>&lt;tag&gt;</code> has appeared yet or not. It will start printing when <code>&lt;/tag&gt;</code> appears and finished when <code>&lt;tag&gt;</code> comes (because we are reading the other way round).</p> <ul> <li><code>split($0, a, "&lt;/tag&gt;"); $0=a[1];</code> gets the data before <code>&lt;/tag&gt;</code></li> <li><code>split($0, a, "&lt;tag&gt;" ); $0=a[2];</code> gets the data after <code>&lt;tag&gt;</code></li> </ul> <h3>Test</h3> <p>Given a file <code>a</code> like this:</p> <pre><code>&lt;tag&gt; and &lt;/tag&gt; aaa &lt;tag&gt; and &lt;b&gt; other thing come here and here &lt;/tag&gt; some text&lt;tag&gt;tag is starting here blabla and ends here&lt;/tag&gt; </code></pre> <p>The output will be:</p> <pre><code>$ tac a | awk '/&lt;\/tag&gt;/ {p=1; split($0, a, "&lt;/tag&gt;"); $0=a[1]}; /&lt;tag&gt;/ {p=0; split($0, a, "&lt;tag&gt;"); $0=a[2]; print; exit}; p' | tac tag is starting here blabla and ends here </code></pre>
19,726,115
Comparing user input date with current date
<p>Hi im trying to compare a user inputted date (as a string) with the current date so as to find out if the date is earlier or older.</p> <p>My current code is</p> <pre><code>String date; Date newDate; Date todayDate, myDate; SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); while(true) { Scanner s = new Scanner (System.in); date = s.nextLine(); Calendar cal = Calendar.getInstance(); try { // trying to parse current date here // newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception // trying to parse inputted date here myDate = dateFormatter.parse(date); //no exception } catch (ParseException e) { e.printStackTrace(System.out); } } </code></pre> <p>Im trying to get both user input date and current date into two Date objects, so that i can use Date.compareTo() to simplify comparing dates.</p> <p>I was able to parse the user input string into the Date object. However the current date cal.getTime().toString() does not parse into the Date object due to being an invalid string.</p> <p>How to go about doing this? Thanks in advance</p>
19,726,145
7
3
null
2013-11-01 11:44:41.497 UTC
3
2021-04-16 05:40:51.01 UTC
null
null
null
null
1,234,897
null
1
11
java|date|calendar|simpledateformat
113,109
<p>You can get the current <code>Date</code> with:</p> <pre><code>todayDate = new Date(); </code></pre> <p>EDIT: Since you need to compare the dates without considering the time component, I recommend that you see this: <a href="https://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion">How to compare two Dates without the time portion?</a></p> <p>Despite the 'poor form' of the one answer, I actually quite like it:</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sdf.format(date1).equals(sdf.format(date2)); </code></pre> <p>In your case, you already have:</p> <pre><code>SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); </code></pre> <p>so I would consider (for simplicity rather than performance):</p> <pre><code>todayDate = dateFormatter.parse(dateFormatter.format(new Date() )); </code></pre>
19,760,138
Parsing JSON in Java without knowing JSON format
<p>I am trying to parse JSON strings in Java and find the key-value pairs so that I can determine the approximate structure of the JSON object since object structure of JSON string is unknown.</p> <p>For example, one execution may have a JSON string like this:</p> <pre><code> {"id" : 12345, "days" : [ "Monday", "Wednesday" ], "person" : { "firstName" : "David", "lastName" : "Menoyo" } } </code></pre> <p>And another like this:</p> <pre><code> {"url" : "http://someurl.com", "method" : "POST", "isauth" : false } </code></pre> <p>How would I cycle through the various JSON elements and determine the keys and their values? I looked at <code>jackson-core</code>'s <a href="http://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/JsonParser.html" rel="noreferrer"><code>JsonParser</code></a>. I see how I can grab the next "token" and determine what type of token it is (i.e., field name, value, array start, etc), but, I don't know how to grab the actual token's value.</p> <p>For example:</p> <pre><code>public void parse(String json) { try { JsonFactory f = new JsonFactory(); JsonParser parser = f.createParser(json); JsonToken token = parser.nextToken(); while (token != null) { if (token.equals(JsonToken.START_ARRAY)) { logger.debug("Start Array : " + token.toString()); } else if (token.equals(JsonToken.END_ARRAY)) { logger.debug("End Array : " + token.toString()); } else if (token.equals(JsonToken.START_OBJECT)) { logger.debug("Start Object : " + token.toString()); } else if (token.equals(JsonToken.END_OBJECT)) { logger.debug("End Object : " + token.toString()); } else if (token.equals(JsonToken.FIELD_NAME)) { logger.debug("Field Name : " + token.toString()); } else if (token.equals(JsonToken.VALUE_FALSE)) { logger.debug("Value False : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NULL)) { logger.debug("Value Null : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_FLOAT)) { logger.debug("Value Number Float : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_INT)) { logger.debug("Value Number Int : " + token.toString()); } else if (token.equals(JsonToken.VALUE_STRING)) { logger.debug("Value String : " + token.toString()); } else if (token.equals(JsonToken.VALUE_TRUE)) { logger.debug("Value True : " + token.toString()); } else { logger.debug("Something else : " + token.toString()); } token = parser.nextToken(); } } catch (Exception e) { logger.error("", e); } } </code></pre> <p>Is there a class in <code>jackson</code> or some other library (<code>gson</code> or <code>simple-json</code>) that produces a tree, or allows one to cycle through the json elements and obtain the actual key names in addition to the values?</p>
19,760,249
7
4
null
2013-11-04 00:55:33.413 UTC
27
2021-07-03 15:35:14.35 UTC
null
null
null
null
2,333,544
null
1
65
java|json|parsing|jackson
162,537
<p>Take a look at <a href="http://wiki.fasterxml.com/JacksonTreeModel" rel="noreferrer">Jacksons built-in tree model feature</a>.</p> <p>And your code will be:</p> <pre><code>public void parse(String json) { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonNode rootNode = mapper.readTree(json); Iterator&lt;Map.Entry&lt;String,JsonNode&gt;&gt; fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry&lt;String,JsonNode&gt; field = fieldsIterator.next(); System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue()); } } </code></pre>
17,272,612
Android Webview: disable CORS
<p>Does Android allow native apps to disable CORS security policies for http:// (not local/file) requests?</p> <p>In my native app, a webview shows a remote html via http://, not on the local/file system. This seems to be CORS-restricted in the same way as within webbrowsers.</p> <p>Worakround: A native-js bridge for ajax requests to cross-domains which do not have <code>Access-Control-Allow-Origin: *</code> is my quick'n'dirt solution. (jsonp or server-side proxy is not an option because cookie+ip of client are checked by the webservice.)</p> <p>Can this policy be disabled for inapp webviews?</p> <p>Please let me know, if there is a simple flag for allowing js to bypass this restriction which limits the "native" app's webview.</p>
17,272,798
3
0
null
2013-06-24 09:53:26.837 UTC
8
2021-08-27 06:43:21.057 UTC
null
null
null
null
1,436,033
null
1
22
android|webview|cors
41,080
<p>AFAIK this is not possible, and believe me, I've tried many ways.</p> <p>The best you can do is override resource loading. See <a href="https://stackoverflow.com/questions/4780899/intercept-and-override-http-requests-from-webview">Intercept and override HTTP-requests from WebView</a></p>
17,351,043
How to get absolute path to file in /resources folder of your project
<p>Assume standard maven setup.</p> <p>Say in your resources folder you have a file <code>abc</code>. </p> <p>In Java, how can I get absolute path to the file please?</p>
17,351,116
6
3
null
2013-06-27 18:52:16.223 UTC
25
2019-12-07 18:16:03.797 UTC
2019-09-24 07:28:49.997 UTC
null
11,881,714
null
359,862
null
1
124
java|maven|file|resources
331,853
<p>You can use <code>ClassLoader.getResource</code> method to get the correct resource.</p> <pre><code>URL res = getClass().getClassLoader().getResource("abc.txt"); File file = Paths.get(res.toURI()).toFile(); String absolutePath = file.getAbsolutePath(); </code></pre> <p>OR</p> <p>Although this may not work all the time, a simpler solution -</p> <p>You can create a <code>File</code> object and use <code>getAbsolutePath</code> method:</p> <pre><code>File file = new File("resources/abc.txt"); String absolutePath = file.getAbsolutePath(); </code></pre>
18,300,674
window.location.href not working
<p>My website is <a href="http://www.collegeanswerz.com/" rel="noreferrer">http://www.collegeanswerz.com/</a>. I'm using rails. The code is for searching for colleges. I want the user to be able to type in the colleges name, click enter, and be taken to the url, rather than seeing the search results (if the user types in the name properly. if not I want to show the search results). I'm using "a" and "stackoverflow.com" as placeholders while I try to get it to work.</p> <p>I'm using window.location.href based on this: <a href="https://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript">How to redirect to another webpage in JavaScript/jQuery?</a></p> <p>javascript</p> <pre><code>$("#search_text").submit(function() { if ($("#search_field").val() == "a") { window.location.href = "http://stackoverflow.com"; alert('worked'); } }); </code></pre> <p>layout file</p> <pre><code>&lt;%= form_tag("/search", :method =&gt; 'get', :id =&gt; 'search_text', :class =&gt; 'form_search') do -%&gt; &lt;div id="search"&gt; &lt;%= search_field_tag :search, params[:search], :placeholder =&gt; 'enter college', :id =&gt; "search_field", :class =&gt; 'input-medium search-query' %&gt;&lt;/div&gt; &lt;% end -%&gt; </code></pre> <p>static_pages_controller.rb</p> <pre><code>def search @colleges = College.search(params[:search]) end </code></pre> <p>The alert is working, which tells me that the things inside the if statement should be being executed. But it's taking me to the normal search results instead of stackoverflow.com. Why is this?</p>
18,300,733
4
6
null
2013-08-18 15:24:10.687 UTC
3
2020-05-09 01:19:53.843 UTC
2017-05-23 11:54:54.673 UTC
null
-1
null
1,927,876
null
1
16
jquery|ruby-on-rails|window.location
124,999
<p>The browser is still submitting the form after your code runs.</p> <p>Add <code>return false;</code> to the handler to prevent that.</p>
12,108,237
Codeigniter: foreach method or result array?? [Models +View]
<p>I am currently following tutorials on viewing data from the database using the Framework Codeigniter. There are various ways in which I've learnt. Is there is a more realiable way- either displaying as an array or using 'foreach' in the view file? Any opinions would be helpful. </p> <p>This is my code using the two methods:</p> <p>Method 1 Model:</p> <pre><code>function getArticle(){ $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;from('test'); $this-&gt;db-&gt;where('author','David'); $this-&gt;db-&gt;order_by('id', 'DESC'); $query=$this-&gt;db-&gt;get(); if($query-&gt;num_rows() &gt; 0) { foreach ($query-&gt;result() as $row) { $data[] = $row; } return $data; }$query-&gt;free_result(); } </code></pre> <p>}</p> <p>Method 1 View file:</p> <pre><code> &lt;?php foreach($article as $row){ ?&gt; &lt;h3&gt;&lt;?php echo $row-&gt;title; ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php echo $row-&gt;content; ?&gt;&lt;/p&gt; &lt;p&gt;&lt;?php echo $row-&gt;author; ?&gt;&lt;/p&gt; &lt;p&gt;&lt;?php echo $row-&gt;date; ?&gt;&lt;/p&gt; &lt;?php } ?&gt; </code></pre> <p>Method 2 Model: class News_model extends CI_Model {</p> <pre><code>function getArticle(){ $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;from('test'); $this-&gt;db-&gt;where('author', 'David'); $this-&gt;db-&gt;order_by('id', 'DESC'); $query=$this-&gt;db-&gt;get(); if ($query-&gt;num_rows()&gt;0) { return $query-&gt;row_array(); } $query-&gt;free_result(); } </code></pre> <p>Method 2 View file:</p> <pre><code> &lt;?php echo '&lt;h3&gt;' .$article['title'].'&lt;/h3&gt;' ?&gt; &lt;?php echo '&lt;p&gt;' .$article['content']. '&lt;/p&gt;' ?&gt; &lt;?php echo '&lt;p&gt;' .$article['author']. '&lt;/p&gt;' ?&gt; &lt;?php echo '&lt;p&gt;'. $article['date']. '&lt;/p&gt;' ?&gt; </code></pre>
12,108,989
1
4
null
2012-08-24 11:08:51.17 UTC
4
2017-06-12 20:39:21.337 UTC
null
null
null
null
1,566,231
null
1
4
php|arrays|codeigniter|model|foreach
69,143
<p>I would do it like that:</p> <p><strong>Model</strong></p> <pre><code>function getArticle() { $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;from('test'); $this-&gt;db-&gt;where('author','David'); $this-&gt;db-&gt;order_by('id', 'DESC'); return $this-&gt;db-&gt;get()-&gt;result(); } </code></pre> <p>}</p> <p><strong>Controller</strong></p> <pre><code>function get_tests() { $data = array( 'tests' =&gt; $this-&gt;mymodel-&gt;getArticle() } $this-&gt;load-&gt;view('myview', $data); } </code></pre> <p><strong>View</strong></p> <pre><code>&lt;table&gt; &lt;?php foreach($tests as $test) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $test-&gt;title;?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $test-&gt;content;?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $test-&gt;author;?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $test-&gt;date;?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>If you wish to work with arrays rather than objects, in your model change line</p> <pre><code>return $this-&gt;db-&gt;get()-&gt;result(); </code></pre> <p>to </p> <pre><code>return $this-&gt;db-&gt;get()-&gt;result_array(); </code></pre> <p>and in views echo like</p> <pre><code>&lt;td&gt;&lt;?php echo $test['title'];?&gt;&lt;/td&gt; </code></pre> <p>P.S.</p> <p>In your code you use <code>$query-&gt;free_result();</code> but it doesn't even run because when you use keyword <code>return</code> everything after that is not even parsed. It's not necessary to free results anyway.</p> <p>P.S.2.</p> <p>You use <code>if($query-&gt;num_rows() &gt; 0) {</code> but don't have the <code>else</code> part, it means that it's not necessary too. If you'll return no lines to your foreach statement in the view, you won't get any errors.</p>
23,295,315
get Key by value, dict, python
<p>How can I get a key from a value? </p> <p>my dict: </p> <pre><code>countries = { "Normal UK project" : "1", "UK Omnibus project" : "1-Omni", "Nordic project" : ["11","12","13","14"], "German project" : "21", "French project" : "31" } </code></pre> <p>my semi functioning code:</p> <pre><code>for k, v in countries.items(): if "1" in v: print k </code></pre> <p>expected output:</p> <pre><code>Normal UK project </code></pre> <p>actual output: </p> <pre><code>French project UK Omnibus project German project Normal UK project </code></pre> <p>How can I fix my code? </p>
23,295,614
7
9
null
2014-04-25 14:00:21.15 UTC
5
2017-09-22 04:29:12.22 UTC
null
null
null
null
2,342,399
null
1
10
python|dictionary|key-value
64,116
<p>The problem is that the types of the values in the dictionary are not the same, making it much more difficult to use the dictionary, not only in this scenario. While Python allows this, you really should consider unifying the types in the dictionary, e.g. make them all lists. You can do so in just one line of code:</p> <pre><code>countries = {key: val if isinstance(val, list) else [val] for key, val in countries.items()} </code></pre> <p>Now, each single string is wrapped into a list and your existing code will work correctly.</p> <p>Alternatively, if you have to use the dictionary in it's current form, you can adapt your lookup function:</p> <pre><code>for k, v in countries.items(): if "1" == v or isinstance(v, list) and "1" in v: print k </code></pre>
31,984,196
Jupyter notebook run all cells on open
<p>I have a Jupyter noteboook and I'm trying to set it up in a way so that all cells are ran automatically when the notebook is opened.</p> <p>This behaviour is different from saved output for notebooks which contain widgets. Widgets only seem to get rendered for me when the cells containing them are run. Consider the following example:</p> <pre><code>from IPython.display import display from IPython.html.widgets import IntSlider w = IntSlider() display(w) </code></pre> <p>The slider is not displayed until the cell is executed.</p> <p>Is this something that can be accomplished through Notebook Metadata or configuration files?</p> <p><strong>EDIT:</strong> <a href="https://try.jupyter.org/" rel="noreferrer">https://try.jupyter.org/</a> seems to be doing something like this: Notice that the notebooks are not running when you open the page and display output when they are opened.</p> <p><strong>EDIT2:</strong> Adding example.</p>
38,856,870
4
5
null
2015-08-13 09:18:59.147 UTC
14
2022-08-08 16:15:18.663 UTC
2020-07-14 09:07:13.193 UTC
null
1,198,642
null
1,198,642
null
1
17
python|jupyter-notebook|ipython|jupyter
24,007
<ol> <li>Paste the snippet below in a normal(code) cell, </li> <li>execute it (hit <em>[Ctrl + Enter]</em>), and</li> <li><em>Save</em> the notebook.</li> </ol> <p>The next time you (re)load it, all cells will run and a checkpoint will be saved with their refreshed outputs.</p> <pre><code>%%html &lt;script&gt; // AUTORUN ALL CELLS ON NOTEBOOK-LOAD! require( ['base/js/namespace', 'jquery'], function(jupyter, $) { $(jupyter.events).on("kernel_ready.Kernel", function () { console.log("Auto-running all cells-below..."); jupyter.actions.call('jupyter-notebook:run-all-cells-below'); jupyter.actions.call('jupyter-notebook:save-notebook'); }); } ); &lt;/script&gt; </code></pre> <p>Note that if you clear the output of the above cell, you have to repeat steps 2 and 3.</p> <h2>TIP</h2> <p>You may consider these more appropriate solutions for what you are probably trying to achieve:</p> <ul> <li><a href="https://github.com/oreillymedia/thebe" rel="noreferrer">Jupyer Thebe</a>: embed code-snippets in static pages communicating with ipython-kernels backends.</li> <li><img src="https://cloud.githubusercontent.com/assets/836375/15271096/98e4c102-19fe-11e6-999a-a74ffe6e2000.gif" height="32" alt="nteract"/><a href="http://nteract.io/" rel="noreferrer">nteract</a>: Build <a href="http://electron.atom.io/" rel="noreferrer">Electron</a>-based applications from notebooks.</li> <li><a href="https://github.com/jupyter-incubator/dashboards" rel="noreferrer">Dashboards</a>: The "official"efforts to allow to pre-configure a grid of notebook-cell outputs ("dashboards"), package and serve them as standalone web apps.</li> </ul> <p>You can find a summary of the situation in <a href="https://blog.ouseful.info/2016/01/25/whats-on-the-horizon-in-the-jupyter-ecosystem/" rel="noreferrer">this article</a>.</p> <h3>Controversy</h3> <p>Similar questions has been <a href="https://github.com/ivanov/ipython-trainingwheels/issues/35" rel="noreferrer">asked</a> <a href="https://github.com/ipython/ipython/issues/3164" rel="noreferrer">before</a> in <a href="https://groups.google.com/forum/#!topic/jupyter/G9A9ukx4Cr8" rel="noreferrer">other sites</a>, but in <a href="https://groups.google.com/forum/#!msg/jupyter/WHTnfAQw9gY/Lc0GZwwiBAAJ" rel="noreferrer">this googlegroup thread</a>, someone submitted a solution, and <em>the group moderator erased it(!)</em>, obviously to preserve life on earth :-) So, be careful with it!</p>
5,491,150
how to do postback Javascript, jquery
<pre><code>&lt;asp:Button ID="btn" OnClientClick="if(confirm_delete()){ /* post back*/ }else{ return false; };" OnClick="btnDelete_Click" runat="server" Text="delete"/&gt; </code></pre> <p>Hi I have this code but I cant do postback for it, im not sure how to?</p> <p>is it:</p> <pre><code>&lt;script type="text/javascript"&gt; function CallServer() { __doPostBack('not sure what goes here','or here'); } &lt;/script&gt; </code></pre> <p>Then:</p> <pre><code>&lt;asp:Button ID="btn" OnClientClick="if(confirm_delete()){ /CallServer()/ }else{ return false; };" OnClick="btnDelete_Click" runat="server" Text="delete"/&gt; </code></pre> <p>My other script:</p> <pre><code>&lt;script type="text/javascript"&gt; function confirm_delete() { if (confirm("Are you sure you want to delete this comment?")==true) return true; else return false; } &lt;/script&gt; </code></pre> <p><strong>EDIT:</strong></p> <p>On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Odbc; using System.IO; public partial class UserProfileWall : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //btn.Visible = false; string theUserId = Session["UserID"].ToString(); PopulateWallPosts(theUserId); } private void PopulateWallPosts(string userId) { using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;")) { cn.Open(); using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn)) { //("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn)) using (OdbcDataReader reader = cmd.ExecuteReader()) { test1.Controls.Clear(); while (reader.Read()) { System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div"); div.Attributes["class"] = "test"; div.ID = String.Format("{0}", reader.GetString(0)); // this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID Image img = new Image(); img.ImageUrl = String.Format("{0}", reader.GetString(2)); img.AlternateText = "Test image"; div.Controls.Add(img); div.Controls.Add(ParseControl(String.Format("&amp;nbsp&amp;nbsp&amp;nbsp;" + "{0}", reader.GetString(1)))); div.Attributes.Add("onclick", "return confirm_delete();"); div.Style["clear"] = "both"; test1.Controls.Add(div); } } } } } //protected void btnDelete_Click(object sender, EventArgs e) //{ // string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26"; // string[] idFragments = id.Split('_'); // id = idFragments[idFragments.Length - 1]; // //serverside code if confirm was pressed. // using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;")) // { // cn.Open(); // using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn)) // { // cmd.ExecuteNonQuery(); // } // } // //PopulateWallPosts(); //} protected void Button1_Click(object sender, EventArgs e) { string theUserId = Session["UserID"].ToString(); using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;")) { cn.Open(); using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn)) { cmd.ExecuteNonQuery(); } } PopulateWallPosts(theUserId); } protected void btn_Click(object sender, EventArgs e) { string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26"; string[] idFragments = id.Split('_'); id = idFragments[idFragments.Length - 1]; //serverside code if confirm was pressed. using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;")) { cn.Open(); using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn)) { cmd.ExecuteNonQuery(); } } //PopulateWallPosts(); } } </code></pre> <p>On my asp.net html side i have:</p> <pre><code>&lt;script type="text/javascript"&gt; function confirm_delete() { if (confirm("Are you sure you want to delete this comment?")==true) return true; else return false; } &lt;/script&gt; &lt;p&gt; &lt;asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server" CssClass="Btn" Text="delete" onclick="btn_Click"/&gt; &lt;asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3" Height="47px" Width="638px"&gt;&lt;/asp:TextBox&gt; &lt;/p&gt; &lt;p&gt; &lt;asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px" onclick="Button1_Click" /&gt; &lt;/p&gt; &lt;p&gt; &lt;/p&gt; &lt;style type="text/css"&gt; img {border-width:0px; width:100px; height:100px;} &lt;/style&gt; &lt;div id="test1" runat="server" /&gt; &lt;/div&gt; &lt;/asp:Content&gt; </code></pre> <p>If you notice in my server side code I added this line:</p> <pre><code>div.Attributes.Add("onclick", "return confirm_delete();") </code></pre> <p>This works any time I click on my div the <code>confirm_delete</code> is called.</p> <p>What I was trying to do with my asp.net button was when the div was clicked I could then call the <code>onclick btnDelete_click</code>. </p>
5,491,316
4
5
null
2011-03-30 19:20:02.527 UTC
0
2015-09-14 19:50:30.07 UTC
2015-09-14 19:50:30.07 UTC
null
4,111,568
null
477,228
null
1
3
javascript|jquery|asp.net
41,427
<pre><code>OnClientClick="return confirm_delete();" </code></pre> <p>That's it...</p> <p>Edit: __doPostBack works also...</p> <pre><code>OnClientClick="if(confirm('delete?'))__doPostBack('btn',''); else return false;" </code></pre>
9,609,731
onchange event for input type="number"
<p>How can I handle an onchange for <code>&lt;input type="number" id="n" value="5" step=".5" /&gt;</code> ? I can't do a <code>keyup</code> or <code>keydown</code>, because, the user may just use the arrows to change the value. I would want to handle it whenever it changes, not just on blur, which I think the <code>.change()</code> event does. Any ideas?</p>
9,609,879
11
3
null
2012-03-07 21:58:01.667 UTC
12
2021-05-31 16:13:20.013 UTC
null
null
null
null
988,233
null
1
96
jquery|html
225,339
<p>Use mouseup and keyup</p> <pre><code>$(":input").bind('keyup mouseup', function () { alert("changed"); }); </code></pre> <p><a href="http://jsfiddle.net/XezmB/2/" rel="noreferrer">http://jsfiddle.net/XezmB/2/</a></p>
18,424,624
Using selenium to save images from page
<p>I'm using Selenium &amp; Google Chrome Driver to open pages programatically. On each page there is a dynamically generated image which I'd like to download. At the moment, I'm waiting for the page to finish loading, then I grab the image URL and download it using System.Net.WebClient.</p> <p>That works fine except I'm downloading the images twice - once in the browser, once with WebClient. The problem is that each image is roughly 15MB and downloading twice adds up quickly.</p> <p>So - is it possible to grab the image straight from Google Chrome?</p>
18,674,724
10
1
null
2013-08-25 00:52:25.25 UTC
8
2020-09-04 00:44:03.303 UTC
null
null
null
null
171,846
null
1
7
c#|selenium|download|selenium-chromedriver
32,735
<p>You can block images from being downloaded in Google Chrome using <a href="https://stackoverflow.com/a/18674383/171846">this</a> technique. It runs a Google Chrome extension called &quot;Block Image&quot;. This way the image won't be downloaded using chrome, and it's just a matter of downloading the image as normal using its URL &amp; System.Net.WebClient.</p>
18,313,576
Confirmation dialog on ng-click - AngularJS
<p>I am trying to setup a confirmation dialog on an <code>ng-click</code> using a custom angularjs directive:</p> <pre><code>app.directive('ngConfirmClick', [ function(){ return { priority: 1, terminal: true, link: function (scope, element, attr) { var msg = attr.ngConfirmClick || "Are you sure?"; var clickAction = attr.ngClick; element.bind('click',function (event) { if ( window.confirm(msg) ) { scope.$eval(clickAction) } }); } }; }]) </code></pre> <p>This works great but unfortunately, expressions inside the tag using my directive are not evaluated:</p> <pre><code>&lt;button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?"&gt;Say hi to {{ name }}&lt;/button&gt; </code></pre> <p>(name is not evaluated is this case). It seems to be due to the terminal parameter of my directive. Do you have any ideas of workaround? </p> <p>To test my code: <a href="http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview" rel="noreferrer">http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview</a></p>
18,313,962
17
2
null
2013-08-19 12:15:09.2 UTC
15
2021-10-16 04:31:13.207 UTC
2016-03-23 08:38:16.17 UTC
null
863,110
null
112,976
null
1
86
javascript|angularjs|angularjs-directive|angularjs-scope
254,078
<p>If you don't mind not using <code>ng-click</code>, it works OK. You can just rename it to something else and still read the attribute, while avoiding the click handler being triggered twice problem there is at the moment.</p> <p><a href="http://plnkr.co/edit/YWr6o2?p=preview">http://plnkr.co/edit/YWr6o2?p=preview</a></p> <p>I think the problem is <code>terminal</code> instructs other directives not to run. Data-binding with <code>{{ }}</code> is just an alias for the <code>ng-bind</code> directive, which is presumably cancelled by <code>terminal</code>. </p>
20,116,444
SEVERE: A message body writer for Java class java.util.ArrayList and MIME media type application/json was not found
<p>I am testing RESTful services and when I execute I am getting exceptions although I have the following jars in my class path(WEB-INF/lib), I am not using Maven and my JDK version is 1.5. Other questions regarding this issue didn't help to resolve the problem.</p> <p>Code snippet</p> <pre><code>@GET @Produces("application/json") //@Produces({MediaType.APPLICATION_JSON}) tried this, didn't work either public List&lt;Emp&gt; getEmployees() { List&lt;Emp&gt; empList = myDAO.getAllEmployees(); log.info("size " + empList.size()); return empList; } @XmlRootElement public class Emp { ...... </code></pre> <p><strong>web.xml</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;servlet&gt; &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;test.employees&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.api.json.POJOMappingFeature&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt; &lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p><strong>List of jars</strong></p> <pre><code>jersey-server-1.2.jar jersey-core-1.2.jar jsr311-api-1.1.jar asm-3.1.jar jaxb-api-2.0.jar jaxb-impl-2.0.jar jackson-xc-1.2.0.jar jackson-jaxrs-1.2.0.jar jackson-mapper-asl-1.2.0.jar jackson-core-asl-1.2.0.jar jettison-1.2.jar jersey-client-1.2.jar jersey-servlet-1.10.jar jersey-json-1.8.jar </code></pre> <p><strong>Exception stack</strong></p> <pre><code> SEVERE: A message body writer for Java class java.util.ArrayList, and Java type java.util.List&lt;test.Emp&gt;, and MIME media type application/json was not found Nov 21, 2013 11:47:26 AM com.sun.jersey.spi.container.ContainerResponse traceException SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException at javax.ws.rs.WebApplicationException.&lt;init&gt;(WebApplicationException.java:97) at javax.ws.rs.WebApplicationException.&lt;init&gt;(WebApplicationException.java:55) at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:267) at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1035) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:947) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:939) at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:399) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:478) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:663) at javax.servlet.http.HttpServlet.service(HttpServlet.java:856) at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719) at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376) at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870) at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451) at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218) at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119) at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112) at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260) at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:230) at oracle.oc4j.network.ServerSocketAcceptHandler.access$800(ServerSocketAcceptHandler.java:33) at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:831) at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303) at java.lang.Thread.run(Thread.java:595) </code></pre> <p>How can I resolve this issue?</p>
20,122,256
9
3
null
2013-11-21 09:01:59.79 UTC
null
2020-04-24 10:02:40.02 UTC
2015-12-26 21:19:22.883 UTC
null
3,885,376
null
599,528
null
1
16
java|rest|jersey|oc4j|java-5
77,619
<p>Make sure you don't have multiple Jersey versions in your project. From the list you provided there are modules from 3 different versions (1.2, 1.10, 1.8). For some modules Jersey does a check that the version of a module is the same as the version of the core. If it's not then providers of the module (such as MessageBodyReaders, MessageBodyWriters) are not registered in the runtime. This can be problem in your setup - json vs core (1.8 vs 1.2).</p>
15,259,547
conditional sums for pandas aggregate
<p>I just recently made the switch from R to python and have been having some trouble getting used to data frames again as opposed to using R's data.table. The problem I've been having is that I'd like to take a list of strings, check for a value, then sum the count of that string- broken down by user. So I would like to take this data:</p> <pre><code> A_id B C 1: a1 "up" 100 2: a2 "down" 102 3: a3 "up" 100 3: a3 "up" 250 4: a4 "left" 100 5: a5 "right" 102 </code></pre> <p>And return:</p> <pre><code> A_id_grouped sum_up sum_down ... over_200_up 1: a1 1 0 ... 0 2: a2 0 1 0 3: a3 2 0 ... 1 4: a4 0 0 0 5: a5 0 0 ... 0 </code></pre> <p>Before I did it with the R code (using data.table)</p> <pre><code>&gt;DT[ ,list(A_id_grouped, sum_up = sum(B == "up"), + sum_down = sum(B == "down"), + ..., + over_200_up = sum(up == "up" &amp; &lt; 200), by=list(A)]; </code></pre> <p>However all of my recent attempts with Python have failed me:</p> <pre><code>DT.agg({"D": [np.sum(DT[DT["B"]=="up"]),np.sum(DT[DT["B"]=="up"])], ... "C": np.sum(DT[(DT["B"]=="up") &amp; (DT["C"]&gt;200)]) }) </code></pre> <p>Thank you in advance! it seems like a simple question however I couldn't find it anywhere.</p>
15,262,146
4
0
null
2013-03-06 22:39:42.59 UTC
9
2021-12-05 10:40:51.627 UTC
null
null
null
null
1,529,734
null
1
23
python|r|pandas|data.table
21,693
<p>To complement unutbu's answer, here's an approach using <code>apply</code> on the groupby object.</p> <pre><code>&gt;&gt;&gt; df.groupby('A_id').apply(lambda x: pd.Series(dict( sum_up=(x.B == 'up').sum(), sum_down=(x.B == 'down').sum(), over_200_up=((x.B == 'up') &amp; (x.C &gt; 200)).sum() ))) over_200_up sum_down sum_up A_id a1 0 0 1 a2 0 1 0 a3 1 0 2 a4 0 0 0 a5 0 0 0 </code></pre>
15,055,634
understanding and decoding the file mode value from stat function output
<p>I have been trying to understand what exactly is happening in the below mentioned code. But i am not able to understand it. </p> <pre><code>$mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode &amp; 07777; </code></pre> <p><strong>Lets say my $mode value is 33188</strong></p> <p><strong>$mode &amp; 07777 yields a value = 420</strong></p> <ul> <li><p>is the $mode value a decimal number ?</p></li> <li><p>why we are choosing 07777 and why we are doing a bitwise and operation. I am not able to underand the logic in here.</p></li> </ul>
15,059,931
2
1
null
2013-02-24 19:26:58.577 UTC
10
2014-01-07 17:14:21.333 UTC
2013-02-26 14:41:57.5 UTC
null
123,109
null
1,878,947
null
1
25
linux|perl|unix|permissions|stat
19,128
<p>The mode from your question corresponds to a regular file with 644 permissions (read-write for the owner and read-only for everyone else), but don’t take my word for it.</p> <pre>$ touch foo $ chmod 644 foo $ perl -le 'print +(stat "foo")[2]' 33188</pre> <p>The value of <code>$mode</code> <em>can</em> be viewed as a decimal integer, but doing so is not particularly enlightening. Seeing the octal representation gives something a bit more familiar.</p> <pre>$ perl -e 'printf "%o\n", (stat "foo")[2]' 100644</pre> <p>Bitwise AND with 07777 gives the last twelve bits of a number’s binary representation. With a Unix mode, this operation gives the permission or mode bits and discards any type information.</p> <pre>$ perl -e 'printf "%d\n", (stat "foo")[2] & 07777' # decimal, not useful 420 $ perl -e 'printf "%o\n", (stat "foo")[2] & 07777' # octal, eureka! 644</pre> <p>A nicer way to do this is below. Read on for all the details.</p> <hr> <h2>Mode Bits</h2> <p>The third element returned from <code>stat</code> (which corresponds to <code>st_mode</code> in <code>struct stat</code>) is a <a href="https://en.wikipedia.org/wiki/Bit_field">bit field</a> where the different bit positions are binary flags.</p> <p>For example, one bit in <code>st_mode</code> POSIX names <code>S_IWUSR</code>. A file or directory whose mode has this bit set is writable by its owner. A related bit is <code>S_IROTH</code> that when set means other users (<em>i.e.</em>, neither the owner nor in the group) may read that particular file or directory.</p> <p>The <a href="http://perldoc.perl.org/functions/stat.html">perlfunc documentation for <code>stat</code></a> gives the names of commonly available mode bits. We can examine their values.</p> <pre><code>#! /usr/bin/env perl use strict; use warnings; use Fcntl ':mode'; my $perldoc_f_stat = q( # Permissions: read, write, execute, for user, group, others. S_IRWXU S_IRUSR S_IWUSR S_IXUSR S_IRWXG S_IRGRP S_IWGRP S_IXGRP S_IRWXO S_IROTH S_IWOTH S_IXOTH # Setuid/Setgid/Stickiness/SaveText. # Note that the exact meaning of these is system dependent. S_ISUID S_ISGID S_ISVTX S_ISTXT # File types. Not necessarily all are available on your system. S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO S_IFSOCK S_IFWHT S_ENFMT ); my %mask; foreach my $sym ($perldoc_f_stat =~ /\b(S_I\w+)\b/g) { my $val = eval { no strict 'refs'; &amp;$sym() }; if (defined $val) { $mask{$sym} = $val; } else { printf "%-10s - undefined\n", $sym; } } my @descending = sort { $mask{$b} &lt;=&gt; $mask{$a} } keys %mask; printf "%-10s - %9o\n", $_, $mask{$_} for @descending; </code></pre> <p>On Red Hat Enterprise Linux and other operating systems in the System V family, the output of the above program will be</p> <pre>S_ISTXT - undefined S_IFWHT - undefined S_IFSOCK - 140000 S_IFLNK - 120000 S_IFREG - 100000 S_IFBLK - 60000 S_IFDIR - 40000 S_IFCHR - 20000 S_IFIFO - 10000 S_ISUID - 4000 S_ISGID - 2000 S_ISVTX - 1000 S_IRWXU - 700 S_IRUSR - 400 S_IWUSR - 200 S_IXUSR - 100 S_IRWXG - 70 S_IRGRP - 40 S_IWGRP - 20 S_IXGRP - 10 S_IRWXO - 7 S_IROTH - 4 S_IWOTH - 2 S_IXOTH - 1</pre> <h2>Bit twiddling</h2> <p>The numbers above are octal (base 8), so any given digit must be 0-7 and has place value 8<sup><em>n</em></sup>, where <em>n</em> is the zero-based number of places to the left of the radix point. To see how they map to bits, octal has the convenient property that each digit corresponds to three bits. Four, two, and 1 are all exact powers of two, so in binary, they are 100, 10, and 1 respectively. Seven (= 4 + 2 + 1) in binary is 111, so then 70<sub>8</sub> is 111000<sub>2</sub>. The latter example shows how converting back and forth is straightforward.</p> <p>With a bit field, you don’t care exactly <em>what</em> the value of a bit in that position is but <em>whether</em> it is zero or non-zero, so</p> <pre><code>if ($mode &amp; $mask) { </code></pre> <p>tests whether any bit in <code>$mode</code> corresponding to <code>$mask</code> is set. For a simple example, given the 4-bit integer 1011 and a mask 0100, their bitwise AND is</p> <pre><code> 1011 &amp; 0100 ------ 0000 </code></pre> <p>So the bit in that position is clear—as opposed to a mask of, say, 0010 or 1100.</p> <p>Clearing the most significant bit of 1011 looks like</p> <pre><code> 1011 1011 &amp; ~(1000) = &amp; 0111 ------ 0011 </code></pre> <p>Recall that <code>~</code> in Perl is bitwise complement.</p> <p>For completeness, set a bit with bitwise OR as in</p> <pre><code>$bits |= $mask; </code></pre> <h2>Octal and file permissions</h2> <p>An octal digit’s direct mapping to three bits is convenient for Unix permissions because they come in groups of three. For example, the permissions for the program that produced the output above are</p> <pre>-rwxr-xr-x 1 gbacon users 1096 Feb 24 20:34 modebits</pre> <p>That is, the owner may read, write, and execute; but everyone else may read and execute. In octal, this is 755—a compact shorthand. In terms of the table above, the set bits in the mode are</p> <ul> <li><code>S_IRUSR</code></li> <li><code>S_IWUSR</code></li> <li><code>S_IXUSR</code></li> <li><code>S_IRGRP</code></li> <li><code>S_IXGRP</code></li> <li><code>S_IROTH</code></li> <li><code>S_IXOTH</code></li> </ul> <p>We can decompose the mode from your question by adding a few lines to the program above.</p> <pre><code>my $mode = 33188; print "\nBits set in mode $mode:\n"; foreach my $sym (@descending) { if (($mode &amp; $mask{$sym}) == $mask{$sym}) { print " - $sym\n"; $mode &amp;= ~$mask{$sym}; } } printf "extra bits: %o\n", $mode if $mode; </code></pre> <p>The mode test has to be more careful because some of the masks are shorthand for multiple bits. Testing that we get the exact mask back avoids false positives when some of the bits are set but not all.</p> <p>The loop also clears the bits from all detected hits so at the end we can check that we have accounted for each bit. The output is</p> <pre>Bits set in mode 33188: - S_IFREG - S_IRUSR - S_IWUSR - S_IRGRP - S_IROTH</pre> <p>No extra warning, so we got everything.</p> <h2>That magic 07777</h2> <p>Converting 7777<sub>8</sub> to binary gives <code>0b111_111_111_111</code>. Recall that 7<sub>8</sub> is 111<sub>2</sub>, and four 7s correspond to 4×3 ones. This mask is useful for selecting the set bits in the last twelve. Looking back at the bit masks we generated earlier</p> <pre>S_ISUID - 4000 S_ISGID - 2000 S_ISVTX - 1000 S_IRWXU - 700 S_IRWXG - 70 S_IRWXO - 7</pre> <p>we see that the last 9 bits are the permissions for user, group, and other. The three bits preceding those are the setuid, setgroupid, and what is sometimes called the sticky bit. For example, the full mode of <code>sendmail</code> on my system is <code>-rwxr-sr-x</code> or 34285<sub>10</sub>. The bitwise AND works out to be</p> <pre><code> (dec) (oct) (bin) 34285 102755 1000010111101101 &amp; 4095 = &amp; 7777 = &amp; 111111111111 ------- -------- ------------------ 1517 = 2755 = 10111101101 </code></pre> <p>The high bit in the mode that gets discarded is <code>S_IFREG</code>, the indicator that it is a regular file. Notice how much clearer the mode expressed in octal is when compared with the same information in decimal or binary.</p> <p>The <a href="http://perldoc.perl.org/functions/stat.html"><code>stat</code> documentation</a> mentions a helpful function.</p> <blockquote> <p>&hellip; and the <code>S_IF*</code> functions are</p> <p><strong><code>S_IMODE($mode)</code></strong><br> the part of <code>$mode</code> containing the permission bits and the setuid/setgid/sticky bits</p> </blockquote> <p><a href="https://github.com/mirrors/perl/blob/v5.17.8/ext/Fcntl/Fcntl.xs#L66">In <code>ext/Fcntl/Fcntl.xs</code></a>, we find its implementation and a familiar constant on the last line.</p> <pre><code>void S_IMODE(...) PREINIT: dXSTARG; SV *mode; PPCODE: if (items &gt; 0) mode = ST(0); else { mode = &amp;PL_sv_undef; EXTEND(SP, 1); } PUSHu(SvUV(mode) &amp; 07777); </code></pre> <p>To avoid the bad practice of <a href="https://en.wikipedia.org/wiki/Magic_number_%28programming%29">magic numbers</a> in source code, write</p> <pre><code>my $permissions = S_IMODE $mode; </code></pre> <p>Using <code>S_IMODE</code> and other functions available from the Fcntl module also hides the low-level bit twiddling and focuses on the domain-level information the program wants. The documentation continues</p> <blockquote> <p><strong><code>S_IFMT($mode)</code></strong><br> the part of <code>$mode</code> containing the file type which can be bit-anded with (for example) <code>S_IFREG</code> or with the following functions</p> <pre><code># The operators -f, -d, -l, -b, -c, -p, and -S. S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) # No direct -X operator counterpart, but for the first one # the -g operator is often equivalent. The ENFMT stands for # record flocking enforcement, a platform-dependent feature. S_ISENFMT($mode) S_ISWHT($mode) </code></pre> </blockquote> <p>Using these constants and functions will make your programs clearer by more directly expressing your intent.</p>
15,078,393
Begin ordered list from 0 in Markdown
<p>I'm new to <strong>Markdown</strong>. I was writing something like:</p> <pre><code># Table of Contents 0. Item 0 1. Item 1 2. Item 2 </code></pre> <p>But that generates a list that starts with 1, effectively rendering something like:</p> <pre><code># Table of Contents 1. Item 0 2. Item 1 3. Item 2 </code></pre> <p>I want to start the list from zero. Is there an easy way to do that?</p> <p>If not, I could simply rename all of my indices, but this is annoying when there are several items. Beginning a list from zero seems so natural to me, it's like beginning the index of an array from zero.</p>
15,078,486
4
0
null
2013-02-25 23:16:38.607 UTC
4
2022-01-27 06:29:54.167 UTC
2022-01-27 06:29:54.167 UTC
null
1,745,064
null
1,745,064
null
1
37
html-lists|markdown
8,416
<p>Simply: <strong>NO</strong></p> <p>Longer: <strong>YES, BUT</strong></p> <p>When you create ordered list in Markdown it is parsed to HTML ordered list, i.e.:</p> <pre><code># Table of Contents 0. Item 0 1. Item 1 2. Item 2 </code></pre> <p>Will create:</p> <pre><code>&lt;h1&gt;Table of Contents&lt;/h1&gt; &lt;ol&gt; &lt;li&gt;Item 0&lt;/li&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>So as you can see, there is no data about starting number. If you want to start at certain number, unfortunately, you have to use pure HTML and write:</p> <pre><code>&lt;ol start="0"&gt; &lt;li&gt;Item 0&lt;/li&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;/ol&gt; </code></pre>
15,292,318
MKMapView MKPointAnnotation tap event
<p>I have a list of annotations (MKPointAnnotation). I have a UIViewController which is for the whole view, MKMapView implementing Controller, which I thought is useful for detecting the users interaction with the map, my own MKPointAnnotation implementing (subclass) Controller which tells how to show the annotation.</p> <p>However I'm struck at the detection of the tap event by the user.</p> <p>Googling told me that I have to do something by implementing the following function.</p> <pre><code>- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control </code></pre> <p>and also that I have to implement this in some class which implements the MapViewDelegate (Protocol).</p> <p>But I'm all confused and unable to move forward. Can anyone tell me where to do what?</p> <p>Sorry for all the fuss!</p>
15,297,919
3
2
null
2013-03-08 10:54:10.607 UTC
21
2016-11-30 10:53:38.823 UTC
2013-03-08 11:02:40.08 UTC
null
790,997
null
2,139,438
null
1
46
ios|objective-c|mkmapview|mapkit|mkannotation
73,116
<p>There are two ways of detecting user interaction with your annotation view. The common technique is to define a callout (that standard little popover bubble that you see when you tap on a pin in a typical maps app) for your <code>MKAnnotationView</code>. And you create the annotation view for your annotation in the standard <code>viewForAnnotation</code> method:</p> <pre><code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id &lt;MKAnnotation&gt;)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"]; annotationView.canShowCallout = YES; annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return annotationView; } </code></pre> <p>By doing this, you get a callout, but you're adding an right accessory, which is, in my example above, a disclosure indicator. That way, they tap on your annotation view (in my example above, a pin on the map), they see the callout, and when they tap on that callout's right accessory (the little disclosure indicator in this example), your <code>calloutAccessoryControlTapped</code> is called (in my example below, performing a segue to some detail view controller):</p> <pre><code>- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control { [self performSegueWithIdentifier:@"DetailsIphone" sender:view]; } </code></pre> <p>That's a very typical user experience on the small iPhone screen. </p> <p>But, if you don't like that UX and you don't want the standard callout, but rather you want something else to happen, you can define your <code>MKAnnotationView</code> so that a callout is not shown, but instead you intercept it and do something else (for example, on iPad maps apps, you might show some more sophisticated popover rather than the standard callout). For example, you could have your <code>MKAnnotationView</code> not show a callout:</p> <pre><code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id &lt;MKAnnotation&gt;)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"]; annotationView.canShowCallout = NO; return annotationView; } </code></pre> <p>But you can then manually handle <code>didSelectAnnotationView</code> to detect when a user tapped on your <code>MKAnnotationView</code>, in this example showing a popover:</p> <pre><code>- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { [mapView deselectAnnotation:view.annotation animated:YES]; DetailsViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailsPopover"]; controller.annotation = view.annotation; self.popover = [[UIPopoverController alloc] initWithContentViewController:controller]; self.popover.delegate = self; [self.popover presentPopoverFromRect:view.frame inView:view.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; } </code></pre> <p>I include some screen snapshots for the user interface yielded by the above code in <a href="https://stackoverflow.com/a/14619356/1271826">my answer here</a>.</p>
15,466,162
View in ScrollView isn't matching parent as configured
<p>I've got a ViewPager and an ActionBar with tabs. One of these tabs has a ListView and when I tap on one of the options in that ListView, I add a child Fragment which is the detail view for that row. </p> <p>That detail view is a ScrollView with a LinearLayout inside it. The ScrollView is <code>match_parent/match_parent</code> and the LinearLayout inside it is <code>width=match_parent</code> and <code>height=wrap_content</code>. On a phone-sized emulator, the detail view fills the screen as desired, but on a tablet, the detail view only covers part of the width of the screen... even though the width of the ScrollView and the width of the LinearLayout are both match_parent.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rootView" style="@style/RootScrollView"&gt; &lt;LinearLayout android:id="@+id/scrollContentView" style="@style/ScrollViewContent"&gt; ... &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>Here is the style for the scroll view:</p> <pre><code>&lt;style name="RootScrollView"&gt; &lt;item name="android:layout_width"&gt;match_parent&lt;/item&gt; &lt;item name="android:layout_height"&gt;match_parent&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Here is the style for the content LinearLayout:</p> <pre><code>&lt;style name="ScrollViewContent"&gt; &lt;item name="android:layout_width"&gt;match_parent&lt;/item&gt; &lt;item name="android:layout_height"&gt;wrap_content&lt;/item&gt; &lt;item name="android:paddingLeft"&gt;15dp&lt;/item&gt; &lt;item name="android:paddingRight"&gt;15dp&lt;/item&gt; &lt;item name="android:orientation"&gt;vertical&lt;/item&gt; &lt;item name="android:background"&gt;@drawable/image_legal_paper_tile&lt;/item&gt; &lt;/style&gt; </code></pre> <p>The content view has a repeated background <code>image_legal_paper_tile</code> which is this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/legal_paper_tile" android:gravity="fill_horizontal" android:tileMode="repeat" /&gt; </code></pre> <p>So, the image should stretch horizontally and repeat which creates a yellow legal paper pad in the background.</p> <p>This is what the list and the detail view look like the phone emulator:</p> <p><img src="https://i.stack.imgur.com/CqMEh.png" alt="enter image description here"></p> <p>This is what the list and detail view look like on a real tablet. The yellow legal pad fragment SHOULD be filling the entire width of the screen, but it's not.</p> <p><img src="https://i.stack.imgur.com/Jk5Mx.jpg" alt="enter image description here"></p> <p>EDIT:</p> <p>Here is the background legal paper image:</p> <p><img src="https://i.stack.imgur.com/B5gyS.png" alt="enter image description here"></p> <p>It's 320px wide. The phone emulator is 480px wide and the image stretches, correctly, to fill the width of the screen. It then repeats vertically as intended. However, it's not stretching to fill the width of the screen on the tablet.</p> <p>The width shown on the tablet is NOT the native size of the image, because it changes size based on the content. When the fragment first loads, it is one width. Then I fill in the fields and execute the calculation which adds some text at the bottom of the content view. That text is wider than the existing content and so when the text is set the width of the fragment increases to support the wider content.</p> <p>So, in short, no, the width on the tablet is not the native size of the image. The image IS stretching, just not stretching all the way.</p>
19,428,718
5
3
null
2013-03-17 20:59:17.71 UTC
7
2020-12-30 09:57:15.083 UTC
2013-03-18 05:02:19.98 UTC
null
416,631
null
416,631
null
1
48
android|android-fragments
35,492
<p>On the ScrollView use <code>android:fillViewport="true"</code> and for child of ScrollView <code>android:height="wrap_content"</code>. If you would like to have many child's with different attributes make a main child as container. Set it as <code>wrap_content</code> and its child as <code>match_parent</code> . </p> <p>example :</p> <pre><code>&lt;ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"&gt; &lt;LinearLayout android:id="@+id/dynamic_frame" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" &gt; &lt;LinearLayout android:id="@+id/dimrix_sub_child" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:visibility="gone" &gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/dimrix_sub_child_21" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:visibility="gone" &gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>In this example I can set visibility in the code for each child and it will match parent as you wish . </p>
38,148,128
How do I reference a .NET Framework project in a .NET Core project?
<p>I'd really like to start using .NET Core and slowly migrate applications and libraries to it. However, I can't realistically upgrade my entire code base to use .NET Core and then go through the process of testing and deploying a plethora of applications in production.</p> <p>As an example, if I create a new .NET Core application and try to reference one of my .NET Framework projects I get the following:</p> <blockquote> <p>The following projects are not supported as references: - Foobar.NetFramework has target frameworks that are incompatible with targets in current project Foobar.NetCore.</p> <p>Foobar.NetCore: .NETCoreApp,Version=v1.0</p> <p>Foobar.NetFramework: .NETFramework,Version=v4.5</p> </blockquote> <p>Is it possible to create a new .NET Core application and reference my existing .NET Framework libraries? If so, what's the process for doing that? I've spent hours going through Microsoft's documentation and searching their issues on GitHub, but I can't find anything official on how to achieve this or what their long-term vision is for this process.</p>
38,148,468
4
3
null
2016-07-01 14:38:31.717 UTC
10
2022-03-18 22:17:38.203 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
190,750
null
1
69
c#|.net|asp.net-core|.net-core
38,336
<p>Yes, we are currently attempting the same thing. The trick is to make sure that you are supporting the same .NET frameworks. Inside your <strong>project.json</strong> file, make sure the framework matches the framework of the project you wish to include. For example:</p> <pre><code>"frameworks": { "net46": { --This line here &lt;&lt;&lt;&lt; "dependencies": { "DomainModel": { "target": "project" }, "Models": { "target": "project" } } } }, </code></pre> <p>FYI: You might need to change the framework of your .NET Core or your older projects to achieve this. .NET Core can be changed just by editing the project.json file as seen above. You can so the same in .NET projects by right clicking the project and opening properties. Change the framework level there.</p> <p>Once you have matched the two project frameworks then you should be able to include them. Good Luck!</p>
8,089,641
OpenCV findHomography Issue
<p>I am working on a Panography / Panorama application in OpenCV and I've run into a problem I really can't figure out. For an idea of what a panorama photograph looks like, have a look here at the Panography Wikipedia article: <a href="http://en.wikipedia.org/wiki/Panography" rel="noreferrer">http://en.wikipedia.org/wiki/Panography</a></p> <p>So far, I can take multiple images, and stitch them together while making any image I like a reference image; here's a little taster of what I mean.</p> <p><img src="https://i.stack.imgur.com/U4wqT.jpg" alt="An example Panography image I&#39;ve created"></p> <p>However, as you can see - it has a lot of issues. The primary one I am facing is that the images are getting cut (re: far right image, top of images). To highlight why this is happening, I'll draw the points that have been matched, and draw lines for where the transformation will end up:</p> <p><img src="https://i.stack.imgur.com/gAkbp.jpg" alt="The image matches"></p> <p>Where the left image is the reference image, and the right image is the image after it's been translated (original below) - I have drawn the green lines to highlight the image. The image has the following corner points: </p> <pre><code>TL: [234.759, -117.696] TR: [852.226, -38.9487] BR: [764.368, 374.84] BL: [176.381, 259.953] </code></pre> <p>So the main problem I have is that after the perspective has been changed the image: </p> <p><img src="https://i.stack.imgur.com/HO6xK.png" alt="Original Image"></p> <p>Suffers losses like so: </p> <p><img src="https://i.stack.imgur.com/Xn1oV.png" alt="Cut up image"></p> <p>Now enough images, some code.</p> <p>I'm using a <code>cv::SurfFeatureDetector</code>, <code>cv::SurfDescriptorExtractor</code> and <code>cv::FlannBasedMatcher</code> to get all of those points, and I calculate the matches and more importantly good matches by doing the following: </p> <pre><code>/* calculate the matches */ for(int i = 0; i &lt; descriptors_thisImage.rows; i++) { double dist = matches[i].distance; if(dist &lt; min_dist) min_dist = dist; if(dist &gt; max_dist) max_dist = dist; } /* calculate the good matches */ for(int i = 0; i &lt; descriptors_thisImage.rows; i++) { if(matches[i].distance &lt; 3*min_dist) { good_matches.push_back(matches[i]); } } </code></pre> <p>This is pretty standard, and to do this I followed the tutorial found here: <a href="http://opencv.itseez.com/trunk/doc/tutorials/features2d/feature_homography/feature_homography.html" rel="noreferrer">http://opencv.itseez.com/trunk/doc/tutorials/features2d/feature_homography/feature_homography.html</a></p> <p>To copy images atop of one another, I use the following method (where <code>img1</code> and <code>img2</code> are <code>std::vector&lt; cv::Point2f &gt;</code>)</p> <pre><code>/* set the keypoints from the good matches */ for( int i = 0; i &lt; good_matches.size(); i++ ) { img1.push_back( keypoints_thisImage[ good_matches[i].queryIdx ].pt ); img2.push_back( keypoints_referenceImage[ good_matches[i].trainIdx ].pt ); } /* calculate the homography */ cv::Mat H = cv::findHomography(cv::Mat(img1), cv::Mat(img2), CV_RANSAC); /* warp the image */ cv::warpPerspective(thisImage, thisTransformed, H, cv::Size(thisImage.cols * 2, thisImage.rows * 2), cv::INTER_CUBIC ); /* place the contents of thisImage in gsThisImage */ thisImage.copyTo(gsThisImage); /* set the values of gsThisImage to 255 */ for(int i = 0; i &lt; gsThisImage.rows; i++) { cv::Vec3b *p = gsThisImage.ptr&lt;cv::Vec3b&gt;(i); for(int j = 0; j &lt; gsThisImage.cols; j++) { for( int grb=0; grb &lt; 3; grb++ ) { p[j][grb] = cv::saturate_cast&lt;uchar&gt;( 255.0f ); } } } /* convert the colour to greyscale */ cv::cvtColor(gsThisImage, gsThisImage, CV_BGR2GRAY); /* warp the greyscale image to create an image mask */ cv::warpPerspective(gsThisImage, thisMask, H, cv::Size(thisImage.cols * 2, thisImage.rows * 2), cv::INTER_CUBIC ); /* stitch the transformed image to the reference image */ thisTransformed.copyTo(referenceImage, thisMask); </code></pre> <p>So, I have the coordinates of where the warped image is going to end up, I have the points that create the homogeneous matrix that's used for these transformations - but I can't figure out how I should go about translating these images so they can't get cut up. Any help or pointers are very appreciated! </p>
8,090,483
2
0
null
2011-11-11 04:22:19.963 UTC
9
2011-11-11 06:55:37.867 UTC
null
null
null
null
657,990
null
1
8
c++|opencv
16,381
<p>First, why didn't you use the newly added stitching module? It does exactly the thing you're trying to do. </p> <p>Second, if you want to continue with your code, to correct it it's easy. In the homography matrix, the translations represent the values on the last column.</p> <pre><code>a11 a12 a13 t1 a21 a22 a23 t2 a31 a32 a33 t3 a41 a42 a43 1 </code></pre> <p>(If you have a 3x3 matrix, you will miss the a13..a43 column and the a41..1 row. a33 will (should) become 1).</p> <p>So, what you have to do is to figure out what you should put in the last column so that yout images are aligned. </p> <p>Check also this post that explaines (somehow the opposite problem) how to build a homography, when you know the camera parameters. It will help you understand the role of the matrix values.</p> <p><a href="https://stackoverflow.com/questions/6606891/opencv-virtually-camera-rotating-translating-for-birds-eye-view">Opencv virtually camera rotating/translating for bird&#39;s eye view</a></p> <p>And <strong>note</strong> that everything I told you about last column is only approximate, because the values in the last column are actually translation plus some (minor) factors. </p>
7,858,114
How can I run a cron job with arguments and pass results to a log?
<p>Example:</p> <pre><code>* * * * * /usr/bin/php /full/path/to/script.php arg1 arg2 &gt; /full/path/to/logfile.log </code></pre> <p>The script runs and accesses the arguments just fine, but the results are never printed to the logfile.log. Also, my logfile.log is chmod 777, so I know it has write access.</p> <p>Can you fix my syntax?</p>
7,858,134
2
3
null
2011-10-22 07:45:28.957 UTC
2
2016-07-01 21:58:18.727 UTC
2011-10-22 07:52:05.55 UTC
null
834,525
null
834,525
null
1
10
linux|unix|cron|crontab
50,368
<p>It looks like you are searching for the log file in the wrong folder. Try this </p> <pre><code>* * * * * cd /path/to/script.php ; ./script.php arg1 arg2 &gt;&gt; logfile.log </code></pre> <p>Then look for your log file in the /path/to/script folder. It can also be a write permission problem. Also, check your script for errors. Your crontab command seems OK.</p>
8,332,475
How to get Android Thread ID?
<p>This code throws a "Given thread does not exist" exception when I try to use it in a thread:</p> <pre><code>android.os.Process.getThreadPriority((int) Thread.currentThread().getId())); </code></pre> <p>Ditto if I try to use Process.setThreadPriority, using the java class Thread id. I've also noticed that this does not match the thread id displayed in the debugger. How do I get the Android specific thread id, in order to use this API?</p>
8,333,167
2
1
null
2011-11-30 20:23:01.693 UTC
8
2015-05-15 09:00:53.49 UTC
null
null
null
null
7,099
null
1
50
android
44,283
<pre><code>android.os.Process.getThreadPriority(android.os.Process.myTid()); </code></pre> <p>For further reference </p> <p><a href="http://developer.android.com/reference/android/os/Process.html#myTid()" rel="noreferrer">http://developer.android.com/reference/android/os/Process.html#myTid()</a></p>
8,595,964
Redirect all traffic to index.php using mod_rewrite
<p>I'm trying to build a url shortener, and I want to be able to take any characters immediately after the domain and have them passed as a variable url. So for example </p> <ul> <li><a href="http://google.com/asdf" rel="nofollow noreferrer">http://google.com/asdf</a> </li> </ul> <p>would become </p> <ul> <li><a href="http://www.google.com/?url=asdf" rel="nofollow noreferrer">http://www.google.com/?url=asdf</a>.</li> </ul> <p>Here's what I have for mod_rewrite right now, but I keep getting a 400 Bad Request:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) index.php?url=$1 [L,QSA] </code></pre>
8,596,029
6
4
null
2011-12-21 20:30:24.217 UTC
3
2021-06-08 15:14:20.877 UTC
2016-06-29 07:45:23.513 UTC
null
3,160,747
null
326,111
null
1
10
php|mod-rewrite|apache
42,950
<p>Try replacing <code>^(.*)</code> with <code>^(.*)$</code></p> <pre><code>RewriteRule ^(.*)$ index.php?url=$1 [L,QSA] </code></pre> <p>Edit: Try replacing <code>index.php</code> with <code>/index.php</code></p> <pre><code>RewriteRule ^(.*)$ /index.php?url=$1 [L,QSA] </code></pre>
5,522,031
Convert timedelta to total seconds
<p>I have a time difference</p> <pre class="lang-py prettyprint-override"><code>import time import datetime time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) ... time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) diff = time2 - time1 </code></pre> <p>Now, how do I find the total number of seconds that passed? <code>diff.seconds</code> doesn't count days. I could do:</p> <pre class="lang-py prettyprint-override"><code>diff.seconds + diff.days * 24 * 3600 </code></pre> <p>Is there a builtin method for this?</p>
5,522,070
4
3
null
2011-04-02 08:11:24.6 UTC
17
2021-01-19 13:44:26.24 UTC
2020-07-29 12:54:48.32 UTC
null
7,964,098
null
11,236
null
1
290
python|datetime
287,899
<p>Use <a href="http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds" rel="noreferrer"><code>timedelta.total_seconds()</code></a>.</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.timedelta(seconds=24*60*60).total_seconds() 86400.0 </code></pre>
4,913,922
Possible problems with NOMINMAX on Visual C++
<p>What problems could I get when defining <code>NOMINMAX</code> before anything else in my program?</p> <p>As far as I know, this will make <code>&lt;Windows.h&gt;</code> not define the <code>min</code> and <code>max</code> macros such that many conflicts with the STL, e.g. <code>std::min()</code>, <code>std::max()</code>, or <code>std::numeric_limits&lt;T&gt;::min()</code> are resolved.</p> <p>Am I right in the assumption that only Windows-specific and legacy code will have problems? Almost all libraries should not depend on <code>min()</code> and <code>max()</code> defined as macros?</p> <p><strong>Edit:</strong> Will there be be problems with other Windows headers?</p>
4,914,108
4
4
null
2011-02-06 14:38:37.473 UTC
10
2018-10-25 04:51:32.947 UTC
2011-02-06 14:50:29.593 UTC
null
84,349
null
84,349
null
1
37
c++|windows|visual-c++
31,284
<p>Using <code>NOMINMAX</code> is the only not-completely-evil way to include <code>&lt;windows.h&gt;</code>. You should also define <code>UNICODE</code> and <code>STRICT</code>. Although the latter is defined by default by modern implementations.</p> <p>You can however run into problems with Microsoft&rsquo;s headers, e.g. for GdiPlus. I&rsquo;m not aware of problems with headers from any other companies or persons.</p> <p>If the header defines a namespace, as GdiPlus does, then one fix is to create a wrapper for the relevant header, where you include <code>&lt;algorithm&gt;</code>, and inside the header&rsquo;s namespace, <code>using namespace std;</code> (or alternatively <code>using std::min;</code> and <code>using std::max</code>):</p> <pre><code>#define NOMINMAX #include &lt;algorithm&gt; namespace Gdiplus { using std::min; using std::max; } </code></pre> <p>Note that that is very different from a <code>using namespace std;</code> at global scope in header, which one should <em>never do</em>.</p> <p>I don&rsquo;t know of any good workaround for the case where there's no namespace, but happily I haven&rsquo;t run into that, so in practice that particular problem is probably moot.</p>
5,310,216
Passing PHP variable into JavaScript
<p>I've a PHP session variable, <code>$_SESSION['user']</code>, alive throughout the session. In the head section, I've my JavaScript file included, <code>scripts.js</code>. </p> <p>How do I pass the session variable into the JavaScript file if I want something like the following.</p> <pre><code>$.("#btn').click ( function() { alert('&lt;?php echo $_SESSION['user']; ?&gt;'); } ) </code></pre> <p>As the <code>&lt;?php ?&gt;</code> isn't recognized in the JavaScript file, the code above doesn't work. So I've to put in the PHP file itself, but how do I keep it in the JavaScript file?</p>
5,310,269
5
0
null
2011-03-15 10:11:40.353 UTC
9
2014-05-19 15:26:12.917 UTC
2011-04-11 11:32:02.327 UTC
null
63,550
null
383,393
null
1
8
php|javascript
23,689
<p>In your PHP file you could set your user as a global varibale:</p> <pre><code>&lt;script type="text/javascript"&gt; var ptamzzNamespace = { sessionUser : '&lt;?php echo $_SESSION['user']; ?&gt;' } &lt;/script&gt; </code></pre> <p>Include this before including your external JavaScript code.</p> <p>Then in your JavaScript file you can use it:</p> <pre><code>$.("#btn').click ( function() { alert(ptamzzNamespace.sessionUser); } ) </code></pre> <p><strong>Additionally:</strong> If you're not sure if your session varibale can contain quotes itsself, you can use <code>addslashes()</code> to fix this problem:</p> <p><code>&lt;?php echo addslashes($_SESSION['user']); ?&gt;</code> even if this will maybe produce something you don't really want to display (because it produces a string with slashes) it will help that your code will not fail. (Thanks to Artefacto)</p> <p>Would this be an option for you?</p>
5,301,666
What is the rationale for not having static constructor in C++?
<p>What is the rationale for not having static constructor in C++?</p> <p>If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:</p> <pre><code>//illegal C++ class sample { public: static int some_integer; static std::vector&lt;std::string&gt; strings; //illegal constructor! static sample() { some_integer = 100; strings.push_back("stack"); strings.push_back("overflow"); } }; </code></pre> <p>In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.</p> <p>So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!</p>
5,301,789
5
11
null
2011-03-14 16:49:28.837 UTC
10
2013-01-28 13:58:11.33 UTC
null
null
null
null
415,784
null
1
31
c++|constructor|language-design|language-features|static-constructor
8,221
<p>Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.</p> <p>Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:</p> <pre><code>//called before main() int static_main() { ClassFoo(); ClassBar(); } </code></pre> <p>with appropriate declarations:</p> <pre><code>class ClassFoo { static int y; ClassFoo() { y = 1; } } class ClassBar { static int x; ClassBar() { x = ClassFoo::y+1; } } </code></pre> <p>So the answer is, there is no reason it isn't there, at least not a technical one.</p>
5,548,142
How to position div at the bottom of a page
<p>How can I set position of a <code>&lt;div&gt;</code> to the bottom of page with either CSS or jQuery?</p>
5,548,182
6
0
null
2011-04-05 06:39:47.45 UTC
1
2016-11-30 01:38:06.467 UTC
2011-04-05 11:51:38.75 UTC
null
637,889
null
369,161
null
1
11
jquery|html|css|position
47,061
<p>Use <code>position:absolute</code> and <code>bottom:0</code> </p> <h2>Check working example. <a href="http://jsfiddle.net/gyExR/" rel="noreferrer">http://jsfiddle.net/gyExR/</a></h2>
5,137,006
Reverse NSMutableArray
<p>What is the best/correct way to reverse an NSMutableArray?</p>
5,137,032
7
0
null
2011-02-28 00:05:58.26 UTC
9
2022-02-04 19:20:56.927 UTC
2017-03-28 01:08:59.233 UTC
null
1,402,846
null
356,387
null
1
41
ios|macos|nsmutablearray
24,289
<pre><code>themutablearray=[[[themutablearray reverseObjectEnumerator] allObjects] mutableCopy]; </code></pre>
5,057,793
How to capitalize names
<p>Basically if I want to transform a name from</p> <pre><code>stephen smith </code></pre> <p>to</p> <pre><code>Stephen Smith </code></pre> <p>I can easily do it with come CSS on the page, but ideally I would like to catch it earlier on and change it when it comes out of the database. How can I get C# to capitalise a string?</p> <p>Is there a function for this?</p>
5,057,800
8
1
null
2011-02-20 15:01:31.84 UTC
5
2021-07-12 19:28:50.567 UTC
2021-07-12 19:18:33.837 UTC
null
63,550
null
369,765
null
1
58
c#|.net
58,229
<p>You can do this using the <code>ToTitleCase</code> method of the <a href="http://support.microsoft.com/kb/312890" rel="noreferrer">System.Globalization.TextInfo</a> class:</p> <pre><code>CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; Console.WriteLine(textInfo.ToTitleCase(title)); Console.WriteLine(textInfo.ToLower(title)); Console.WriteLine(textInfo.ToUpper(title)); </code></pre>
5,513,615
Add 'decimal-mark' thousands separators to a number
<p>How do I format <code>1000000</code> to <code>1.000.000</code> in Python? where the '.' is the decimal-mark thousands separator.</p>
5,513,747
9
6
null
2011-04-01 12:50:40.6 UTC
9
2022-01-12 07:38:44.527 UTC
2016-10-20 12:51:54.67 UTC
null
202,229
null
687,580
null
1
62
python|format|locale|number-formatting|digit-separator
62,878
<p>If you want to add a thousands separator, you can write:</p> <pre><code>&gt;&gt;&gt; '{0:,}'.format(1000000) '1,000,000' </code></pre> <p>But it only works in Python 2.7 and above.</p> <p>See <a href="http://docs.python.org/library/string.html#format-string-syntax" rel="noreferrer">format string syntax</a>.</p> <p>In older versions, you can use <a href="http://docs.python.org/library/locale.html#locale.format" rel="noreferrer">locale.format()</a>:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, '') 'en_AU.utf8' &gt;&gt;&gt; locale.format('%d', 1000000, 1) '1,000,000' </code></pre> <p>the added benefit of using <code>locale.format()</code> is that it will use your locale's thousands separator, e.g.</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, 'de_DE.utf-8') 'de_DE.utf-8' &gt;&gt;&gt; locale.format('%d', 1000000, 1) '1.000.000' </code></pre>
4,937,517
IP to Location using Javascript
<pre><code>&lt;script type="application/javascript"&gt; function getip(json){ alert(json.ip); // alerts the ip address } &lt;/script&gt; &lt;script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"&gt;&lt;/script&gt; </code></pre> <p>I can get User IP by this code...</p> <p>I want to find location of this IP. How can I?</p>
4,937,578
14
2
null
2011-02-08 19:40:45.823 UTC
21
2022-03-30 12:42:31.713 UTC
null
null
null
null
389,200
null
1
53
javascript|jquery|ip
137,910
<p>You can submit the IP you receive to an online geolocation service, such as <code>http://www.geoplugin.net/json.gp?ip=&lt;your ip here&gt;&amp;jsoncallback=&lt;suitable javascript function in your source&gt;</code>, then including the source it returns which will run the function you specify in <code>jsoncallback</code> with the geolocation information.</p> <p>Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action <a href="http://html5demos.com/geo" rel="noreferrer">here</a>. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.</p>
4,967,496
Check if a Windows service exists and delete in PowerShell
<p>I am currently writing a deployment script that installs a number of Windows services.</p> <p>The services names are versioned, so I want to delete the prior Windows service version as part of the installs of the new service.</p> <p>How can I best do this in PowerShell?</p>
4,967,750
15
0
null
2011-02-11 09:39:14.337 UTC
31
2022-02-14 19:13:20.16 UTC
2013-11-13 19:12:36.99 UTC
null
23,199
null
395,440
null
1
172
powershell|windows-services
247,016
<p>You can use WMI or other tools for this since there is no <code>Remove-Service</code> cmdlet until Powershell 6.0 (<a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-service?view=powershell-6&amp;viewFallbackFrom=powershell-5" rel="noreferrer" title="Remove-Service module documentation for PowerShell 6.0">See Remove-Service doc)</a></p> <p>For example:</p> <pre><code>$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'" $service.delete() </code></pre> <p>Or with the <code>sc.exe</code> tool:</p> <pre><code>sc.exe delete ServiceName </code></pre> <p>Finally, if you do have access to PowerShell 6.0:</p> <pre><code>Remove-Service -Name ServiceName </code></pre>
29,392,763
Cardview - white border around card
<p>I am using a cardview as the root of a custom view I am writing. I using the v7 support library. My XML looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="6dp" card_view:cardElevation="0dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;!-- some other views --&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p>My problem is that I am getting a white border around my card view. It looks like it is there to indicate elevation as it is thicker on the right side. I've tried adjusting <code>cardElevation</code> and <code>MaxCardElevation</code> in my XML like so : <code>card_view:cardElevation="0dp"</code></p> <p>and in code in my custom view that extends CardView and uses this layout:</p> <pre><code>setCardElevation(0); setMaxCardElevation(0); </code></pre> <p>But the white border persists. I'm not sure how to get rid of it. If anyone had any input into why this is happening or suggestions on how I can remove the white border it would be appreciated. Thanks much. </p>
30,242,617
4
6
null
2015-04-01 13:58:04.577 UTC
12
2017-12-28 15:44:28.767 UTC
null
null
null
null
1,001,495
null
1
34
android|android-cardview
39,477
<p>I know it's a bit late, but for anyone having a similar problem:</p> <p>I had the same issue: A white border was shown on pre-lollipop devices.</p> <p>I solved it setting the <a href="https://developer.android.com/reference/android/support/v7/widget/CardView.html#attr_android.support.v7.cardview:cardPreventCornerOverlap">cardPreventCornerOverlap</a> to <code>false</code> on your XML.</p> <p>Like this:</p> <pre><code>&lt;android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="6dp" card_view:cardPreventCornerOverlap="false"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;!-- some other views --&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p>Hope this helps!</p>
29,571,304
How can I @Autowire a spring bean that was created from an external jar?
<p>I have a module/jar that I've created and am using as a util <em><strong>library</strong></em>. I created a service in there like so:</p> <pre><code>@Service public class PermissionsService { ... } </code></pre> <p>... where this resides in a package here: <strong>com.inin.architect.permissions</strong> and in my main application, I'm referencing/loading this jar (i.e. set as a dependency in the maven POM.xml file for the app) like so:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.inin.architect&lt;/groupId&gt; &lt;artifactId&gt;permissions&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>and within the application I want to use that service like:</p> <pre><code>@Autowired PermissionsService permissions </code></pre> <p>In the application's spring setup, I've got this:</p> <pre><code>@Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.inin.generator", "com.inin.architect.permissions" }) public class WebConfig extends WebMvcConfigurerAdapter implements ServletContextAware { } </code></pre> <p>However when I run my application under tomcat, it complains that there isn't a bean for the <strong>PermissionsService</strong>: "org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ..."</p> <p>So, how can I bring over the bean from the lib into my application? Surely there's a way. Do you have to set the library up as a full blown spring MVC application so that this can work? i.e. do you have to have @Configuration and @ComponentScan setup in the lib as well?</p>
29,571,429
5
13
null
2015-04-10 21:57:54.6 UTC
14
2021-06-06 09:37:25.563 UTC
2015-04-11 14:42:23.377 UTC
null
385,981
null
385,981
null
1
67
java|spring|maven|spring-mvc
88,606
<p>You have to scan at least the package containing the class you want to inject. For example, with Spring 4 annotation:</p> <pre><code>@Configuration @ComponentScan("com.package.where.my.class.is") class Config { ... } </code></pre> <p>It is the same principle for XML configuration.</p>
12,266,502
Android MediaPlayer Stop and Play
<p>I'm creating Android application contains 2 buttons, on click on each button play a mp3 file. The problem is when I play <code>button1</code> it plays <code>sound1</code>, when I click <code>button2</code> it plays <code>sound2</code>.</p> <p>I check on each button the other player if it's working and I stop it and play the clicked one</p> <p>But If I click on same button twice it's keep first audio playing in the background and play another one again </p> <p>I tried to check <code>isPlaying()</code> and to stop it, but it doesn't work!</p> <p>I want If I click on <code>button1</code> it play <code>sound1</code> and if clicked on it again it stop it and play it again from beginning.</p> <p>My code:</p> <pre><code>package com.hamoosh.playaudio; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; public class PlayaudioActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b= (Button) findViewById(R.id.button1); Button b2= (Button) findViewById(R.id.button2); final TextView t= (TextView) findViewById(R.id.textView1); final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far); final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mp1.isPlaying()) { mp1.stop(); } mp.start(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mp.isPlaying()) { mp.stop(); } mp1.start(); } }); } } </code></pre> <p>Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.</p>
12,266,668
5
0
null
2012-09-04 15:15:19.173 UTC
13
2021-07-19 17:06:13.573 UTC
2012-10-03 23:51:39.34 UTC
null
260,411
null
1,646,584
null
1
32
android|media-player
114,509
<p>You should use only one mediaplayer object</p> <pre><code> public class PlayaudioActivity extends Activity { private MediaPlayer mp; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button) findViewById(R.id.button1); Button b2 = (Button) findViewById(R.id.button2); final TextView t = (TextView) findViewById(R.id.textView1); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopPlaying(); mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far); mp.start(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopPlaying(); mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet); mp.start(); } }); } private void stopPlaying() { if (mp != null) { mp.stop(); mp.release(); mp = null; } } } </code></pre>
12,428,755
1064 error in CREATE TABLE ... TYPE=MYISAM
<p>Here is my error(if you need any more info just ask)- Error SQL query:</p> <pre><code>CREATE TABLE dave_bannedwords( id INT( 11 ) NOT NULL AUTO_INCREMENT , word VARCHAR( 60 ) NOT NULL DEFAULT '', PRIMARY KEY ( id ) , KEY id( id ) ) TYPE = MYISAM ; </code></pre> <p>MySQL said: </p> <blockquote> <p>1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=MyISAM' at line 6</p> </blockquote>
12,428,808
5
1
null
2012-09-14 16:46:52.977 UTC
8
2018-12-10 16:27:30.123 UTC
2012-09-14 18:04:35.477 UTC
null
205,608
null
1,671,978
null
1
32
mysql|syntax
110,263
<p>As documented under <a href="http://dev.mysql.com/doc/en/create-table.html"><code>CREATE TABLE</code> Syntax</a>:</p> <blockquote> <p><strong>Note</strong><br/> The older <code>TYPE</code> option was synonymous with <code>ENGINE</code>. <code>TYPE</code> was deprecated in MySQL 4.0 and removed in MySQL 5.5. <em>When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on <code>TYPE</code> to use <code>ENGINE</code> instead.</em></p> </blockquote> <p>Therefore, you want:</p> <pre><code>CREATE TABLE dave_bannedwords( id INT(11) NOT NULL AUTO_INCREMENT, word VARCHAR(60) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary ) ENGINE = MyISAM ; </code></pre>
12,533,661
Chrome says my extension's manifest file is missing or unreadable
<p>I'm a new chrome extension developer, and I was going through the Chrome tutorial on making a "Hello World" extension, here's my code:</p> <pre><code> { "name": "My First Extension", "version": "1.0", "manifest_version": 2, "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png" }, "permissions": [ "http://api.flickr.com/" ] } </code></pre> <p>When I went to load the unpacked extension it said the manifest file was missing or unreadable. Yes I have the image in a folder with it and it is correctly named manifest.json</p>
12,533,743
9
3
null
2012-09-21 15:34:07.393 UTC
6
2021-05-25 10:48:57.23 UTC
2015-09-20 18:57:23.117 UTC
null
445,131
null
1,689,242
null
1
40
google-chrome-extension
191,962
<p>Something that commonly happens is that the manifest file isn't named properly. Double check the name (and extension) and be sure that it doesn't end with <em>.txt</em> (for example).</p> <p>In order to determine this, make sure you aren't hiding file extensions:</p> <ol> <li>Open Windows Explorer</li> <li>Go to Folder and Search Options > View tab</li> <li>Uncheck <em>Hide extensions for known file types</em></li> </ol> <p>Also, note that the naming of the manifest file is, in fact, case sensitive, i.e. <em>manifest.json</em> != <em>MANIFEST.JSON</em>.</p>
12,203,521
Selecting max record for each user
<p>This seems if it should be fairly simple, but I'm stumbling in trying to find a solution that works for me. </p> <p>I have a member_contracts table that has the following (simplified) structure.</p> <pre><code>MemberID | ContractID | StartDate | End Date | ------------------------------------------------ 1 1 2/1/2002 2/1/2003 2 2 3/1/2002 3/1/2003 3 3 4/1/2002 4/1/2003 1 4 2/1/2002 2/1/2004 2 5 3/1/2003 2/1/2004 3 6 4/1/2003 2/1/2004 </code></pre> <p>I'm trying to create a query that will select the most recent contracts from this table. That being the following output for this small example:</p> <pre><code>MemberID | ContractID | StartDate | End Date | ------------------------------------------------ 1 4 2/1/2002 2/1/2004 2 5 3/1/2003 2/1/2004 3 6 4/1/2003 2/1/2004 </code></pre> <p>Doing this on a per-user basis is extremely simple since I can just use a subquery to select the max contractID for the specified user. I am using SQL server, so if there's a special way of doing it with that flavor, I'm open to using it. Personally, I'd like something that was engine agnostic. </p> <p>But, how would I go about writing a query that would accomplish the goal for all the users?</p> <p>EDIT: I should also add that I'm looking for the max contractID value for each user, not the most recent dates. </p>
12,203,599
2
3
null
2012-08-30 18:48:24.533 UTC
7
2019-04-02 15:03:24.12 UTC
2014-09-18 04:20:30.65 UTC
null
113,632
null
842,223
null
1
41
sql|sql-server|subquery
61,418
<p>This solution uses the uniqueness of the ContractId field:</p> <pre><code>SELECT MemberID, ContractID, StartDate, EndDate FROM member_contracts WHERE ContractId IN ( SELECT MAX(ContractId) FROM member_contracts GROUP BY MemberId ) </code></pre> <p>See it working online: <a href="http://sqlfiddle.com/#!3/599b2/1">sqlfiddle</a></p>
12,152,890
XPath contains one of multiple values
<p>I have simple xpath</p> <pre><code> /products/product[contains(categorie,'Kinderwagens')] </code></pre> <p>It works but now how do I filter on multiple categorie values</p> <p>like</p> <pre><code>/products/product[contains(categorie,'Kinderwagens')] + /products/product[contains(categorie,'Kinderwagens')] </code></pre>
12,153,123
4
0
null
2012-08-28 04:43:27.71 UTC
9
2021-07-14 16:14:29.303 UTC
2017-09-30 13:47:41.18 UTC
null
712,334
null
1,545,866
null
1
52
xpath|filter
88,537
<p>Will this work?</p> <pre><code>/products/product[contains(categorie,'Kinderwagens') or contains(categorie,'Wonderwagens')] </code></pre> <p>There is a similar question <a href="https://stackoverflow.com/questions/472966/xpath-multiple-element-filters">here</a></p>
12,168,624
Pagination response payload from a RESTful API
<p>I want to support pagination in my RESTful API.</p> <p>My API method should return a JSON list of product via <code>/products/index</code>. However, there are potentially thousands of products, and I want to page through them, so my request should look something like this:</p> <pre><code>/products/index?page_number=5&amp;page_size=20 </code></pre> <p>But what does my JSON response need to look like? Would API consumers typically expect pagination meta data in the response? Or is only an array of products necessary? Why?</p> <p>It looks like Twitter's API includes meta data: <a href="https://dev.twitter.com/docs/api/1/get/lists/members" rel="noreferrer">https://dev.twitter.com/docs/api/1/get/lists/members</a> (see Example Request).</p> <p>With meta data:</p> <pre><code>{ "page_number": 5, "page_size": 20, "total_record_count": 521, "records": [ { "id": 1, "name": "Widget #1" }, { "id": 2, "name": "Widget #2" }, { "id": 3, "name": "Widget #3" } ] } </code></pre> <p>Just an array of products (no meta data):</p> <pre><code>[ { "id": 1, "name": "Widget #1" }, { "id": 2, "name": "Widget #2" }, { "id": 3, "name": "Widget #3" } ] </code></pre>
12,171,176
6
0
null
2012-08-28 22:47:57.1 UTC
67
2022-04-29 07:52:10.79 UTC
2012-08-28 22:53:08.583 UTC
null
83,897
null
83,897
null
1
100
rest|pagination
149,575
<p>ReSTful APIs are consumed primarily by other systems, which is why I put paging data in the response headers. However, some API consumers may not have direct access to the response headers, or may be building a UX over your API, so providing a way to retrieve (on demand) the metadata in the JSON response is a plus. </p> <p>I believe your implementation should include machine-readable metadata as a default, and human-readable metadata when requested. The human-readable metadata could be returned with every request if you like or, preferably, on-demand via a query parameter, such as <code>include=metadata</code> or <code>include_metadata=true</code>. </p> <p>In your particular scenario, I would include the URI for each product with the record. This makes it easy for the API consumer to create links to the individual products. I would also set some reasonable expectations as per the limits of my paging requests. Implementing and documenting default settings for page size is an acceptable practice. For example, <a href="http://developer.github.com/v3/#pagination" rel="noreferrer">GitHub's API</a> sets the default page size to 30 records with a maximum of 100, plus sets a rate limit on the number of times you can query the API. If your API has a default page size, then the query string can just specify the page index.</p> <p>In the human-readable scenario, when navigating to <code>/products?page=5&amp;per_page=20&amp;include=metadata</code>, the response could be:</p> <pre><code>{ "_metadata": { "page": 5, "per_page": 20, "page_count": 20, "total_count": 521, "Links": [ {"self": "/products?page=5&amp;per_page=20"}, {"first": "/products?page=0&amp;per_page=20"}, {"previous": "/products?page=4&amp;per_page=20"}, {"next": "/products?page=6&amp;per_page=20"}, {"last": "/products?page=26&amp;per_page=20"}, ] }, "records": [ { "id": 1, "name": "Widget #1", "uri": "/products/1" }, { "id": 2, "name": "Widget #2", "uri": "/products/2" }, { "id": 3, "name": "Widget #3", "uri": "/products/3" } ] } </code></pre> <p>For machine-readable metadata, I would add <a href="http://www.rfc-editor.org/rfc/rfc5988.txt" rel="noreferrer">Link headers</a> to the response:</p> <pre><code>Link: &lt;/products?page=5&amp;perPage=20&gt;;rel=self,&lt;/products?page=0&amp;perPage=20&gt;;rel=first,&lt;/products?page=4&amp;perPage=20&gt;;rel=previous,&lt;/products?page=6&amp;perPage=20&gt;;rel=next,&lt;/products?page=26&amp;perPage=20&gt;;rel=last </code></pre> <p><em>(the Link header value should be urlencoded)</em></p> <p>...and possibly a custom <code>total-count</code> response header, if you so choose:</p> <pre><code>total-count: 521 </code></pre> <p>The other paging data revealed in the human-centric metadata might be superfluous for machine-centric metadata, as the link headers let me know which page I am on and the number per page, and I can quickly retrieve the number of records in the array. Therefore, I would probably only create a header for the total count. You can always change your mind later and add more metadata.</p> <p><em>As an aside, you may notice I removed <code>/index</code> from your URI. A generally accepted convention is to have your ReST endpoint expose collections. Having <code>/index</code> at the end muddies that up slightly.</em></p> <p>These are just a few things I like to have when consuming/creating an API. Hope that helps!</p>
24,149,994
How can I use a regex to replace upper case with lower case in Intellij IDEA?
<p>I've googled for this and found out how to do with with other regex parsers:</p> <pre><code>http://vim.wikia.com/wiki/Changing_case_with_regular_expressions http://www.regular-expressions.info/replacecase.html </code></pre> <p>I've tried these and neither work. As an example, I want to use a regex to change this:</p> <pre><code>private String Name; private Integer Bar = 2; </code></pre> <p>To this:</p> <pre><code>private String name; private Integer bar = 2; </code></pre> <p>I tried something like this:</p> <pre><code>replace: private (\S+) (\S+) with: private $1 $L$2 with: private $1 \L$2 with: &lt;etc.&gt; </code></pre> <p>None of them work. Is it possible to do this in intellij, or is this a missing feature? This is just for educational purposes and the example is contrived. I just want to know if this is possible to do in intellij.</p>
32,137,232
3
4
null
2014-06-10 20:08:53.793 UTC
35
2016-04-20 00:22:17.233 UTC
null
null
null
null
61,624
null
1
106
java|regex|intellij-idea
29,635
<p><strong>In IDEA 15</strong> you're able to use the below switches to toggle the case of captured expressions. This is now <a href="https://www.jetbrains.com/idea/help/regular-expression-syntax-reference.html" rel="noreferrer">officially documented</a> since this version was released.</p> <ul> <li><code>\l</code>: lower the case of the one next character</li> <li><code>\u</code>: up the case of the one next character</li> <li><code>\L</code>: lower the case of the next characters until a <code>\E</code> or the end of the replacement string</li> <li><code>\U</code>: up the case of the next characters until a <code>\E</code> or the end of the replacement string</li> <li><code>\E</code>: mark the end of a case change initiated by <code>\U</code> or <code>\L</code></li> </ul> <p>Here is an example usage (as the documentation is not clear):</p> <blockquote> <p>find: (\w+_)+(\w+) replace: \L$1$2\E</p> </blockquote> <p>The above will convert <code>FOO_BAR_BAZ</code> to <code>foo_bar_baz</code> etc The $1 refers to the first found capture group (in parenthesis), $2 to the second set, etc.</p> <p>For posterity's sake: this was initially <a href="https://youtrack.jetbrains.com/issue/IDEA-70451" rel="noreferrer">reported</a> by @gaoagong and documented <a href="https://youtrack.jetbrains.com/issue/IDEA-70451#comment=27-1023022" rel="noreferrer">there</a>.</p>
4,012,996
jQuery change function not working
<p>I can't seem to get this working seems like it should </p> <pre><code>$('.titleother').change(function() { if ($('.titleother').val() == 'Other') { ​$('.hiddentext').css('display','block') }​​​ }) </code></pre> <p>For this HTML</p> <pre><code>&lt;select class="titleother"&gt;​ &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="Other"&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;p class="hiddentext" style="display:none"&gt;TEXT&lt;/p&gt; </code></pre> <p>Any ideas?</p>
4,013,174
3
3
null
2010-10-25 08:41:46.877 UTC
null
2015-07-18 00:03:18.117 UTC
2012-01-29 07:44:46.847 UTC
null
746,010
null
372,364
null
1
8
jquery|onchange
45,789
<p>This works for me using Chrome:</p> <pre><code>$(function(ready){ $('.titleother').change(function() { if ($(this).val() == 'Other') { $('.hiddentext').show(); } }); }); </code></pre> <p><a href="http://jsfiddle.net/amuec/11/" rel="noreferrer">http://jsfiddle.net/amuec/11/</a></p> <p>(Darin's code didn't work for me either)</p>
3,424,156
Upgrade SQLite database from one version to another?
<p>I am getting an error from <code>Logcat</code> saying that a certain column (in my <code>SQLiteOpenHelper</code> subclass) does not exist. I thought I could upgrade the database by changing the <code>DATABASE_CREATE</code> string. But apparently not, so how can I (step-by-step) upgrade my SQLite Database from version 1 to version 2? </p> <p>I apologize if the question seems "noobish", but I am still learning about Android. </p> <p>@Pentium10 This is what I do in onUpgrade:</p> <pre><code>private static final int DATABASE_VERSION = 1; .... switch (upgradeVersion) { case 1: db.execSQL("ALTER TABLE task ADD body TEXT"); upgradeVersion = 2; break; } ... </code></pre>
3,424,444
3
1
null
2010-08-06 13:23:27.2 UTC
34
2015-05-06 22:09:37.81 UTC
2014-02-10 06:31:10.147 UTC
null
1,318,946
null
200,477
null
1
14
java|android|sqlite|upgrade
22,868
<p>Ok, before you run into bigger problems you should know that SQLite is limited on the ALTER TABLE command, it allows <code>add</code> and <code>rename</code> only no remove/drop which is done with recreation of the table. </p> <p>You should always have the new table creation query at hand, and use that for upgrade and transfer any existing data. Note: that the onUpgrade methods runs one for your sqlite helper object and you need to handle all the tables in it.</p> <p>So what is recommended onUpgrade:</p> <ul> <li>beginTransaction</li> <li>run a table creation with <code>if not exists</code> (we are doing an upgrade, so the table might not exists yet, it will fail alter and drop)</li> <li>put in a list the existing columns <code>List&lt;String&gt; columns = DBUtils.GetColumns(db, TableName);</code></li> <li>backup table (<code>ALTER table " + TableName + " RENAME TO 'temp_" + TableName</code>)</li> <li>create new table (the newest table creation schema)</li> <li>get the intersection with the new columns, this time columns taken from the upgraded table (<code>columns.retainAll(DBUtils.GetColumns(db, TableName));</code>)</li> <li>restore data (<code>String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); </code>)</li> <li>remove backup table (<code>DROP table 'temp_" + TableName</code>)</li> <li>setTransactionSuccessful</li> </ul> <p>.</p> <pre><code>public static List&lt;String&gt; GetColumns(SQLiteDatabase db, String tableName) { List&lt;String&gt; ar = null; Cursor c = null; try { c = db.rawQuery("select * from " + tableName + " limit 1", null); if (c != null) { ar = new ArrayList&lt;String&gt;(Arrays.asList(c.getColumnNames())); } } catch (Exception e) { Log.v(tableName, e.getMessage(), e); e.printStackTrace(); } finally { if (c != null) c.close(); } return ar; } public static String join(List&lt;String&gt; list, String delim) { StringBuilder buf = new StringBuilder(); int num = list.size(); for (int i = 0; i &lt; num; i++) { if (i != 0) buf.append(delim); buf.append((String) list.get(i)); } return buf.toString(); } </code></pre>
3,834,175
jQuery key code for command key
<p>I have read <a href="https://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed">jQuery Event Keypress: Which key was pressed?</a> and <a href="https://stackoverflow.com/questions/2445613/how-can-i-check-if-key-is-pressed-during-click-event-with-jquery">How can i check if key is pressed during click event with jquery?</a></p> <p>However my question is if you can get the same key event for all browsers? Currently I know that Firefox gives the <kbd>command</kbd> button (Mac) the code 224 while Chrome and Safari give it the value 91. Is the best approach to simply check what browser the user is using and base the key pressed on that or is there a way so that I can get 1 key code across all browsers? Note I am getting the value with the:</p> <pre><code>var code = (evt.keyCode ? evt.keyCode : evt.which); </code></pre> <p>I would love to not use a plugin if possible just because I only need to know about the <kbd>command</kbd>/<kbd>ctrl</kbd> (windows system) key pressed.</p>
3,834,210
3
4
null
2010-09-30 19:36:04.213 UTC
14
2021-09-23 15:30:19.973 UTC
2017-05-23 12:09:24.12 UTC
null
-1
null
362,969
null
1
50
javascript|jquery|command|keydown|onkeyup
56,787
<p>jQuery already handles that. To check if control was pressed you should use:</p> <pre><code>$(window).keydown(function (e){ if (e.ctrlKey) alert("control"); }); </code></pre> <p>The list of modifier keys:</p> <pre><code>e.ctrlKey e.altKey e.shiftKey </code></pre> <p>And as fudgey suggested:</p> <pre><code>e.metaKey </code></pre> <p><a href="http://answers.google.com/answers/threadview/id/16409.html" rel="noreferrer">Might work on MAC. Some other ways here as well</a>.</p>
3,955,959
What's an easy way to get the url in the current window minus the domain name?
<p>My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:</p> <p>If the current url is: "http://stackoverflow.com/questions/ask"</p> <p>What's a good way to to just get: "/questions/ask" ?</p> <p>Basically I want a string that matches the Url without the domain or the "http://"</p>
3,955,962
3
0
null
2010-10-18 00:42:26.533 UTC
6
2021-09-09 08:02:25.34 UTC
null
null
null
null
204,355
null
1
67
javascript|string|url
35,778
<pre><code>alert(window.location.pathname); </code></pre> <p><a href="https://developer.mozilla.org/en/DOM/window.location" rel="noreferrer">Here's some documentation for you</a> for <code>window.location</code>.</p>
3,517,162
How to undo the effect of "set -e" which makes bash exit immediately if any command fails?
<p>After entering <code>set -e</code> in an interactive bash shell, bash will exit immediately if any command exits with non-zero. How can I undo this effect?</p>
3,517,181
3
0
null
2010-08-18 22:13:37.093 UTC
25
2018-06-29 08:38:55.57 UTC
2018-06-29 08:38:55.57 UTC
null
895,245
null
424,592
null
1
231
bash|exit
61,449
<p>With <code>set +e</code>. Yeah, it's backward that you <em>enable</em> shell options with <code>set -</code> and <em>disable</em> them with <code>set +</code>. Historical raisins, donchanow.</p>
38,127,053
Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0
<p>So this morning I started updating to the latest version of my project libraries.</p> <p>I'm trying to update GCM to the latest version 9.2.0, but I get this error:</p> <blockquote> <p>Error:Execution failed for task ':app:processDebugGoogleServices'. Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at <a href="https://bintray.com/android/android-tools/com.google.gms.google-services/">https://bintray.com/android/android-tools/com.google.gms.google-services/</a>) or updating the version of com.google.android.gms to 9.0.0.</p> </blockquote> <p>This is how I have my code:</p> <pre><code>dependencies { classpath 'com.android.tools.build:gradle:2.1.2' classpath 'com.google.gms:google-services:3.0.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' } </code></pre> <p>And then:</p> <pre><code>dependencies { ... compile "com.google.android.gms:play-services-gcm:9.2.0" ... } </code></pre> <p>Anyone having the same issue/fixed the same issue?</p> <p>Thanks.</p> <p><strong>EDIT</strong></p> <p>Apparently you have to apply your GSM plugin at the bottom of your app/build.gradle file. Else, version 9.2.0 will cause conflict in your project.</p> <p>For reference, this is how my app/build.gradle file looks like now:</p> <pre><code>apply plugin: "com.android.application" apply plugin: "com.neenbedankt.android-apt" android { ... } dependencies { ... // Google Cloud Messaging compile "com.google.android.gms:play-services-gcm:9.2.0" ... } apply plugin: "com.google.gms.google-services" </code></pre>
38,202,698
11
6
null
2016-06-30 15:07:29.12 UTC
24
2017-12-03 17:51:07.51 UTC
2016-07-07 18:01:37.363 UTC
null
6,996,944
null
6,996,944
null
1
178
android|google-cloud-messaging|google-play-services
121,670
<p>Do you have the line </p> <pre><code>apply plugin: 'com.google.gms.google-services' </code></pre> <p>line at the bottom of your app's build.gradle file?</p> <p>I saw some errors when it was on the top and as it's written <a href="https://firebase.google.com/docs/android/setup#add_the_sdk" rel="noreferrer">here</a>, it should be at the bottom.</p>
8,916,656
Why is arr and &arr the same?
<p>I have been programming c/c++ for many years, but todays accidental discovery made me somewhat curious... Why does both outputs produce the same result in the code below? (<code>arr</code> is of course the address of <code>arr[0]</code>, i.e. a pointer to <code>arr[0]</code>. I would have expected <code>&amp;arr</code> to be the adress of that pointer, but it has the same value as <code>arr</code>) </p> <pre><code> int arr[3]; cout &lt;&lt; arr &lt;&lt; endl; cout &lt;&lt; &amp;arr &lt;&lt; endl; </code></pre> <p>Remark: This question was closed, but now it is opened again. (Thanks ?)</p> <p>I know that <code>&amp;arr[0]</code> and <code>arr</code> evaluates to the same number, but that is <em>not</em> my question! The question is why <code>&amp;arr</code> and <code>arr</code> evaluates to the same number. If <code>arr</code> is a literal (not stored anyware), then the compiler should complain and say that <code>arr</code> is not an lvalue. If the address of the <code>arr</code> is stored somewhere then <code>&amp;arr</code> should give me the address of that location. (but this is not the case)</p> <p>if I write</p> <blockquote> <p>const int* arr2 = arr;</p> </blockquote> <p>then <code>arr2[i]==arr[i]</code> for any integer <code>i</code>, but <code>&amp;arr2 != arr</code>. </p>
8,916,695
7
6
null
2012-01-18 20:04:53.833 UTC
15
2022-03-22 08:27:35.02 UTC
2012-02-04 07:50:38.377 UTC
null
46,642
null
165,729
null
1
24
c++|c|pointers
15,790
<p>They're not the same. They just are at the same memory location. For example, you can write <code>arr+2</code> to get the address of <code>arr[2]</code>, but not <code>(&amp;arr)+2</code> to do the same.</p> <p>Also, <code>sizeof arr</code> and <code>sizeof &amp;arr</code> are different.</p>
11,409,912
Android how to update value of ProgressBar?
<p>My activity have a ProgressBar. When start activity, I'll check value get from another place and update to ProgressBar. Here's my code:</p> <pre><code>final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar_detail); final TextView progressText = (TextView) findViewById(R.id.progressText_detail); final ImageView btnCancel = (ImageView) findViewById(R.id.imgCancel_detail); progressBar.setVisibility(View.VISIBLE); progressText.setVisibility(View.VISIBLE); btnCancel.setVisibility(View.VISIBLE); Thread t = new Thread() { public void run() { ((Activity) ctx).runOnUiThread(new Runnable() { public void run() { int oldProgress = 0; while (progressBar.getProgress() &lt; 100) { int value = Downloader.progress.get(gameId+ ""); if (value != oldProgress) { oldProgress = value; progressBar.setProgress(value); progressText.setText(value + " %"); } } } }); } }; t.start(); </code></pre> <p>Value of ProgressBar i get from <code>int value = Downloader.progress.get(gameId)</code> and it's correct. But when I run this code, the activity is not responding and not showing anything (but app not crash). Seems like the thread to update ProgressBar running and block the UI thread so the activity layout is not showing.</p> <p>What's wrong with my code? What is the correct way to update ProgressBar in this situation?</p>
11,410,030
4
3
null
2012-07-10 08:59:54.683 UTC
2
2018-10-08 14:10:43.237 UTC
2012-07-10 09:05:41.493 UTC
null
1,417,127
null
1,417,127
null
1
9
android|progress-bar
60,322
<p>You are running a <code>while (progressBar.getProgress() &lt; 100)</code> in the UI thread (you use <code>runOnUiThread</code>) so UI thread will be blocked (and nothing painted) until this loop finish.</p> <p>You can:</p> <ul> <li><p>Put the <code>runOnUiThread</code> inside the loop and, maybe, a sleep inside de <code>runOnUiThread</code> call. However, it is not the preferred kind of solution since you are using too much CPU to just look for a value change. The sleep approach it a bit ugly but solves the cpu problem. It would be something like::</p> <pre><code>Thread t = new Thread() { public void run() { int oldProgress = 0; while (progressBar.getProgress() &lt; 100) { ((Activity) ctx).runOnUiThread(new Runnable() { public void run() { int value = Downloader.progress.get(gameId+ ""); if (value != oldProgress) { oldProgress = value; progressBar.setProgress(value); progressText.setText(value + " %"); } } } Thread.sleep(500); } }); } }; </code></pre></li> <li><p>Update the progress bar in an event way so you only call (in the UI thread) the update code when progress changes. It is the preferred way.</p></li> </ul>
11,249,633
Make Localhost a Custom Domain in IIS Express
<p>I am using IIS Express in Visual Studio 2010 and right now it runs on localhost:61156. But I need it to run on a domain. Is it possible to make IIS Express to run on devserver.com, instead of localhost:61156? So basically when I run debug I want devserver,com, instead of localhost:61156. I've come across a few things on google, but no luck. Any ideas on how to do this?</p> <p>Thanks!</p>
11,250,513
2
0
null
2012-06-28 17:09:10.767 UTC
12
2018-09-11 10:21:13.007 UTC
null
null
null
user482375
null
null
1
15
visual-studio-2010|iis-7.5|iis-express
9,170
<p>Do the following</p> <ol> <li>If IIS Express is running stop it</li> <li>Open your webapplication project file (*.csproj or *.vbproj) </li> <li>Find <code>&lt;IISUrl&gt;http://localhost:61156/&lt;/IISUrl&gt;</code> and change it to &lt;<code>IISUrl&gt;http://devserver.com:61156/&lt;/IISUrl&gt;</code></li> <li><p>Open %userprofile%\documents\iisexpress\config\applicationhost.config file</p></li> <li><p><strong>Visual Studio 2015 now puts an applicationhost.config file specific to your project instead of using the global one. It is located at: <em>/path/to/code/root/.vs/config/applicationhost.config</em></strong></p></li> <li>Find your site entry in applicationhost.config file change the binding as shown below<br> <code>&lt;binding protocol="http" bindingInformation="*:61156:devserver.com" /&gt;</code></li> <li>In \Windows\system32\drivers\etc\hosts file add following mapping "<code>127.0.0.1 devserver.com</code>"</li> <li>In your browser add exception to bypass proxy for devserver.com</li> <li>Note that, since you are using custom domain (non localhost binding), you must run visual studio as Administrator</li> </ol>
11,445,125
Disabling particular Items in a Combobox
<p>I have a WinForms App and I was wondering if there was a more elegant way of disabling Combobox item without changing the SelectedIndex property -1 for all disabled values.</p> <p>I have been googling and a lot of the solutions involve ASP.Net DropDownLists but this <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.drawmode%28VS.80%29.aspx">LINK</a> looks promising. I think I may have to build my own ComboBox control but before I re-invent the wheel I figure I would ask here if it was possible.</p> <h1><strong>UPDATE</strong></h1> <p>Here is the final solution, thanks to Arif Eqbal:</p> <pre><code>//Add a Combobox to a form and name it comboBox1 // using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed; this.comboBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox1_DrawItem); this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); } private void Form1_Load(object sender, EventArgs e) { this.comboBox1.Items.Add("Test1"); this.comboBox1.Items.Add("Test2"); this.comboBox1.Items.Add("Test3"); this.comboBox1.Items.Add("Test4"); this.comboBox1.Items.Add("Test5"); this.comboBox1.Items.Add("Test6"); this.comboBox1.Items.Add("Test7"); } Font myFont = new Font("Aerial", 10, FontStyle.Underline|FontStyle.Regular); Font myFont2 = new Font("Aerial", 10, FontStyle.Italic|FontStyle.Strikeout); private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == 1 || e.Index == 4 || e.Index == 5)//We are disabling item based on Index, you can have your logic here { e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont2, Brushes.LightSlateGray, e.Bounds); } else { e.DrawBackground(); e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.Black, e.Bounds); e.DrawFocusRectangle(); } } void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedIndex == 1 || comboBox1.SelectedIndex == 4 || comboBox1.SelectedIndex == 5) comboBox1.SelectedIndex = -1; } } } </code></pre>
11,446,265
3
2
null
2012-07-12 04:44:00.633 UTC
10
2019-07-04 15:26:21.647 UTC
2012-07-12 07:29:31.307 UTC
null
100,283
null
100,283
null
1
20
c#|winforms|combobox
45,837
<p>Try this... Does it serve your purpose:</p> <p>I assume you have a combobox called <code>ComboBox1</code> and you want to disable the second item i.e. an item with index 1. </p> <p>Set the <code>DrawMode</code> property of the combobox to <code>OwnerDrawFixed</code> then handle these two events as shown below:</p> <pre><code>Font myFont = new Font("Aerial", 10, FontStyle.Regular); private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == 1) //We are disabling item based on Index, you can have your logic here { e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.LightGray, e.Bounds); } else { e.DrawBackground(); e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.Black, e.Bounds); e.DrawFocusRectangle(); } } void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedIndex == 1) comboBox1.SelectedIndex = -1; } </code></pre>
11,393,438
What is ActiveRecord equivalence in the node.js world?
<p>I am considering to use <code>node.js</code> tools for a upcoming project, for learning and performance purpose. <a href="https://stackoverflow.com/questions/11151243/how-to-optimize-this-query-in-activerecord-latest-10-topics-by-friends">For example</a>, some models in Rails:</p> <pre><code>class User has_many :topics has_many :friends has_many :friend_users, :through =&gt; :friends has_many :friend_topics, :through =&gt; :friend_users, :source =&gt; :topics end class Friend belongs_to :user belongs_to :friend_user, :class_name =&gt; "User", :foreign_key =&gt; :phone_no, :primary_key =&gt; :phone_no end class Topic belongs_to :user end </code></pre> <p>allows elegant query code like:</p> <pre><code>latest_10_topics_from_friends = current_user.friend_topics.limit(10) </code></pre> <p>and generates optimized SQLs. Is there something similar in <code>node.js</code> ecosystem?</p>
11,401,877
4
2
null
2012-07-09 10:42:29.537 UTC
4
2017-08-10 03:43:20.263 UTC
2017-05-23 11:59:55.81 UTC
null
-1
null
88,597
null
1
28
ruby-on-rails|node.js|activerecord
26,234
<h2>Updated answer</h2> <p>Use <a href="https://github.com/sequelize/sequelize" rel="nofollow noreferrer">sequelize</a></p> <hr> <h3>Old answer:</h3> <p>Look at the <a href="https://github.com/viatropos/tower" rel="nofollow noreferrer">Tower</a> project. You can define your models as follows:</p> <pre><code># app/models/user.coffee class App.User extends Tower.Model @belongsTo "author", type: "User" @belongsTo "commentable", polymorphic: true @has_many "topics" @has_many "friends" @has_many "friend_users", through: "friends" @has_many "friend_topics", through: "friends_users", source: "topics" # app/models/friend.coffee class App.Friend extends Tower.Model @belongs_to "user" @belongs_to "friend_user", type: "User", foreign_key: "phone_no", primary_key: "phone_no" # app/models/topic.coffee class App.Topic extends Tower.Model @belongs_to "user" </code></pre> <p>Now you will be able to query your data as</p> <pre><code>current_user.friend_topics().limit(10) </code></pre>
11,269,575
How to hide output of subprocess
<p>I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:</p> <pre><code>import subprocess text = 'Hello World.' print text subprocess.call(['espeak', text]) </code></pre> <p>eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib..., no socket connect) so i cannot easily read what was printed earlier. Exit code is 0. </p> <p>Unfortunately there is no documented option to turn off its verbosity, so I'm looking for a way to only visually silence it and keep the open shell clean for further interaction.</p> <p>How can I do this?</p>
11,269,627
5
6
null
2012-06-29 22:08:57.657 UTC
68
2021-09-25 18:20:32.417 UTC
2021-09-25 18:20:32.417 UTC
null
9,426,920
null
1,492,145
null
1
344
python|subprocess|espeak
291,968
<p>For python &gt;= 3.3, Redirect the output to DEVNULL:</p> <pre><code>import os import subprocess retcode = subprocess.call(['echo', 'foo'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) </code></pre> <p>For python &lt;3.3, including 2.7 use:</p> <pre><code>FNULL = open(os.devnull, 'w') retcode = subprocess.call(['echo', 'foo'], stdout=FNULL, stderr=subprocess.STDOUT) </code></pre> <p>It is effectively the same as running this shell command:</p> <pre><code>retcode = os.system(&quot;echo 'foo' &amp;&gt; /dev/null&quot;) </code></pre>
12,970,187
Nested SELECT statement with LEFT JOIN
<p>I can't for the life of me figure out what's wrong with this SQL statement and why it's not producing any results. If I take out the LEFT JOIN is works, so what's wrong with it?</p> <pre><code>SELECT b.id, r.avg_rating FROM items AS b LEFT JOIN ( SELECT avg(rating) as avg_rating FROM ratings GROUP BY item_id ) AS r ON b.id = r.item_id WHERE b.creator = " . $user_id . " AND b.active = 1 AND b.deleted = 0 ORDER BY b.order ASC, b.added DESC </code></pre> <p>Would appreciate the help greatly. </p>
12,970,209
1
0
null
2012-10-19 08:23:58.693 UTC
null
2013-01-03 09:04:53.717 UTC
2013-01-03 09:04:53.717 UTC
null
491,243
null
695,408
null
1
9
php|mysql|sql|left-join
40,485
<p>add the <code>item_id</code> column in your subquery (<em>I guarantee that it will work</em>) so the <code>ON</code> clause can find <code>r.item_id</code></p> <pre><code>SELECT item_id, avg(rating) as avg_rating FROM ratings GROUP BY item_id </code></pre>
12,760,491
The R console is in my native language, how can I set R to English?
<p>I am using R on Windows 7. Apparently R somehow found evidence that I speak languages besides English, and stubbornly insists on giving output in the console in my own language. For a variety of reasons, this is undesirable, and I want R to be English.</p> <h2>What works</h2> <p>I am able to use <code>LANGUAGE=en</code> as a command line option for the R console desktop shortcut, but the language is still wrong in Rstudio, which launches the R executable directly and hence ignores the command line arguments in the shortcut.</p> <h2>What doesn't work</h2> <p>I have tried creating an <code>.Renviron</code> file under <code>C:\Users\[MY_NAME]\Documents</code>, which is the path returned for the working directory by <code>getwd()</code>, with <code>LANGUAGE=en</code> in it. R ignores this. My <code>R_ENVIRON</code> and <code>R_ENVIRON_USER</code> variables show up as <code>""</code> so <code>.Renviron</code> should be the correct filename.</p> <p>I have also tried creating <code>.Renviron</code> under <code>R_HOME\etc</code> (<code>R_HOME</code> points to <code>C:/PROGRA~1/R/R-215~1.0</code>) and R also ignores it.</p> <p>I was somewhat successful with adding <code>Sys.setenv(LANGUAGE="en")</code> in <code>R_HOME\etc</code> - this made all output from the R console English, except for the initial copyright information.</p> <h2>The question</h2> <p>How can I make R default to English such that this is propagated to RStudio?</p>
12,760,493
6
0
null
2012-10-06 14:06:14.007 UTC
23
2017-02-21 01:46:09.81 UTC
2012-10-06 21:19:07.887 UTC
null
1,042,555
null
1,042,555
null
1
66
windows|r|localization|settings|rstudio
60,518
<p>On a fresh install, adding <code>language = en</code> to the <code>Rconsole</code> file (which exists by default under <code>R_HOME\etc</code>) will make R's language English in the R console as well as RStudio. This can be overridden by code in the working directory and RStudio's individual projects.</p>
16,691,437
When are Java temporary files deleted?
<p>Suppose I create a temporary file in Java with the method</p> <pre><code>File tmp = File.createTempFile(prefix, suffix); </code></pre> <p>If I do not explicity call the <code>delete()</code> method, when will the file be deleted?</p> <p>As an intuition, it might be when the JVM terminates, or <em>earlier</em> (by the Garbage Collector), or <em>later</em> (by some Operating System sweeping process).</p>
16,691,560
6
2
null
2013-05-22 12:12:45.473 UTC
16
2015-03-02 14:22:32.88 UTC
null
null
null
null
2,091,700
null
1
108
java|garbage-collection|temporary-files
98,197
<p>The file won't be deleted automatically, from the <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String,%20java.io.File%29" rel="noreferrer">JavaDoc</a>:</p> <blockquote> <p>This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.</p> </blockquote> <p>So you have to explicitly call <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit%28%29" rel="noreferrer">deleteOnExit()</a>:</p> <blockquote> <p>Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.</p> </blockquote>
4,235,171
Installing Tomcat 7 on Linux system with Native Library
<p>How do you install native library for <code>Tomcat 7.0</code> under Linux system such as CentOS?</p>
7,175,301
2
1
null
2010-11-20 21:45:31.107 UTC
9
2019-08-28 18:37:53.46 UTC
2019-08-28 18:37:53.46 UTC
null
985,906
null
465,179
null
1
8
linux|tomcat|installation|linux-native-library
23,872
<h3>Installer</h3> <pre><code>wget ftp:\\yourdeployment.server.local/tomcat7.tar.gz tar xvzf tomcat7.tar.gz cp -f tomcat /usr/share/tomcat7 rm -f /usr/share/tomcat ln -s /usr/share/tomcat7 /usr/share/tomcat chmod 777 /usr/share/tomcat7/bin/ *.sh useradd -d /usr/share/tomcat -s /sbin/nologin tomcat chown -R tomcat /usr/share/tomcat7 rm -f /etc/init.d/tomcat cp -f /usr/share/tomcat7/tomcat /etc/init.d/ chmod +x /etc/init.d/tomcat rm -f /etc/profile.d/env.sh cp -f /usr/share/tomcat7/env.sh /etc/profile.d/ chmod +x /etc/profile.d/env.sh chmod 755 /etc/init.d/tomcat </code></pre> <h3>Native package installation</h3> <pre><code>cd /usr/share/tomcat7/bin tar -xvzf tomcat-native.tar.gz cd tomcat-native-&lt;replace with current version&gt;-src/jni/native ./configure --with-apr=/usr &amp;&amp; make &amp;&amp; sudo make install cd /usr/lib rm -f libtcnative-1.so ln -s /usr/local/apr/lib/libtcnative-1.so libtcnative-1.so init 6 </code></pre> <h3>tomcat file:</h3> <pre><code>#!/bin/bash chkconfig: 234 20 80 description: Tomcat Server basic start/shutdown script processname: tomcat export JAVA_HOME=/jdk7 export TOMCAT_HOME=/usr/share/tomcat7 export JEE_JAR=/jdk7 export JRE_HOME=/jdk7/jre export PATH=$PATH:$JAVA_HOME/bin export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar case $1 in start) sh /usr/share/tomcat7/bin/startup.sh ;; stop) sh /usr/share/tomcat7/bin/shutdown.sh ;; restart) sh /usr/share/tomcat7/bin/shutdown.sh sh /usr/share/tomcat7/bin/startup.sh ;; esac exit 0 </code></pre> <h3>env.sh</h3> <pre><code>export JAVA_HOME=/jdk7 export JRE_HOME=$JAVA_HOME export TOMCAT_HOME=/usr/share/tomcat7 export PATH=$PATH:$JAVA_HOME/bin export CLASSPATH=.:$JRE_HOME/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar </code></pre>
4,814,867
Fill hash map during creation
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/507602/how-to-initialise-a-static-map-in-java">How to Initialise a static Map in Java</a> </p> </blockquote> <p>How to fill HashMap in Java at initialization time, is possible something like this ?</p> <pre><code>public static Map&lt;byte,int&gt; sizeNeeded=new HashMap&lt;byte,int&gt;(){1,1}; </code></pre>
4,814,910
2
0
null
2011-01-27 09:54:42.397 UTC
10
2021-10-08 15:24:44.237 UTC
2017-05-23 12:00:28.833 UTC
null
-1
null
486,578
null
1
26
java|collections|initialization
41,702
<p><code>byte</code>, <code>int</code> are primitive, collection works on object. You need something like this:</p> <pre class="lang-java prettyprint-override"><code>public static Map&lt;Byte, Integer&gt; sizeNeeded = new HashMap&lt;Byte, Integer&gt;() {{ put(new Byte(&quot;1&quot;), 1); put(new Byte(&quot;2&quot;), 2); }}; </code></pre> <p>This will create a new <code>map</code> and using <a href="http://download.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="nofollow noreferrer"><em>initializer block</em></a> it will call put method to fill data.</p>
4,165,174
When does a UDP sendto() block?
<p>While using the default (blocking) behavior on an UDP socket, in which case will a call to sendto() block? I'm interested essentially in the Linux behavior.</p> <p>For TCP I understand that congestion control makes the send() call blocking if the sending window is full, but what about UDP? Does it even block sometimes or just let packets getting discarded at lower layers?</p>
4,165,711
2
0
null
2010-11-12 13:39:35.393 UTC
15
2021-01-22 14:52:35.93 UTC
2012-05-27 19:18:32.463 UTC
null
648,658
null
1,377,500
null
1
33
network-programming|udp|blocking
28,796
<p>This can happen if you filled up your socket buffer, but it is <em>highly operating system dependent</em>. Since UDP does not provide any guarantee your operating system can decide to do whatever it wants when your socket buffer is full: block or drop. You can try to increase SO_SNDBUF for temporary relief.</p> <p>This can even depend on the fine tuning of your system, for instance it can also depend on the size of the TX ring in the driver of your network interface. There are a few discussions about this in the <a href="http://www.mail-archive.com/search?q=udp+socket+buffer&amp;l=iperf-users%40lists.sourceforge.net" rel="noreferrer">iperf mailing list</a>, but you really want to discuss this with the <em>developers of your operating system</em>. Pay special attention to O_NONBLOCK and EAGAIN / EWOULDBLOCK.</p>
4,117,228
Reflection MethodInfo.Invoke() catch exceptions from inside the method
<p>I have a call to <code>MethodInfo.Invoke()</code> to execute a function through reflection. The call is wrapped in a <code>try/catch</code> block but it still won't catch the exception thrown by the function I'm invoking.</p> <p>I receive the following message:</p> <blockquote> <p>Exception was unhandled by the user.</p> </blockquote> <p><br /> Why does <code>MethodInfo.Invoke()</code> prevent the Exception to be caught outside of the <code>Invoke()</code>?<br> How do I bypass it? </p>
4,117,437
2
0
null
2010-11-07 09:52:20.687 UTC
2
2013-03-11 18:34:49.863 UTC
2013-02-12 18:52:13.813 UTC
null
1,518,087
null
154,293
null
1
34
c#|exception|reflection|methods|invoke
35,725
<p>EDIT: As I understand your issue, the problem is purely an IDE one; you don't like VS treating the exception thrown by the invocation of the <code>MethodInfo</code> as uncaught, when it clearly isn't. You can read about how to resolve this problem here: <a href="https://stackoverflow.com/questions/2658908/why-is-targetinvocationexception-treated-as-uncaught-by-the-ide">Why is TargetInvocationException treated as uncaught by the IDE?</a> It appears to be a bug / by design; but one way or another, decent workarounds are listed in that answer.</p> <p>As I see it, you have a couple of options:</p> <ol> <li><p>You can use <code>MethodInfo.Invoke</code>, catch the <code>TargetInvocationException</code> and inspect its <code>InnerException</code> property. You will have to workaround the IDE issues as mentioned in that answer.</p></li> <li><p>You can create an appropriate <code>Delegate</code> out of the <code>MethodInfo</code> and invoke that instead. With this technique, the thrown exception will not be wrapped. Additionally, this approach <em>does</em> seem to play nicely with the debugger; I don't get any "Uncaught exception" pop-ups.</p></li> </ol> <p>Here's an example that highlights both approaches:</p> <pre><code>class Program { static void Main() { DelegateApproach(); MethodInfoApproach(); } static void DelegateApproach() { try { Action action = (Action)Delegate.CreateDelegate (typeof(Action), GetMethodInfo()); action(); } catch (NotImplementedException nie) { } } static void MethodInfoApproach() { try { GetMethodInfo().Invoke(null, new object[0]); } catch (TargetInvocationException tie) { if (tie.InnerException is NotImplementedException) { } } } static MethodInfo GetMethodInfo() { return typeof(Program) .GetMethod("TestMethod", BindingFlags.NonPublic | BindingFlags.Static); } static void TestMethod() { throw new NotImplementedException(); } } </code></pre>
9,669,805
How do I animate though a PNG sequence using jQuery (either by scrolling or triggered animation)
<p>More and more I am seeing an effect where pngs are loaded into a series of DIVs (or one div) and then sequenced though frame by frame either based on button click or based on scroll. I've tried to peek at the code, and I understand that javascript is doing the heavy lifting, but I'm still a bit lost, are there any tutorials on this technique? examples?</p> <p>example of animation (multiple div) <a href="http://atanaiplus.cz/index_en.html" rel="noreferrer">http://atanaiplus.cz/index_en.html</a>:</p> <p>example of animation (one div): <a href="http://www.hyundai-veloster.eu/" rel="noreferrer">http://www.hyundai-veloster.eu/</a></p> <p>example of scrolling animation: <a href="http://discover.store.sony.com/tablet/#design/ergonomics" rel="noreferrer">http://discover.store.sony.com/tablet/#design/ergonomics</a></p>
9,669,981
2
0
null
2012-03-12 15:20:23.213 UTC
6
2014-09-11 06:14:42.723 UTC
2014-09-11 06:14:42.723 UTC
null
-1
null
379,468
null
1
6
jquery|animation|sequence|parallax
56,442
<p>you just want to swap out the src attribute using a setInterval timer</p> <pre><code>var myAnim = setInterval(function(){ $(".myImageHolder").attr('src', nextImage); }, 42); </code></pre> <p>The trick is how you generate <code>nextImage</code>. This largely depends on the naming conventions of your images, or which direction you wish the animation to run in</p> <p><strong>Update</strong></p> <p>Or use a <a href="http://spritely.net/" rel="noreferrer">plugin</a></p>
10,182,857
Getting error message with spring "cvc-elt.1: Cannot find the declaration of element 'beans'."
<p>I'm trying to set up a simple spring application and I'm getting the below exception. This is being run standalone in eclipse indigo.</p> <pre><code>Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Line 2 in XML document from class path resource [context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'. org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318) </code></pre> <p>Here's the initial portion of my code:</p> <pre><code>public static void main(String[] args) { try { BeanFactory beanfactory = new ClassPathXmlApplicationContext( "context.xml"); FirstBean bean = (FirstBean) beanfactory.getBean("show"); </code></pre> <p>Here's my context.xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"&gt; &lt;bean id="anotherBean" class="AnotherBean" /&gt; &lt;bean id="show" class="FirstBean"&gt; &lt;constructor-arg ref="anotherBean" /&gt; &lt;/bean&gt; &lt;bean id="populateFD" class="PopulateFactData"&gt; &lt;constructor-arg value="localhost" /&gt; &lt;constructor-arg value="3309" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
10,183,361
5
1
null
2012-04-16 22:55:58.09 UTC
2
2015-09-18 07:02:03.127 UTC
null
null
null
null
549,226
null
1
10
java|eclipse|spring
49,547
<p>Are you sure you have <code>spring-beans</code> on the classpath?</p> <p>This error normally means that it can't find a <code>spring.schemas</code> (which is in <code>spring-beans.jar</code>) explaining to it what that namespace means.</p> <p>Other options are that the Maven Shade plugin has damaged <code>spring.schemas</code>, but that's unlikely to be the case as you haven't mentioned Maven.</p>
9,676,149
SSRS - Expression using different dataset fields
<p>I have a report with multiple data-sets. Different fields from different data-sets are used in different locations of the report. </p> <p>In one part of the report, I need to do a calculation using fields from two different data-sets. Is this possible within an expression?<br> Can I somehow reference the data-set the field is in, in the expression?</p> <p>For example, I'd like to do something like this: </p> <pre><code>=Fields.Dataset1.Field / Fields.Dataset2.Field </code></pre>
9,677,237
3
0
null
2012-03-12 23:15:45.14 UTC
1
2016-06-30 19:25:29.35 UTC
2012-03-14 02:39:11.017 UTC
null
331,508
null
884,625
null
1
10
ssrs-2008|reporting-services|bids|reportbuilder3.0
75,463
<p>You can achieve that by specifying the scope of you fields like this:</p> <pre><code>=First(Fields!fieldName_A.Value, "Dataset1") / First(Fields!fieldName_B.Value, "Dataset2") </code></pre> <p>Assuming A is 10 and B is 2 and they are of type numeric then you will have the result of 5 when the report renders.</p> <p>When you are in the expression builder you can choose the Category: Datasets, your desired dataset highlighted under Item: and then double click the desired field under Value: and it will appear in your expression string with the scope added.</p> <p>Using same logic you can concatenate two fields like so:</p> <pre><code>=First(Fields!fieldName_A.Value, "Dataset1") &amp; “ “ &amp; First(Fields!fieldName_B.Value, "Dataset2") </code></pre>
9,944,160
NASM is pure assembly, but MASM is high level Assembly?
<p>I'm learning assembly, motivation being able to <strong>reverse engineer</strong>. I'm trying to find the assembler I should begin with, so that I can then find tutorials and start writing some assembly.</p> <p>I came to know that MASM has a lot of built in constructs, so I'll be using them mostly instead of coding them which I'll have to do if I choose NASM.</p> <p>My question is.. is that true? If it is, <strong>what assembler you suggest for learning assembly from a reverse engineer's perspective</strong> and some good tutorials for it.</p> <p>Also, if you have other suggestions regarding reversing? Alternative approach or something?</p> <p>P.S: I have read many articles and questions here, but am still confused.</p>
9,944,294
1
6
null
2012-03-30 13:42:29.48 UTC
11
2012-03-31 12:48:11.257 UTC
2012-03-30 20:57:02.303 UTC
null
1,241,347
null
1,241,347
null
1
12
assembly|x86|reverse-engineering|nasm|masm
9,409
<p>My recommendation purely from a "reverse engineering" perspective is to understand how a compiler translates high-level concepts into assembly language instructions in the first place. The understanding of how register allocation is done in various compilers and how various optimizations will obscure the high-level representation of nested loops (et.al.) is more important than being able to write one particular dialect of assembly input.</p> <p>Your best bet is to start with the assembly language intermediate files from source code that you write (see <a href="https://stackoverflow.com/questions/840321/how-can-i-see-the-assembly-code-for-a-c-program">this question for more information</a>). Then you can change the source and see how it affects the intermediate files. The other place to start is by using an <em>interactive disassembler</em> like <a href="http://www.hex-rays.com/" rel="noreferrer">IDA Pro</a>.</p> <p>Actually writing assembly language programs and learning the syntax of NASM, MASM, <code>gas</code>, of <code>as</code> is the easiest part and it does not really matter which one you learn. They are very similar because the syntax of the source language is very basic. If you are planning to learn how to disassemble and understand what a program is doing, then I would completely ignore macro assemblers since the macros completely disappear during translation and you will not see them when looking at disassembler output.</p> <p><strong>Diatribe on Learning Assembly</strong></p> <p>Learning an assembly language is different than learning a higher level programming language. There are fewer syntactical constructs if you ignore macro assemblers. The problem is that every compiler chain has a slightly different representation so you have to concentrate on the concepts such as supported address modes, register restrictions, etc. These aren't part of the language per se as they are dictated by the hardware.</p> <p>The approach that I took (partially because the university forced me to), is to explore and understand the hardware itself (e.g., # of registers, size of registers, type of branch instructions supported, etc.) and slightly more academic concepts such as interrupts and using bitwise manipulation for integer match before you start to write assembly language programs. This is a much longer route but results in a rich understanding of assembly and how to write high performance programs.</p> <p>The interesting thing is that in the time that I spent learning assembly and compiler construction (which is intrinsically related), I actually wrote very few assembly programs. More often, I am required to write little snippets of inline assembly here and there (e.g. setting up index registers when the runtime loader didn't). I have spent an enormous amount of time dissecting crash dumps from a memory location, loader map file, and assembler output listings. I can honestly say that the syntax of each assembler is dramatically different as well as what various compilers will do to muddle the intent into fast or small code. </p> <p>Learning how to write assembly programs was the least worthwhile part of the education process. It was necessary to understand how source is translated into the bits and bytes that the computer executes, but it really was not what I really needed to reverse engineer from a raw binary (disassembler -> assembly listing -> best guess of high level intent) or a memory dump. I do more of the latter, but the requirements of the job are the same.</p> <ol> <li>You really have to understand what the constraints of the architecture are.</li> <li>You have to know the very basic syntax of the assembler in question - how are address modes indicated, how are registers indicated, what is the order of arguments for a <code>move</code></li> <li>What transformations a compiler does to go from <code>if (a &gt; 0)</code> to <code>mov.b r0,d0 ... bnz $L</code></li> </ol> <p>Start by learning about computer architecture (e.g., read something from <a href="http://en.wikipedia.org/wiki/Andrew_S._Tanenbaum" rel="noreferrer">Andrew Tanenbaum</a>), then how an OS actually loads and runs a program (Levine's <a href="http://www.iecc.com/linker/" rel="noreferrer"><em>Linkers &amp; Loaders</em></a>), then compile simple programs in C/C++ and look at the assembly language listings.</p>
10,153,087
Equivalent of ps -A | grep -c process in Windows?
<p>I am looking for an equivalent/alternative of Linux's <code>ps -A | grep -c script.php</code> for ms windows ?</p> <p>cheers, /Marcin</p>
10,153,249
2
2
null
2012-04-14 11:02:38.55 UTC
9
2016-08-26 16:01:52.373 UTC
null
null
null
null
193,400
null
1
25
windows|linux|process|grep|ps
39,428
<p>Simple commands:</p> <pre><code>tasklist | FIND "script.php" </code></pre>
9,812,237
Can you use canvas.getContext('3d')? If yes, how?
<p>I read about the canvas tag in HTML5, and always saw <code>getContext('2d')</code>.<br> The parameter is '2d', so isn't there another possibility like '3d'?<br> And, how could you use that? I tried 3D before, but didn't really understand (due to a non-explaining tutorial). Any Tutorials?</p>
9,812,379
4
2
null
2012-03-21 20:21:18.287 UTC
15
2021-06-12 16:18:53.23 UTC
2012-07-09 16:42:05.167 UTC
null
1,087,848
null
1,087,848
null
1
57
html|canvas|html5-canvas
67,808
<p>There is a 3D context for canvas, but it is not called &quot;3d&quot;, but <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API" rel="noreferrer">WebGL</a> (&quot;webgl&quot;).</p>
9,821,121
Postgresql column reference "id" is ambiguous
<p>I tried the following select:</p> <pre><code>SELECT (id,name) FROM v_groups vg inner join people2v_groups p2vg on vg.id = p2vg.v_group_id where p2vg.people_id =0; </code></pre> <p>and I get the following error column reference <code>id</code> is ambiguous.</p> <p>Thing is if I try the same <code>SELECT</code> but I only ask for <code>name</code>, and not for <code>id</code> also, it works. I'm new to this and maybe I am missing something obvious. Any suggestions?</p> <p>Thanks.</p>
9,821,137
5
2
null
2012-03-22 11:09:40.143 UTC
11
2022-05-24 10:06:25.18 UTC
2020-12-04 12:01:09.447 UTC
null
2,088,053
null
1,004,978
null
1
79
sql|postgresql|select
206,596
<p>You need the table name/alias in the <code>SELECT</code> part (maybe <code>(vg.id, name)</code>) :</p> <pre><code>SELECT (vg.id, name) FROM v_groups vg inner join people2v_groups p2vg on vg.id = p2vg.v_group_id where p2vg.people_id =0; </code></pre>
7,788,394
What's the difference between "Add JARs" and "Add External JARs" in Eclipse?
<p>In a project's Properties page, under "Java Build Path" -> "Libraries" page, I can't figure out what the difference is between the "Add JARs" and "Add External JARs" buttons.</p>
7,788,414
3
0
null
2011-10-17 00:45:33.047 UTC
9
2018-06-03 17:19:08.55 UTC
null
null
null
null
468,653
null
1
28
java|eclipse|jar
10,801
<p>Add Jar - to include jar files in you build path which are already present in your project.<br> Add External jar - used to include jar files which are 'outside' your eclipse project workspace folder. They will either be linked or copied.</p>
11,812,215
MySQL - Select most recent date out of a set of several possible timestamps?
<p>I would like to know if this is possible using a mysql query:</p> <p>I have a table called updates.</p> <p>In the updates table I have 2 columns, <code>id</code> and <code>timestamp</code>.</p> <p>I have 5 rows each with the same <code>id</code> but with different date timestamps. An example of this timestamp would be the value: <code>2012-08-04 23:14:09</code>.</p> <p>I would like to select only the most recent timestamp value out of the 5 results. This could also be explained by saying that I would like to select the value that is closest to the current date and time. How could I do this?</p>
11,812,238
2
0
null
2012-08-04 21:46:54.127 UTC
3
2013-09-30 19:53:46.253 UTC
2013-08-20 23:26:09.537 UTC
null
2,110,294
null
2,110,294
null
1
19
mysql|select|timestamp|sql-order-by
41,283
<pre><code>SELECT id, timestamp FROM updates ORDER BY timestamp DESC LIMIT 1 </code></pre>
11,549,235
Nested IF ( IF ( ... ) ELSE( .. ) ) statement in batch
<p>I'm trying to write an <code>IF ELSE</code> statement nested inside another <code>IF</code> statement. Here's what I have:</p> <pre><code>IF %dirdive%==1 ( IF DEFINED log ( ECHO %DATE%, %TIME% &gt;&gt; %log% FOR /R %root1% %%G IN (.) DO ( SET _G=%%G CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log% ) GOTO :end ) ELSE ( ECHO %DATE%, %TIME% FOR /R %root1% %%G IN (.) DO ( SET _G=%%G CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2% ) GOTO :end ) ) </code></pre> <p>When <code>log</code> isn't defined, I get: </p> <pre><code>The syntax of the command is incorrect. ECHO Wed 07/18/2012, 15:50:12.34 &gt;&gt; </code></pre> <p>Aaaand I'm at a loss. I've tried playing with the parenthesis. I've moved the last ) up onto the same line as the one before it and it doesn't work. The thing is, <em>it works fine when</em> <code>log</code> <em>is defined</em>. It seems to break right after or at <code>IF %dirdive%==1</code>, as it won't get to an echo command inserted right after that. </p>
11,549,975
5
0
null
2012-07-18 19:55:07.693 UTC
2
2014-12-26 01:47:45.3 UTC
null
null
null
null
1,454,613
null
1
20
batch-file
69,472
<p>The source of your problem is that even if a branch of an IF statement does not execute, it still must have valid syntax.</p> <p>When <code>log</code> is not defined, then the following line</p> <pre><code>ECHO %DATE%, %TIME% &gt;&gt; %log% </code></pre> <p>expands to the following when <code>log</code> is undefined </p> <pre><code>ECHO someDate, someTime &gt;&gt; </code></pre> <p>There is no file name after the redirection, which results in a syntax error.</p> <p>As long as your <code>log</code> variable is not already defined with enclosing quotes (when it is defined that is), then simply changing the line as follows should fix it:</p> <pre><code>ECHO %DATE%, %TIME% &gt;&gt; "%log%" </code></pre> <p>That line expands to the following when <code>log</code> is undefined</p> <pre><code>ECHO someDate, someTime &gt;&gt; "" </code></pre> <p>Which is valid syntax. It will fail with a "The system cannot find the path specified" error if it is executed, but it won't execute because log is undefined :-)</p> <p><strong>EDIT</strong></p> <p>Perhaps a better solution is to define a new variable that includes the redirection operator in the value if and only if <code>log</code> is defined. Then you don't even need your big IF statement and the code is easier to maintain.</p> <pre><code>SET "redirect=" IF DEFINED log SET "redirect=&gt;&gt;!log!" IF %dirdive%==1 ( ECHO %DATE%, %TIME% %redirect% FOR /R %root1% %%G IN (.) DO ( SET _G=%%G CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log% ) GOTO :end ) </code></pre> <p>Note that normal expansion <code>%redirect%</code> must be used in the ECHO statement. Delayed expansion <code>!redirect!</code> will not work because the redirection phase of the command parser occurs prior to delayed expansion.</p>
11,746,079
filter in tasklist.exe does not take wildcards?
<p>OS: Windows XP, Windows 7 64bit.</p> <p>We have some fairly hefty cmd scripts that are used for some daily build processes. These scripts spawn numerous other (windowed) processes. There is one controlling cmd script, a small simple script, which starts the main cmd script. The purpose of the small controlling script is to clean up in situations where the main script or any of its children fail. This is accomplished fairly easily: the main script and all its children have window titles which begin with a unique identifier. When the controlling script determines that the main script and all its children should have completed, it uses tasklist to find windows of any hung processes, via:</p> <p>tasklist.exe /FI "WINDOWTITLE eq UniqueIdentifier*"</p> <p>This all worked very nicely in XP. Now enter Windows7 64-bit. Here, if the main .cmd script or any other .cmd shell window attempts to sets its window title via</p> <pre><code>title UniqueIdentifier Followed By Descriptive Text </code></pre> <p>Windows7 64-bit kindly prepends other text to the title (specifically, "Administrator: " or similar). The prepended text cannot be relied upon. So now we want to use</p> <pre><code>tasklist.exe /FI "WINDOWTITLE eq *UniqueIdentifier*" </code></pre> <p>but <strong>THIS FAILS</strong> with the error message "The search filter cannot be recognized". Going the route of using our UniqueIdentifier as a post-fix does not work: the command</p> <pre><code>tasklist.exe /FI "WINDOWTITLE eq *UniqueIdentifier" </code></pre> <p>also results in the same error message. It seems that Microsoft's notion of "wildcard" in a filter does not extend beyond having a "*" as the terminal character. Ouch.</p> <p>DOES ANYONE HAVE ANY WORK-AROUNDS? Pslist does not seem to allow filtering with window title.</p>
11,747,041
5
0
null
2012-07-31 17:49:58.213 UTC
6
2021-04-12 13:42:29.657 UTC
2017-02-10 12:40:30.633 UTC
null
2,932,052
null
1,082,063
null
1
22
filter|cmd|windows-7|windows-8|tasklist
53,842
<p>You can use the /V option to include the window title in the output and then pipe the result to FIND (or FINDSTR) to filter the result.</p> <pre><code>tasklist /v | find "UniqueIdentifier" tasklist /v | findstr /c:"UniqueIdentifier" </code></pre> <p>If using FINDSTR then I recommend using the /C option so that you can include spaces in the search string.</p> <p>You might want to use the <code>/I</code> option if you need to do a case insensitive search.</p>
11,672,542
ASP.NET MVC4 Redirect to login page
<p>I'm creating a web application using ASP.NET MVC 4 and C#.</p> <p>I want all users to be logged in before using application.</p> <p>I'm using ASP.NET Membership with a custom database.</p> <p>One method is check if <code>Membership.GetUser()</code> is null or not in every function.</p> <p><strong>But isn't there any easier way than checking user login state in every function?</strong> (maybe checking in web.config, global.asax, etc...??)</p>
11,672,595
6
0
null
2012-07-26 15:18:47.82 UTC
4
2017-09-13 10:04:43.663 UTC
null
null
null
null
942,659
null
1
24
c#|asp.net-mvc|asp.net-mvc-4
43,952
<p>Sure, decorate your actions or the whole class with <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx" rel="noreferrer"><code>[Authorize]</code></a> and it will require that the user is logged in first.</p>
11,554,414
How to use LINQ to select into an object?
<p>I have data that looks like so:</p> <pre><code>UserId | SongId -------- -------- 1 1 1 4 1 12 2 95 </code></pre> <p>I also have the following class:</p> <pre><code>class SongsForUser { public int User; public List&lt;int&gt; Songs; } </code></pre> <p>What I would like to do is use LINQ to select from my data to create a collection of SongsForUser objects. Below is what I have come up with so far:</p> <pre><code>var userCombos = songs.UserSongs.Select(x =&gt; new SongsForUser() { User = x.UserId, Songs = /*What goes here?*/ }); </code></pre> <p>How would I go about populating my <code>Songs</code> List?</p> <p>So the result should be two SongsForUser objects. For user <code>1</code> it would have 3 items in the <code>Songs</code> list. For user <code>2</code> it would have 1 item in the <code>Songs</code> list.</p>
11,554,452
4
0
null
2012-07-19 05:23:35.273 UTC
2
2019-02-05 00:09:24.55 UTC
2012-07-19 05:33:38.13 UTC
null
226,897
null
226,897
null
1
30
c#|.net|linq|linq-to-entities
106,179
<pre><code>songs.UserSongs.GroupBy(x =&gt; x.User).Select(g =&gt; new SongsForUser() { User = g.Key, Songs = g.Select(s =&gt; s.SongId).ToList() }); </code></pre>
11,881,165
Slice Pandas DataFrame by Row
<p>I am working with survey data loaded from an h5-file as <code>hdf = pandas.HDFStore('Survey.h5')</code> through the pandas package. Within this <code>DataFrame</code>, all rows are the results of a single survey, whereas the columns are the answers for all questions within a single survey. </p> <p>I am aiming to reduce this dataset to a smaller <code>DataFrame</code> including only the rows with a certain depicted answer on a certain question, i.e. with all the same value in this column. I am able to determine the index values of all rows with this condition, but I can't find how to <em>delete</em> this rows or make a new df with these rows only.</p>
11,882,354
4
0
null
2012-08-09 10:15:27.97 UTC
14
2022-06-10 20:00:15.933 UTC
2017-01-05 00:19:52.367 UTC
null
2,336,654
null
698,207
null
1
49
python|pandas|slice
96,855
<pre><code>In [36]: df Out[36]: A B C D a 0 2 6 0 b 6 1 5 2 c 0 2 6 0 d 9 3 2 2 In [37]: rows Out[37]: ['a', 'c'] In [38]: df.drop(rows) Out[38]: A B C D b 6 1 5 2 d 9 3 2 2 In [39]: df[~((df.A == 0) &amp; (df.B == 2) &amp; (df.C == 6) &amp; (df.D == 0))] Out[39]: A B C D b 6 1 5 2 d 9 3 2 2 In [40]: df.ix[rows] Out[40]: A B C D a 0 2 6 0 c 0 2 6 0 In [41]: df[((df.A == 0) &amp; (df.B == 2) &amp; (df.C == 6) &amp; (df.D == 0))] Out[41]: A B C D a 0 2 6 0 c 0 2 6 0 </code></pre>
11,947,587
Is there a naming convention for git repositories?
<p>For example, I have a RESTful service called Purchase Service. Should I name my repository:</p> <ol> <li><code>purchaserestservice</code></li> <li><code>purchase-rest-service</code></li> <li><code>purchase_rest_service</code></li> <li>or something else?</li> </ol> <p>What's the convention? How about in Github? Should public repositories follow some standard?</p>
11,947,816
6
1
null
2012-08-14 07:23:42.207 UTC
100
2022-07-30 05:50:59.26 UTC
2019-10-25 15:18:41.547 UTC
null
6,214,491
null
462,408
null
1
488
git|github|naming-conventions
307,741
<p>I'd go for <code>purchase-rest-service</code>. Reasons:</p> <ol> <li><p>What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."</p></li> <li><p>"_" is harder to type than "-"</p></li> </ol>
3,374,831
In IIS, can I safely remove the X-Powered-By ASP.NET header?
<p>Will this cause any harm? Does it serve any purpose other than tell browsers you have .net installed?</p> <p>I like this article about changing the header to Pure Evil. Genius!</p> <p><a href="http://www.iishacks.com/index.php/2009/11/11/remove-x-powered-by-aspnet-http-response-header/" rel="noreferrer">http://www.iishacks.com/index.php/2009/11/11/remove-x-powered-by-aspnet-http-response-header/</a></p>
3,374,894
4
2
null
2010-07-30 19:44:28.117 UTC
4
2013-09-24 18:31:11.47 UTC
null
null
null
null
112,194
null
1
49
asp.net|iis|header
40,683
<p>This header (and a few other headers) is not required or used by modern browsers and can safely be removed from the web site configuration in IIS without consequence. Other server-side languages also tend to include a "Powered by..." header that can be safely removed. Here is another article that claims the same thing:</p> <p><a href="https://web.archive.org/web/20210506093425/http://www.4guysfromrolla.com/articles/120209-1.aspx" rel="noreferrer">https://web.archive.org/web/20210506093425/http://www.4guysfromrolla.com/articles/120209-1.aspx</a></p> <blockquote> <p>[...]</p> <p>The Server, X-Powered-By, X-AspNet-Version, and X-AspNetMvc-Version HTTP headers provide no direct benefit and unnecessarily chew up a small amount of bandwidth. Fortunately, these response headers can be removed with some configuration changes.</p> </blockquote>
3,536,674
How does Spring annotation @Autowired work?
<p>I came across an example of <code>@Autowired</code>:</p> <pre><code>public class EmpManager { @Autowired private EmpDao empDao; } </code></pre> <p>I was curious about how the <code>empDao</code> get sets since there are no setter methods and it is private.</p>
3,538,154
4
2
null
2010-08-21 06:51:09.17 UTC
17
2019-08-15 00:26:41.76 UTC
2019-08-14 22:40:58.39 UTC
null
3,657,460
null
300,535
null
1
52
spring|dependency-injection|autowired
33,870
<p>Java allows access controls on a field or method to be turned off (yes, there's a security check to pass first) via the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible%28boolean%29" rel="noreferrer"><code>AccessibleObject.setAccessible()</code> method</a> which is part of the reflection framework (both <code>Field</code> and <code>Method</code> inherit from <code>AccessibleObject</code>). Once the field can be discovered and written to, it's pretty trivial to do the rest of it; merely a <a href="http://catb.org/jargon/html/S/SMOP.html" rel="noreferrer">Simple Matter Of Programming</a>.</p>
3,298,569
Difference between MBCS and UTF-8 on Windows
<p>I am reading about the charater set and encodings on Windows. I noticed that there are two compiler flags in Visual Studio compiler (for C++) called MBCS and UNICODE. What is the difference between them ? What I am not getting is how UTF-8 is conceptually different from a MBCS encoding ? Also, I found the following quote in <a href="http://msdn.microsoft.com/en-us/library/cwe8bzh0%28VS.80%29.aspx" rel="noreferrer">MSDN</a>:</p> <blockquote> <p>Unicode is a 16-bit character encoding</p> </blockquote> <p>This negates whatever I read about the Unicode. I thought unicode can be encoded with different encodings such as UTF-8 and UTF-16. Can somebody shed some more light on this confusion?</p>
3,299,860
4
0
null
2010-07-21 11:11:12.333 UTC
28
2022-06-13 16:24:16.807 UTC
null
null
null
null
39,742
null
1
68
windows|unicode|character-encoding|mbcs
40,956
<blockquote> <p>I noticed that there are two compiler flags in Visual Studio compiler (for C++) called MBCS and UNICODE. What is the difference between them ?</p> </blockquote> <p>Many functions in the Windows API come in two versions: One that takes <code>char</code> parameters (in a locale-specific code page) and one that takes <code>wchar_t</code> parameters (in UTF-16).</p> <pre><code>int MessageBoxA(HWND hWnd, const char* lpText, const char* lpCaption, unsigned int uType); int MessageBoxW(HWND hWnd, const wchar_t* lpText, const wchar_t* lpCaption, unsigned int uType); </code></pre> <p>Each of these function pairs also has a macro without the suffix, that depends on whether the <code>UNICODE</code> macro is defined.</p> <pre><code>#ifdef UNICODE #define MessageBox MessageBoxW #else #define MessageBox MessageBoxA #endif </code></pre> <p>In order to make this work, the <code>TCHAR</code> type is defined to abstract away the character type used by the API functions.</p> <pre><code>#ifdef UNICODE typedef wchar_t TCHAR; #else typedef char TCHAR; #endif </code></pre> <p>This, however, <a href="https://stackoverflow.com/questions/234365/is-tchar-still-relevant/3002494#3002494">was a bad idea</a>. You should always explicitly specify the character type.</p> <blockquote> <p>What I am not getting is how UTF-8 is conceptually different from a MBCS encoding ?</p> </blockquote> <p>MBCS stands for &quot;multi-byte character set&quot;. For the literal minded, it seems that UTF-8 would qualify.</p> <p>But in Windows, &quot;MBCS&quot; only refers to character encodings that can be used with the &quot;A&quot; versions of the Windows API functions. This includes code pages 932 (Shift_JIS), 936 (GBK), 949 (KS_C_5601-1987), and 950 (Big5), <s>but <strong>NOT</strong> UTF-8.</s></p> <p><s>To use UTF-8, you have to convert the string to UTF-16 using <code>MultiByteToWideChar</code>, call the &quot;W&quot; version of the function, and call <code>WideCharToMultiByte</code> on the output. This is essentially what the &quot;A&quot; functions actually do, which makes me wonder <a href="https://stackoverflow.com/questions/2995111/why-isnt-utf-8-allowed-as-the-ansi-code-page">why Windows doesn't just support UTF-8</a></s>.</p> <p><s>This inability to support <a href="http://w3techs.com/technologies/overview/character_encoding/all" rel="nofollow noreferrer">the most common character encoding</a> makes the &quot;A&quot; version of the Windows API useless. Therefore, you should <strong>always use the &quot;W&quot; functions</strong></s>.</p> <p><strong>Update</strong>: As of Windows 10 build 1903 (May 2019 update), <a href="https://docs.microsoft.com/en-us/windows/apps/design/globalizing/use-utf8-code-page" rel="nofollow noreferrer">UTF-8 is now supported as an &quot;ANSI&quot; code page.</a> Thus, my original (2010) recommendation to always use &quot;W&quot; functions no longer applies, unless you need to support old versions of Windows. See <a href="http://utf8everywhere.org/" rel="nofollow noreferrer">UTF-8 Everywhere</a> for text-handling advice.</p> <blockquote> <p>Unicode is a 16-bit character encoding</p> <p>This negates whatever I read about the Unicode.</p> </blockquote> <p>MSDN is wrong. Unicode is a 21-bit coded character set that has several encodings, the most common being UTF-8, UTF-16, and UTF-32. (There are other Unicode encodings as well, such as GB18030, UTF-7, and UTF-EBCDIC.)</p> <p>Whenever Microsoft refers to &quot;Unicode&quot;, they really mean UTF-16 (or UCS-2). This is for historical reasons. Windows NT was an early adopter of Unicode, back when 16 bits was thought to be enough for everyone, and UTF-8 was only used on Plan 9. So UCS-2 <em>was</em> Unicode.</p>
3,241,033
designing database to hold different metadata information
<p>So I am trying to design a database that will allow me to connect one product with multiple categories. This part I have figured. But what I am not able to resolve is the issue of holding different type of product details. </p> <p>For example, the product could be a book (in which case i would need metadata that refers to that book like isbn, author etc) or it could be a business listing (which has different metadata) .. </p> <p>How should I tackle that?</p>
3,242,426
6
1
null
2010-07-13 20:06:13.213 UTC
28
2019-08-04 17:02:46.567 UTC
null
null
null
null
151,089
null
1
32
database-design|database|relational-database
20,961
<p>This is called the Observation Pattern.</p> <p><a href="https://i.stack.imgur.com/L8rKm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/L8rKm.png" alt="enter image description here"></a></p> <p>Three objects, for the example</p> <pre><code>Book Title = 'Gone with the Wind' Author = 'Margaret Mitchell' ISBN = '978-1416548898' Cat Name = 'Phoebe' Color = 'Gray' TailLength = 9 'inch' Beer Bottle Volume = 500 'ml' Color = 'Green' </code></pre> <p>This is how tables may look like:</p> <pre><code>Entity EntityID Name Description 1 'Book' 'To read' 2 'Cat' 'Fury cat' 3 'Beer Bottle' 'To ship beer in' </code></pre> <p>.</p> <pre><code>PropertyType PropertyTypeID Name IsTrait Description 1 'Height' 'NO' 'For anything that has height' 2 'Width' 'NO' 'For anything that has width' 3 'Volume' 'NO' 'For things that can have volume' 4 'Title' 'YES' 'Some stuff has title' 5 'Author' 'YES' 'Things can be authored' 6 'Color' 'YES' 'Color of things' 7 'ISBN' 'YES' 'Books would need this' 8 'TailLength' 'NO' 'For stuff that has long tails' 9 'Name' 'YES' 'Name of things' </code></pre> <p>.</p> <pre><code>Property PropertyID EntityID PropertyTypeID 1 1 4 -- book, title 2 1 5 -- book, author 3 1 7 -- book, isbn 4 2 9 -- cat, name 5 2 6 -- cat, color 6 2 8 -- cat, tail length 7 3 3 -- beer bottle, volume 8 3 6 -- beer bottle, color </code></pre> <p>.</p> <pre><code>Measurement PropertyID Unit Value 6 'inch' 9 -- cat, tail length 7 'ml' 500 -- beer bottle, volume </code></pre> <p>.</p> <pre><code>Trait PropertyID Value 1 'Gone with the Wind' -- book, title 2 'Margaret Mitchell' -- book, author 3 '978-1416548898' -- book, isbn 4 'Phoebe' -- cat, name 5 'Gray' -- cat, color 8 'Green' -- beer bottle, color </code></pre> <p><strong>EDIT:</strong></p> <p>Jefferey raised a valid point (see comment), so I'll expand the answer.</p> <p>The model allows for dynamic (on-fly) creation of any number of entites with any type of properties without schema changes. Hovewer, this flexibility has a price -- storing and searching is slower and more complex than in a usual table design. </p> <p>Time for an example, but first, to make things easier, I'll flatten the model into a view.</p> <pre><code>create view vModel as select e.EntityId , x.Name as PropertyName , m.Value as MeasurementValue , m.Unit , t.Value as TraitValue from Entity as e join Property as p on p.EntityID = p.EntityID join PropertyType as x on x.PropertyTypeId = p.PropertyTypeId left join Measurement as m on m.PropertyId = p.PropertyId left join Trait as t on t.PropertyId = p.PropertyId ; </code></pre> <p>To use Jefferey's example from the comment</p> <pre><code>with q_00 as ( -- all books select EntityID from vModel where PropertyName = 'object type' and TraitValue = 'book' ), q_01 as ( -- all US books select EntityID from vModel as a join q_00 as b on b.EntityID = a.EntityID where PropertyName = 'publisher country' and TraitValue = 'US' ), q_02 as ( -- all US books published in 2008 select EntityID from vModel as a join q_01 as b on b.EntityID = a.EntityID where PropertyName = 'year published' and MeasurementValue = 2008 ), q_03 as ( -- all US books published in 2008 not discontinued select EntityID from vModel as a join q_02 as b on b.EntityID = a.EntityID where PropertyName = 'is discontinued' and TraitValue = 'no' ), q_04 as ( -- all US books published in 2008 not discontinued that cost less than $50 select EntityID from vModel as a join q_03 as b on b.EntityID = a.EntityID where PropertyName = 'price' and MeasurementValue &lt; 50 and MeasurementUnit = 'USD' ) select EntityID , max(case PropertyName when 'title' than TraitValue else null end) as Title , max(case PropertyName when 'ISBN' than TraitValue else null end) as ISBN from vModel as a join q_04 as b on b.EntityID = a.EntityID group by EntityID ; </code></pre> <p>This looks complicated to write, but on a closer inspection you may notice a pattern in CTEs.</p> <p>Now suppose we have a standard fixed schema design where each object property has its own column. The query would look something like:</p> <pre><code>select EntityID, Title, ISBN from vModel WHERE ObjectType = 'book' and PublisherCountry = 'US' and YearPublished = 2008 and IsDiscontinued = 'no' and Price &lt; 50 and Currency = 'USD' ; </code></pre>
3,377,688
what do these symbolic strings mean: %02d %01d?
<p>I'm looking at a code line similar to:</p> <pre><code>sprintf(buffer,"%02d:%02d:%02d",hour,minute,second); </code></pre> <p>I think the symbolic strings refer to the number of numeric characters displayed per hour, minute etc - or something like that, I am not entirely certain. </p> <p>Normally I can figure this sort of thing out but I have been unable to find any useful reference searching "%02d %01d" on google. Anyone able to shed some light on this for me?</p>
3,377,695
6
2
null
2010-07-31 10:21:55.973 UTC
22
2016-03-14 18:25:57.37 UTC
2010-07-31 11:07:17.84 UTC
null
71,059
null
407,409
null
1
43
java|printf
141,468
<p><a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf/" rel="noreferrer">http://www.cplusplus.com/reference/clibrary/cstdio/printf/</a></p> <p>the same rules should apply to Java.</p> <p>in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9</p>
3,475,793
How to find program location in registry, if I know MSI GUID?
<p>I have installed some MSI with GUID (0733556C-37E8-4123-A801-D3E6C5151617). The program registered in the registry: HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Uninstall \ ()</p> <p>Value UninstallString = MsiExec.exe / I (0733556C-37E8-4123-A801-D3E6C5151617)</p> <p>My question is: how utility MsiExec.exe knows the name and path to the file you want to run when you remove programs? Where in the registry this information can be found?</p>
3,479,373
7
2
null
2010-08-13 10:00:20.983 UTC
1
2017-10-10 20:01:50.443 UTC
2010-08-13 17:45:26.397 UTC
null
238,639
null
419,416
null
1
10
guid|windows-installer
80,076
<p>Windows keeps Windows Installer configuration information hidden and encrypted in the Registry. It is not browseable with the human eye as other parts of the Registry are.</p> <p>To query/modify/delete this information, you'll need to use MSI functions.<br> (<a href="http://msdn.microsoft.com/en-us/library/aa369426(VS.85).aspx" rel="noreferrer">Installer Function Reference</a>)</p> <p>For your particular question, try the function <a href="http://msdn.microsoft.com/en-us/library/aa370130(v=VS.85).aspx" rel="noreferrer">MsiGetProductInfo</a>.</p>
3,387,655
Safest way to convert float to integer in python?
<p>Python's math module contain handy functions like <code>floor</code> &amp; <code>ceil</code>. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:</p> <pre><code>import math f=math.floor(2.3) </code></pre> <p>Now <code>f</code> returns:</p> <pre><code>2.0 </code></pre> <p>What is the safest way to get an integer out of this float, without running the risk of rounding errors (for example if the float is the equivalent of 1.99999) or perhaps I should use another function altogether?</p>
3,387,715
9
3
null
2010-08-02 12:20:20.617 UTC
26
2021-10-29 22:39:17.95 UTC
2014-08-05 18:21:05.243 UTC
null
270,986
null
2,892
null
1
268
python|math|integer|python-2.x
772,161
<p>All integers that can be represented by floating point numbers have an exact representation. So you can safely use <code>int</code> on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.</p> <p>That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.</p> <p>To quote from <a href="http://en.wikipedia.org/w/index.php?title=Floating_point&amp;oldid=376101741#IEEE_754:_floating_point_in_modern_computers" rel="noreferrer">Wikipedia</a>,</p> <blockquote> <p>Any integer with absolute value less than or equal to 2<sup>24</sup> can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 2<sup>53</sup> can be exactly represented in the double precision format.</p> </blockquote>
3,774,976
What are some uses for linked lists?
<p>Do linked lists have any practical uses at all. Many computer science books compare them to arrays and say the main advantage is that they are mutable. However, most languages provide mutable versions of arrays. So do linked lists have any actual uses in the real world, or are they just part of computer science theory?</p>
3,775,082
10
0
null
2010-09-23 02:16:39.537 UTC
3
2019-10-22 07:54:14.52 UTC
null
null
null
null
427,494
null
1
23
data-structures|computer-science|linked-list
47,359
<p>Linked lists have many uses. For example, implementing data structures that appear to the end user to be mutable arrays.</p> <p>If you are using a programming language that provides implementations of various collections, many of those collections will be implemented using linked lists. When programming in those languages, you won't often be implementing a linked list yourself but it might be wise to understand them so you can understand what tradeoffs the libraries you use are making. In other words, the set "just part of computer science theory" contains elements that you just need to know if you are going to write programs that just work.</p>
3,706,219
Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin
<p>For example, here is the shape of intended spiral (and each step of the iteration)</p> <pre><code> y | | 16 15 14 13 12 17 4 3 2 11 -- 18 5 0 1 10 --- x 19 6 7 8 9 20 21 22 23 24 | | </code></pre> <p>Where the lines are the x and y axes.</p> <p>Here would be the actual values the algorithm would "return" with each iteration (the coordinates of the points):</p> <pre><code>[0,0], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1], [2,-1], [2,0], [2,1], [2,2], [1,2], [0,2], [-1,2], [-2,2], [-2,1], [-2,0].. </code></pre> <p>etc.</p> <p>I've tried searching, but I'm not exactly sure what to search for exactly, and what searches I've tried have come up with dead ends.</p> <p>I'm not even sure where to start, other than something messy and inelegant and ad-hoc, like creating/coding a new spiral for each layer.</p> <p>Can anyone help me get started?</p> <p>Also, is there a way that can easily switch between clockwise and counter-clockwise (the orientation), and which direction to "start" the spiral from? (the rotation)</p> <p>Also, is there a way to do this recursively?</p> <hr> <p><strong>My application</strong></p> <p>I have a sparse grid filled with data points, and I want to add a new data point to the grid, and have it be "as close as possible" to a given other point.</p> <p>To do that, I'll call <code>grid.find_closest_available_point_to(point)</code>, which will iterate over the spiral given above and return the first position that is empty and available.</p> <p>So first, it'll check <code>point+[0,0]</code> (just for completeness's sake). Then it'll check <code>point+[1,0]</code>. Then it'll check <code>point+[1,1]</code>. Then <code>point+[0,1]</code>, etc. And return the first one for which the position in the grid is empty (or not occupied already by a data point).</p> <p>There is no upper bound to grid size.</p>
3,706,260
12
6
null
2010-09-14 04:58:36.533 UTC
9
2021-04-13 22:02:47.8 UTC
2010-09-14 06:22:20.67 UTC
null
292,731
null
292,731
null
1
35
algorithm|language-agnostic|recursion|iteration
20,168
<p>There's nothing wrong with direct, &quot;ad-hoc&quot; solution. It can be clean enough too.<br /> Just notice that spiral is built from segments. And you can get next segment from current one rotating it by 90 degrees. And each two rotations, length of segment grows by 1.</p> <p><strong>edit</strong> Illustration, those segments numbered</p> <pre><code> ... 11 10 7 7 7 7 6 10 8 3 3 2 6 10 8 4 . 1 6 10 8 4 5 5 5 10 8 9 9 9 9 9 </code></pre> <pre class="lang-java prettyprint-override"><code> // (di, dj) is a vector - direction in which we move right now int di = 1; int dj = 0; // length of current segment int segment_length = 1; // current position (i, j) and how much of current segment we passed int i = 0; int j = 0; int segment_passed = 0; for (int k = 0; k &lt; NUMBER_OF_POINTS; ++k) { // make a step, add 'direction' vector (di, dj) to current position (i, j) i += di; j += dj; ++segment_passed; System.out.println(i + &quot; &quot; + j); if (segment_passed == segment_length) { // done with current segment segment_passed = 0; // 'rotate' directions int buffer = di; di = -dj; dj = buffer; // increase segment length if necessary if (dj == 0) { ++segment_length; } } } </code></pre> <p>To change original direction, look at original values of <code>di</code> and <code>dj</code>. To switch rotation to clockwise, see how those values are modified.</p>
3,326,571
How can I view MSIL / CIL generated by C# compiler? Why is it called assembly?
<p>I'm new to .NET C# programming. I'm following few books. It is said that instead of compiling C# code directly to machine code, it is converted into an intermediate language (called MSIL aka CIL). But when I compile, I get an exe/dll file.</p> <ol> <li>Is this MSIL/CIL contained in these exe/dll files?</li> <li>I want to see that intermediate language code, just to get feel for its existence. How do I view it?</li> <li>They are calling this exe/dll file an <code>assembly</code>. Are they using this &quot;fancy word&quot; just to differentiate these from the exe/dll files that contain native/machine code?</li> </ol>
3,326,586
13
2
null
2010-07-24 19:35:15.23 UTC
46
2021-10-25 21:20:31.153 UTC
2020-12-25 11:00:27.527 UTC
null
11,650,562
walter
null
null
1
149
c#|.net|assemblies
73,139
<ol> <li>Yes it is, more exactly in the <code>.text</code> section of the <a href="http://en.wikipedia.org/wiki/Portable_Executable" rel="noreferrer">PE file</a> (portable executable = *.exe or *.dll). More information can be found <a href="http://ntcore.com/files/dotnetformat.htm" rel="noreferrer">here</a>.</li> <li>The best choice is to use <a href="https://github.com/icsharpcode/ILSpy" rel="noreferrer">ILSpy</a> (Reflector is no longer free). It's a free disassembler that can dissassemble your assembly into MSIL but also C#, VB (to some extent). The .NET Framework SDK contains ILDasm, which is the official MSIL dissasembler.</li> <li>Basically yes. An assembly is a file that contains MSIL code and corresponding metadata. This is not restricted to PE files per se, but all current CLR implementations use them.</li> </ol> <p>If I may recommend a good book on that matter too, it's Expert .NET 2.0 IL Assembler by Serge Lidin. He's the guy who designed MSIL.</p>
3,968,593
How can I set multiple CSS styles in JavaScript?
<p>I have the following JavaScript variables:</p> <pre><code>var fontsize = "12px" var left= "200px" var top= "100px" </code></pre> <p>I know that I can set them to my element iteratively like this:</p> <pre><code>document.getElementById("myElement").style.top=top document.getElementById("myElement").style.left=left </code></pre> <p>Is it possible to set them all together at once, something like this?</p> <pre><code>document.getElementById("myElement").style = allMyStyle </code></pre>
3,968,772
28
4
null
2010-10-19 13:03:00.03 UTC
110
2022-07-14 12:45:22.6 UTC
2017-08-24 11:41:26.1 UTC
null
123,671
null
265,205
null
1
277
javascript|coding-style
365,822
<p>If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make use of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration" rel="noreferrer"><code>cssText</code> property</a>:</p> <pre class="lang-js prettyprint-override"><code>document.getElementById(&quot;myElement&quot;).style.cssText = &quot;display: block; position: absolute&quot;; </code></pre> <p>You can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="noreferrer">template literals</a> for an easier, more readable multiline CSS-like syntax:</p> <pre class="lang-js prettyprint-override"><code>document.getElementById(&quot;myElement&quot;).style.cssText = ` display: block; position: absolute; `; </code></pre> <p>This is good in a sense as it avoids repainting the element every time you change a property (you change them all &quot;at once&quot; somehow).</p> <p>On the other side, you would have to build the string first.</p>
7,736,006
Vim inserting comments while copy pasting
<p>When I copy lines, like the ones below, to Vim,</p> <pre><code>" OmniCppComplete let OmniCpp_NamespaceSearch = 1 let OmniCpp_GlobalScopeSearch = 1 let OmniCpp_ShowAccess = 1 </code></pre> <p>Vim automagically adds <code>"</code> to all lines. How do I get rid of this and have it paste as it is?</p> <pre><code>In Vim 66 " OmniCppComplete 67 " let OmniCpp_NamespaceSearch = 1 68 " let OmniCpp_GlobalScopeSearch = 1 69 " let OmniCpp_ShowAccess = 1 </code></pre>
7,736,041
4
0
null
2011-10-12 06:16:22.477 UTC
17
2020-03-09 18:34:10.75 UTC
2018-07-05 08:04:29.88 UTC
null
63,550
null
97,642
null
1
58
vim
37,754
<p>Two main options:</p> <ul> <li>Put directly from the register without ever entering insert mode, using &nbsp;<code>"+p</code><br/> <ul> <li><code>"</code> means "use the following register"; </li> <li><code>+</code> refers to the clipboard, and </li> <li><code>p</code> for put! </li> </ul></li> </ul> <p>Should you be using the middle click selection paste in Linux, use <code>*</code> instead of <code>+</code> to refer to it.</p> <ul> <li>Before entering insert mode to paste, run <code>:set paste</code>. Turn it off once you leave insert mode with <code>:set nopaste</code>.</li> </ul>
8,358,265
How to update PATH variable permanently from Windows command line?
<p>If I execute <code>set PATH=%PATH%;C:\\Something\\bin</code> from the command line (<code>cmd.exe</code>) and then execute <code>echo %PATH%</code> I see this string added to the PATH. If I close and open the command line, that new string is not in PATH.</p> <p>How can I update PATH permanently from the command line for all processes in the future, not just for the current process?</p> <p>I don't want to do this by going to System Properties → Advanced → Environment variables and update PATH there.</p> <p>This command must be executed from a Java application (please see my other <a href="https://stackoverflow.com/questions/8350663/how-can-i-set-update-path-variable-from-within-java-application-on-windows">question</a>).</p>
8,358,361
7
3
null
2011-12-02 15:03:39.36 UTC
49
2019-10-30 08:42:56.12 UTC
2019-10-30 08:42:56.12 UTC
null
775,954
null
365,011
null
1
127
java|windows|cmd|path
245,764
<p>The documentation on how to do this can be found on <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682653%28v=vs.85%29.aspx" rel="noreferrer">MSDN</a>. The key extract is this:</p> <blockquote> <p>To programmatically add or modify system environment variables, add them to the <strong>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment</strong> registry key, then broadcast a <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms725497%28v=vs.85%29.aspx" rel="noreferrer"><code>WM_SETTINGCHANGE</code></a> message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.</p> </blockquote> <p>Note that your application will need elevated admin rights in order to be able to modify this key.</p> <p>You indicate in the comments that you would be happy to modify just the per-user environment. Do this by editing the values in <strong>HKEY_CURRENT_USER\Environment</strong>. As before, make sure that you broadcast a <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms725497%28v=vs.85%29.aspx" rel="noreferrer"><code>WM_SETTINGCHANGE</code></a> message.</p> <p>You should be able to do this from your Java application easily enough using the JNI registry classes.</p>