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
33,571,628
Laravel Collection get unique values from nested datastructure
<p>I want to use <a href="http://laravel.com/docs/5.1/collections#method-unique" rel="noreferrer">Laravel 5.1 Collection's Unique</a> method to filter unique IDs from nested objects.</p> <p>Given the data structure</p> <pre><code>{ "key1": [ {"id": 1}, {"id": 1} ], "key2": [ {"id": 1}, {"id": 2} ] } </code></pre> <p>I want to return the same datastructure with duplicate <code>id 1</code> removed from "key 1". </p> <p>I wanted to use <code>$unique = $collection-&gt;unique('id');</code>, but this doesn't seem to apply to a nested datastructure as I have.</p> <p>So I thought to use $collection</p> <pre><code> $input = $request-&gt;all(); $collection = collect($input); $collection-&gt;each(function($obj, $key) { //$key is "key1", "key2" //obj is the associated array of objects containing IDs })-&gt;unique('id'); </code></pre> <p>I don't quite know how to structure this.</p> <p>The result structure should be:</p> <pre><code>{ "key1": [ {"id": 1} ], "key2": [ {"id": 1}, {"id": 2} ] } </code></pre>
33,571,695
4
0
null
2015-11-06 16:46:36.543 UTC
6
2022-07-29 12:56:54.937 UTC
null
null
null
null
507,624
null
1
15
php|laravel|collections|filter|laravel-5.1
43,003
<pre><code>$collection = $collection-&gt;map(function ($array) { return collect($array)-&gt;unique('id')-&gt;all(); }); </code></pre>
19,839,172
How to read all of Inputstream in Server Socket JAVA
<p>I am using Java.net at one of my project. and I wrote a App Server that gets inputStream from a client. But some times my (buffered)InputStream can not get all of OutputStream that client sent to my server. How can I write a wait or some thing like that, that my InputStream gets all of the OutputStream of client?</p> <p>(My InputStream is not a String)</p> <pre><code>private Socket clientSocket; private ServerSocket server; private BufferedOutputStream outputS; private BufferedInputStream inputS; private InputStream inBS; private OutputStream outBS; server = new ServerSocket(30501, 100); clientSocket = server.accept(); public void getStreamFromClient() { try { outBS = clientSocket.getOutputStream(); outputS = new BufferedOutputStream( outBS); outputS.flush(); inBS = clientSocket.getInputStream(); inputS = new BufferedInputStream( inBS ); } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>Thanks.</p>
19,863,726
3
0
null
2013-11-07 15:00:31.86 UTC
13
2018-07-10 06:09:58.9 UTC
null
null
null
null
2,194,223
null
1
32
java|network-programming|inputstream|serversocket|bufferedinputstream
124,222
<p>The problem you have is related to TCP streaming nature.</p> <p>The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.</p> <p>You need to implement a loop in which you read until the whole message was received. Let me provide an example with <code>DataInputStream</code> instead of <code>BufferedinputStream</code>. Something very simple to give you just an example.</p> <p>Let's suppose you know beforehand the server is to send 100 Bytes of data.</p> <p>In client you need to write:</p> <pre><code>byte[] messageByte = new byte[1000]; boolean end = false; String dataString = ""; try { DataInputStream in = new DataInputStream(clientSocket.getInputStream()); while(!end) { int bytesRead = in.read(messageByte); dataString += new String(messageByte, 0, bytesRead); if (dataString.length == 100) { end = true; } } System.out.println("MESSAGE: " + dataString); } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.</p> <p>The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:</p> <ul> <li>1 Byte indicating type (For example, it could also be 2 or whatever). </li> <li>1 Byte (or whatever) for length of message </li> <li>N Bytes for the value (N is indicated in length).</li> </ul> <p>So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.</p> <p>This is just a suggestion of a possible protocol. You could also get rid of "Type".</p> <p>So it would be something like:</p> <pre><code>byte[] messageByte = new byte[1000]; boolean end = false; String dataString = ""; try { DataInputStream in = new DataInputStream(clientSocket.getInputStream()); int bytesRead = 0; messageByte[0] = in.readByte(); messageByte[1] = in.readByte(); int bytesToRead = messageByte[1]; while(!end) { bytesRead = in.read(messageByte); dataString += new String(messageByte, 0, bytesRead); if (dataString.length == bytesToRead ) { end = true; } } System.out.println("MESSAGE: " + dataString); } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.</p> <pre><code>import java.nio.ByteBuffer; import java.io.DataInputStream; import java.net.ServerSocket; import java.net.Socket; class Test { public static void main(String[] args) { byte[] messageByte = new byte[1000]; boolean end = false; String dataString = ""; try { Socket clientSocket; ServerSocket server; server = new ServerSocket(30501, 100); clientSocket = server.accept(); DataInputStream in = new DataInputStream(clientSocket.getInputStream()); int bytesRead = 0; messageByte[0] = in.readByte(); messageByte[1] = in.readByte(); ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2); int bytesToRead = byteBuffer.getShort(); System.out.println("About to read " + bytesToRead + " octets"); //The following code shows in detail how to read from a TCP socket while(!end) { bytesRead = in.read(messageByte); dataString += new String(messageByte, 0, bytesRead); if (dataString.length() == bytesToRead ) { end = true; } } //All the code in the loop can be replaced by these two lines //in.readFully(messageByte, 0, bytesToRead); //dataString = new String(messageByte, 0, bytesToRead); System.out.println("MESSAGE: " + dataString); } catch (Exception e) { e.printStackTrace(); } } } </code></pre>
21,808,415
How to show the image after upload in asp.net fileupload
<p>I have a fileupload control which is inside update panel. I want to display the image after upload is complete. below is my html code</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;br /&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" /&gt; &lt;br /&gt; &lt;div&gt; &lt;br /&gt; &lt;table width="50%" cellpadding="2" cellspacing="0"&gt; &lt;br /&gt; &lt;tr&gt; &lt;br /&gt; &lt;td&gt; &lt;br /&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional"&gt; &lt;ContentTemplate&gt; &lt;br /&gt; &lt;asp:FileUpload ID="FileUpload1" runat="server" /&gt;&lt;br /&gt; &lt;asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /&gt;&lt;br /&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:PostBackTrigger ControlID="btnUpload" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;br /&gt; &lt;asp:Image ID="imgViewFile" runat="server" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br /&gt; &lt;/div&gt; &lt;br /&gt; &lt;/form&gt; </code></pre> <p>Below is mycode</p> <pre><code>protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { FileUpload1.SaveAs(MapPath("~/TEST/" + FileUpload1.FileName)); imgViewFile.ImageUrl = Server.MapPath("~/TEST/" + FileUpload1.FileName); } } </code></pre> <p>But the image is not showing the file after upload. Can anybody help me on this..?</p>
21,808,436
2
0
null
2014-02-16 07:15:42.29 UTC
null
2017-09-09 04:34:44.69 UTC
2014-02-16 08:07:31.157 UTC
null
3,240,038
null
1,145,184
null
1
8
c#|asp.net|ajax|updatepanel|asyncfileupload
55,076
<p>set path as </p> <pre><code>imgViewFile.ImageUrl = "~/TEST/" + FileUpload1.FileName; </code></pre> <p>and aslo put your image inside update panel </p> <pre><code> &lt;br /&gt; &lt;asp:Image ID="imgViewFile" runat="server" /&gt; &lt;/asp:UpdatePanel&gt; </code></pre>
21,483,003
Replacing a character in Django template
<p>I want to change <code>&amp;amp;</code> to <code>and</code> in the my page's meta description.</p> <p>This is what I tried</p> <pre><code>{% if '&amp;' in dj.name %} {{ dj.name.replace('&amp;', 'and') }} {% else %} {{ dj.name }} {% endif %} </code></pre> <p>This doesn't work. It still shows as <code>&amp;amp;</code></p>
21,483,185
3
0
null
2014-01-31 14:54:43.523 UTC
4
2021-07-23 17:59:23.02 UTC
null
null
null
null
2,924,060
null
1
22
python|django|django-templates
55,127
<p><code>dj.name.replace('&amp;', 'and')</code> You can not invoke method with arguments.You need to write a custom filter.</p> <p>Official guide is here:</p> <p><a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="noreferrer">https://docs.djangoproject.com/en/dev/howto/custom-template-tags/</a></p> <p>Ok, here is my example, say, in an app named 'questions', I want to write a filter <code>to_and</code> which replaces '&amp;' to 'and' in a string.</p> <p>In /project_name/questions/templatetags, create a blank <code>__init__.py</code>, and <code>to_and.py</code> which goes like:</p> <pre><code>from django import template register = template.Library() @register.filter def to_and(value): return value.replace(&quot;&amp;&quot;,&quot;and&quot;) </code></pre> <p>In template , use:</p> <pre><code>{% load to_and %} </code></pre> <p>then you can enjoy:</p> <pre><code>{{ string|to_and }} </code></pre> <p>Note, the directory name <code>templatetags</code> and file name <code>to_and.py</code> can not be other names.</p>
58,220,995
Cannot read property 'history' of undefined (useHistory hook of React Router 5)
<p>I am using the new useHistory hook of React Router, which came out a few weeks ago. My React-router version is 5.1.2. My React is at version 16.10.1. You can find my code at the bottom.</p> <p>Yet when I import the new useHistory from react-router, I get this error:</p> <p><code>Uncaught TypeError: Cannot read property 'history' of undefined</code></p> <p>which is caused by this line in React-router</p> <pre><code>function useHistory() { if (process.env.NODE_ENV !== "production") { !(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React &gt;= 16.8 in order to use useHistory()") : invariant(false) : void 0; } return useContext(context).history; &lt;---------------- ERROR IS ON THIS LINE !!!!!!!!!!!!!!!!! } </code></pre> <p>Since it is related to useContext and perhaps a conflict with context is at fault, I tried completely removing all calls to useContext, creating the provider, etc. However, that did nothing. Tried with React v16.8; same thing. I have no idea what could be causing this, as every other feature of React router works fine.</p> <p>***Note that the same thing happens when calling the other React router hooks, such as useLocation or useParams. </p> <p>Has anyone else encountered this? Any ideas to what may cause this? Any help would be greatly appreciated, as I found nothing on the web related to this issue.</p> <pre><code>import React, {useEffect, useContext} from 'react'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import { Switch, useHistory } from 'react-router' import { useTranslation } from 'react-i18next'; import lazyLoader from 'CommonApp/components/misc/lazyLoader'; import {AppContext} from 'CommonApp/context/context'; export default function App(props) { const { i18n } = useTranslation(); const { language } = useContext(AppContext); let history = useHistory(); useEffect(() =&gt; { i18n.changeLanguage(language); }, []); return( &lt;Router&gt; &lt;Route path="/"&gt; &lt;div className={testClass}&gt;HEADER&lt;/div&gt; &lt;/Route&gt; &lt;/Router&gt; ) } </code></pre>
58,221,867
7
0
null
2019-10-03 14:12:00.583 UTC
5
2021-10-27 10:07:05.213 UTC
null
null
null
null
9,926,621
null
1
55
reactjs|react-router|react-hooks|react-router-dom|react-context
49,742
<p>It's because the <code>react-router</code> context isn't set in that component. Since its the <code>&lt;Router&gt;</code> component that sets the context you could use <code>useHistory</code> in a sub-component, but not in that one.</p> <p>Here is a very basic strategy for solving this issue:</p> <pre class="lang-js prettyprint-override"><code>const AppWrapper = () =&gt; { return ( &lt;Router&gt; // Set context &lt;App /&gt; // Now App has access to context &lt;/Router&gt; ) } const App = () =&gt; { let history = useHistory(); // Works! ... // Render routes in this component </code></pre> <p>Then just be sure to use the &quot;wrapper&quot; component instead of <code>App</code> directly.</p>
49,906,483
What does the '@' symbol do in Rust?
<p>I forgot to specify the type of a parameter and the error message was as follows:</p> <pre class="lang-none prettyprint-override"><code>error: expected one of `:` or `@`, found `)` --&gt; src/main.rs:2:12 | 2 | fn func(arg) | ^ expected one of `:` or `@` here </code></pre> <p>Which raises the question: what can you do with an <code>@</code> symbol? I don't remember reading about using the <code>@</code> symbol for anything. I also did some Googling and couldn't find anything. What does <code>@</code> do?</p>
49,906,536
1
2
null
2018-04-18 18:18:32.323 UTC
4
2022-01-04 10:32:15.053 UTC
2018-04-18 19:23:45.707 UTC
null
155,423
null
1,291,990
null
1
37
rust
6,161
<p>You can use the <code>@</code> symbol to bind a pattern to a name. As the <a href="https://doc.rust-lang.org/reference/expressions/match-expr.html" rel="noreferrer">Rust Reference demonstrates</a>:</p> <pre><code>let x = 1; match x { e @ 1 ... 5 =&gt; println!("got a range element {}", e), _ =&gt; println!("anything"), } </code></pre> <p>Assignments in Rust <a href="https://doc.rust-lang.org/book/second-edition/ch18-01-all-the-places-for-patterns.html#let-statements" rel="noreferrer">allow pattern expressions</a> (provided they are complete) and <a href="https://doc.rust-lang.org/book/second-edition/ch18-01-all-the-places-for-patterns.html#function-parameters" rel="noreferrer">argument lists are no exception</a>. In the specific case of <code>@</code>, this isn't very useful because you can already name the matched parameter. However, for completeness, here is an example which compiles:</p> <pre><code>enum MyEnum { TheOnlyCase(u8), } fn my_fn(x @ MyEnum::TheOnlyCase(_): MyEnum) {} </code></pre>
20,780,976
Obtain a link to a specific email in GMail
<p>How can I obtain a link (a URL) to a specific email in GMail? I want to click that link and open the specific email.</p>
24,463,019
9
0
null
2013-12-26 07:32:53.637 UTC
13
2022-09-08 14:13:51.077 UTC
null
null
null
null
1,632,456
null
1
45
hyperlink|gmail
45,133
<p>I don't know about a specific "email", but you can view a specific thread (which is usually one email) by clicking in the URL bar and copying that. Then, change the label to "all".</p> <p>So if the url is "<a href="https://mail.google.com/mail/u/0/#inbox/abc123def456" rel="noreferrer">https://mail.google.com/mail/u/0/#inbox/abc123def456</a>", you would change "#inbox" to say "#all" like this: "<a href="https://mail.google.com/mail/u/0/#all/abc123def456" rel="noreferrer">https://mail.google.com/mail/u/0/#all/abc123def456</a>"</p> <p>Now the link will work, even after you archive it and it's not in your inbox.</p>
18,035,719
Drawing a border on a 2d polygon with a fragment shader
<p>I have some simple polygons (fewer than 20 vertices) rendering flat on a simple xy plane, using GL_TRIANGLES and a flat color, a 2d simulation.</p> <p>I would like to add a border of variable thickness and a different color to these polygons. I have something implemented using the same vertices and glLineWidth/GL_LINE_LOOP, which works, but is another rendering pass and repeats all the vertex transforms.</p> <p>I think I should be able to do this in the fragment shader using gl_FragCoord and the vertex data and/or texture coordinates, but I'm not sure, and my naive attempts have been obviously incorrect.</p> <p>I imagine something like the following.</p> <pre><code>uniform vec2 scale; // viewport h/w uniform float line_width; uniform vec4 fill_color; uniform vec4 border_color; varying vec4 vertex; // in world coords void main() { if (distance_from_edge(gl_FragCoord, vertex, scale) &lt; line_width) { // we're close to the edge the polygon, so we're the border. gl_FragColor = border_color; } else { gl_FragColor = fill_color; } } </code></pre> <p>The part I'm trying to figure out is the distance_from_edge function - how can that be calculated? Is using gl_FragCoord the wrong approach - should I be using some kind of texture mapping?</p> <p>As an experiment I tried converting the vertex to pixel space with the scale, and then calculate the distance between that and gl_FragCoord in pixels, but that give strange results that I didn't really understand. Plus I need the distance to the <em>edge</em>, not the vertex, but I'm not sure how to get that. </p> <p>Any ideas?</p> <p>EDIT: based on Nicol's response, my question becomes:</p> <p>Assuming I have a triangle with 3 corner vertices marked as edge vertices, and one vertex in the middle marked as not edge (so rendered with 3 triangles in total), then how do I interpolate in the fragment shader to draw a border of a given thickness? I am assuming I pass the edge flag to the fragment shader, as well as the desired line thickness, and it does some interpolation calculation to figure out the distance between the edge and not edge vertices, and thresholds the color as border/fill as appropriate?</p>
18,068,177
1
2
null
2013-08-03 17:59:48.487 UTC
17
2019-08-05 09:24:18.64 UTC
2017-01-19 16:24:59.807 UTC
null
815,724
null
934,540
null
1
26
opengl-es|opengl-es-2.0|glsl|fragment-shader|vertex-shader
21,250
<p>All you need are the barycentric coordinates, since you are dealing with triangles. Assign each vertex of the triangle an identity, and then use the hardware's built-in interpolation between the vertex and fragment stages to figure out the relative distance from each of the vertices in your fragment shader.</p> <p>You can think of the barycentric coordinates for each vertex as the distance from the opposite edge. In the diagram below, vertex P0's opposite edge is e1, and its distance is represented by h1; its barycentric coordinate is <code>&lt;0.0, h1, 0.0&gt;</code>. GPUs may use this coordinate space internally to interpolate vertex attributes for triangles when fragments are generated during rasterization, it makes quick work of weighting per-vertex properties based on location within a triangle.</p> <p><img src="https://i.stack.imgur.com/5EAgs.png" alt="Diagram illustrating the calculation of distance from each edge"></p> <p>Below are two tutorials that explain how to do this, typically this is used for rendering a wireframe overlay so you might have better luck searching for that. For your purposes, since this is effectively a specialization of wireframe rendering (with the addition that you want to throw out lines that do not belong to exterior polygon edges), you will need to identify edge vertices and perform additional processing.</p> <p>For instance, if a vertex is not part of an exterior edge, then you will want to assign it a barycentric coordinate of something like &lt;1,100,0> and the connected vertex &lt;0,100,1> and the interior edge will be ignored (assuming it is an edge opposite the vertex designated &lt;0,1,0>, as seen in the diagram below). The idea is that you never want a point along this edge to interpolate anywhere near 0.0 (or whatever your threshold you use for shading a fragment as part of the border), making it extremely distant from the center of the triangle in the direction of the opposite vertex will solve this.</p> <p><img src="https://i.stack.imgur.com/oK4pu.png" alt="Diagram showing how to exclude interior edges"></p> <p><b>Without Geometry Shaders (OpenGL ES friendly):</b></p> <p>Here's a link explaining how to do this, if you are able to modify your vertex data to hold the barycentric coordinates. It has higher storage and pre-processing requirements (in particular, sharing of vertices between adjacent edges may no longer be possible since you need each triangle to consist of three vertices that each have a different input barycentric coordinate - which is why geometry shaders are a desirable solution). However, it will run on a lot more OpenGL ES class hardware than more general solutions that require geometry shaders.</p> <p><a href="https://web.archive.org/web/20190220052115/http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/" rel="noreferrer">https://web.archive.org/web/20190220052115/http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/</a></p> <p><b>With Geometry Shaders (<i>Not</i> OpenGL ES friendly):</b></p> <p>Alternatively, you can use a geometry shader to compute the barycentric coordinates for each triangle at render-time as seen in this tutorial. Chances are in OpenGL ES you will not have access to geometry shaders, so this can probably be ignored.</p> <p><a href="http://strattonbrazil.blogspot.com/2011/09/single-pass-wireframe-rendering_10.html" rel="noreferrer">http://strattonbrazil.blogspot.com/2011/09/single-pass-wireframe-rendering_10.html</a> <a href="http://strattonbrazil.blogspot.com/2011/09/single-pass-wireframe-rendering_11.html" rel="noreferrer">http://strattonbrazil.blogspot.com/2011/09/single-pass-wireframe-rendering_11.html</a></p> <p>The theoretical basis for this solution can be found here (courtesy of the Internet Archive Wayback Machine):</p> <p><a href="http://web.archive.org/web/" rel="noreferrer">http://web.archive.org/web/</a>*/<a href="http://cgg-journal.com/2008-2/06/index.html" rel="noreferrer">http://cgg-journal.com/2008-2/06/index.html</a></p>
27,529,191
How to update code from Git to a Docker container
<p>I have a Docker file trying to deploy Django code to a container</p> <pre><code>FROM ubuntu:latest MAINTAINER { myname } #RUN echo "deb http://archive.ubuntu.com/ubuntu/ $(lsb_release -sc) main universe" &gt;&gt; /etc/apt/sou$ RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get install -y tar git curl dialog wget net-tools nano buil$ RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python python-dev python-distribute python-p$ RUN mkdir /opt/app WORKDIR /opt/app #Pull Code RUN git clone [email protected]/{user}/{repo} RUN pip install -r website/requirements.txt #EXPOSE = ["8000"] CMD python website/manage.py runserver 0.0.0.0:8000 </code></pre> <p>And then I build my code as <code>docker build -t dockerhubaccount/demo:v1 .</code>, and this pulls my code from Bitbucket to the container. I run it as <code>docker run -p 8000:8080 -td felixcheruiyot/demo:v1</code> and things appear to work fine.</p> <p>Now I want to update the code i.e since I used <code>git clone ...</code>, I have this confusion:</p> <ul> <li>How can I update my code when I have new commits and upon Docker containers build it ships with the new code (note: when I run build it does not fetch it because of cache).</li> <li>What is the best workflow for this kind of approach?</li> </ul>
27,530,136
5
0
null
2014-12-17 15:35:43.42 UTC
17
2017-11-29 22:42:08.173 UTC
2017-11-29 22:38:07.28 UTC
null
63,550
null
1,008,459
null
1
31
python|git|deployment|continuous-integration|docker
22,923
<p>There are a couple of approaches you can use.</p> <ol> <li>You can use <code>docker build --no-cache</code> to avoid using the cache of the Git clone.</li> <li>The startup command calls <code>git pull</code>. So instead of running <code>python manage.py</code>, you'd have something like <code>CMD cd /repo &amp;&amp; git pull &amp;&amp; python manage.py</code> or use a start script if things are more complex.</li> </ol> <p>I tend to prefer 2. You can also run a cron job to update the code in your container, but that's a little more work and goes somewhat against the Docker philosophy.</p>
27,797,351
Class has no initializers Swift
<p>I have a problem with Swift class. I have a swift file for UITableViewController class and UITableViewCell class. My problem is the UITableViewCell class, and outlets. This class has an error <strong>Class "HomeCell" has no initializers</strong>, and I don't understand this problem.</p> <p>Thanks for your responses.</p> <pre><code>import Foundation import UIKit class HomeTable: UITableViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableViex: UITableView! var items: [(String, String, String)] = [ ("Test", "123", "1.jpeg"), ("Test2", "236", "2.jpeg"), ("Test3", "678", "3.jpeg") ] override func viewDidLoad() { super.viewDidLoad() var nib = UINib(nibName: "HomeCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "bookCell") } // Number row override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return self.items.count } // Style Cell override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("bookCell") as UITableViewCell // Style here return cell } // Select row override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Select } } // PROBLEM HERE class HomeCell : UITableViewCell { @IBOutlet var imgBook: UIImageView @IBOutlet var titleBook: UILabel @IBOutlet var pageBook: UILabel func loadItem(#title: String, page: String, image:String) { titleBook.text = title pageBook.text = page imgBook.image = UIImage(named: image) } } </code></pre>
27,797,738
7
1
null
2015-01-06 11:07:22.783 UTC
24
2019-09-30 19:01:07.813 UTC
null
null
null
null
2,223,952
null
1
185
ios|uitableview|swift
144,641
<p>You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent &lt;-> child of the UI components in this case) during the initialization phase.</p> <pre><code>@IBOutlet var imgBook: UIImageView! @IBOutlet var titleBook: UILabel! @IBOutlet var pageBook: UILabel! </code></pre> <p>Read this <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_98">doc</a>, they explain it all nicely.</p>
34,652,036
Awake() and Start()
<p>I see that we can initialize Variable in <code>Awake()</code> or <code>Start()</code> and <code>Awake()</code> will be called before <code>Start()</code>.</p> <p>When should we initialize in <code>Awake</code> and <code>Start</code> to have the best performance?</p>
34,652,545
5
0
null
2016-01-07 09:52:17.77 UTC
10
2022-04-25 21:37:49.02 UTC
2017-08-24 18:03:59.013 UTC
null
494,143
null
5,217,524
null
1
83
unity3d
71,056
<p>Usually <code>Awake()</code> is used to initialize if certain values or script are dependent on each other and would cause errors if one of them is initialized too late (awake runs before the game starts). Awake is also called only once for every script instance.</p> <p>Let me quote the Documentation:</p> <blockquote> <p>[...] Awake is called after all objects are initialized so you can safely speak to other objects or query them using eg. GameObject.FindWithTag. Each GameObject's Awake is called in a random order between objects. Because of this, you should use Awake to set up references between scripts, and use Start() to pass any information back and forth. Awake is always called before any Start functions. This allows you to order initialization of scripts. Awake can not act as a coroutine.</p> </blockquote> <p>and about <code>Start()</code>:</p> <blockquote> <p>Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.</p> <p>Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. <strong>Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.</strong></p> </blockquote> <p>Where the last part makes one big difference</p> <p>To get to your question:</p> <p>If the script is <strong>NOT</strong> enabled at the beginning of your game, and you don't need the variables to be initialized, <strong><em>start would be saving performance</em></strong> as awake() would be called regardless...<br> every variable would be initialized at the very beginning. At least that's the logical assumption I make.</p>
34,490,218
How to make a Windows Notification in Java
<p>In Windows 10 there is a notification that opens in the bottom right of the screen and I find them quite useful.</p> <p>Is there is any way to create Windows notifications in Java? This is what they look like:</p> <p><a href="https://i.stack.imgur.com/XsNPo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XsNPo.png" alt="sample of windows notification desired"></a></p>
34,490,485
2
0
null
2015-12-28 08:40:10.833 UTC
30
2020-07-12 13:03:06.297 UTC
2017-10-11 01:44:17.97 UTC
null
3,357,935
null
5,552,231
null
1
43
java|notifications
45,543
<p>I can successfully produce this result using this very simple sample code:</p> <p><a href="https://i.stack.imgur.com/zp6zF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zp6zF.png" alt="screenshot"></a></p> <pre><code>import java.awt.*; import java.awt.TrayIcon.MessageType; public class TrayIconDemo { public static void main(String[] args) throws AWTException { if (SystemTray.isSupported()) { TrayIconDemo td = new TrayIconDemo(); td.displayTray(); } else { System.err.println("System tray not supported!"); } } public void displayTray() throws AWTException { //Obtain only one instance of the SystemTray object SystemTray tray = SystemTray.getSystemTray(); //If the icon is a file Image image = Toolkit.getDefaultToolkit().createImage("icon.png"); //Alternative (if the icon is on the classpath): //Image image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("icon.png")); TrayIcon trayIcon = new TrayIcon(image, "Tray Demo"); //Let the system resize the image if needed trayIcon.setImageAutoSize(true); //Set tooltip text for the tray icon trayIcon.setToolTip("System tray icon demo"); tray.add(trayIcon); trayIcon.displayMessage("Hello, World", "notification demo", MessageType.INFO); } } </code></pre>
24,724,866
Android Eclipse - Cannot see annotation processing option
<p>I am unable to fine the option to set annotation processing in my Eclipse preferences. <img src="https://i.stack.imgur.com/cNzf4.png" alt="enter image description here"></p> <p>Not sure since when am I getting this problem but surely it has started to occur after I updated eclipse last. I also tried pasting the annotations.jar file in tools/support folder but to no good. </p> <p>Kindly help.</p> <p>TIA</p>
25,364,253
5
0
null
2014-07-13 16:33:21.96 UTC
9
2014-08-18 13:15:02.313 UTC
null
null
null
null
610,837
null
1
12
java|android|eclipse|android-annotations
4,479
<p>Installing </p> <blockquote> <p>Programming Languages > Eclipse Java Development Tools</p> </blockquote> <p>may enable it again.</p> <p><img src="https://i.stack.imgur.com/ewIn8.png" alt="enter image description here"></p>
50,506,470
How to pass an object as props with vue router?
<p>I have the following fiddle <a href="https://jsfiddle.net/91vLms06/1/" rel="noreferrer">https://jsfiddle.net/91vLms06/1/</a></p> <pre><code>const CreateComponent = Vue.component('create', { props: ['user', 'otherProp'], template: '&lt;div&gt;User data: {{user}}; other prop: {{otherProp}}&lt;/div&gt;' }); const ListComponent = Vue.component('List', { template: '&lt;div&gt;Listing&lt;/div&gt;' }); const app = new Vue({ el: '#app', router: new VueRouter(), created: function () { const self = this; // ajax request returning the user const userData = {'name': 'username'} self.$router.addRoutes([ { path: '/create', name: 'create', component: CreateComponent, props: { user: userData }}, { path: '/list', name: 'list', component: ListComponent }, { path: '*', redirect: '/list'} ]); self.$router.push({name: 'create'}); // ok result: User data: { "name": "username" }; other prop: self.$router.push({name: 'list'}); // ok result: Listing // first attempt self.$router.push({name: 'create', props: {otherProp: {"a":"b"}}}) // not ok result: User data: { "name": "username" }; other prop: self.$router.push({name: 'list'}); // ok result: Listing // second attempt self.$router.push({name: 'create', params: {otherProp: {"a":"b"}}}) //not ok result: User data: { "name": "username" }; other prop: } }); </code></pre> <p>As you can see first I am passing to <code>CreateComponent</code> the <code>user</code> just when I initialize the route.</p> <p>Later I need to pass another property <code>otherProp</code> and still keep the <code>user</code> parameter. When I try to do this the object I send is not passed to the component.</p> <p>How can I pass the <code>otherProp</code> and still keep the <code>user</code>?</p> <p>The real purpose of the <code>otherProp</code> is to fill a form with the data from it. In the listing part I have the object and when I click the "edit" button I want to populate the form with the data that comes from the listing.</p>
50,507,329
2
0
null
2018-05-24 10:04:10.56 UTC
8
2022-07-27 10:16:45.65 UTC
2020-04-02 16:14:57.89 UTC
null
3,995,261
null
869,793
null
1
34
javascript|vue.js|vuejs2|vue-router
53,449
<p>It can work by using <a href="https://router.vuejs.org/en/essentials/passing-props.html" rel="nofollow noreferrer">props's Function mode</a> and <code>params</code></p> <p>Vue 2 demo: <a href="https://jsfiddle.net/hacg6ody/" rel="nofollow noreferrer">https://jsfiddle.net/hacg6ody/</a></p> <p>when adding routes, use <a href="https://router.vuejs.org/en/essentials/passing-props.html" rel="nofollow noreferrer">props's Function mode</a> so that it has a default property <code>user</code> and it will add <code>route.params</code> as props.</p> <pre><code>{ path: '/create', name: 'create', component: CreateComponent, props: (route) =&gt; ({ user: userData, ...route.params }) } </code></pre> <p>params passed in push will automatically be added to props.</p> <pre><code>self.$router.push({ name: 'create', params: { otherProp: { &quot;a&quot;: &quot;b&quot; } } }) </code></pre>
22,111,338
Tomcat 7 startup.bat exception
<p>When i run startup.bat file of Tomcat 7 i m getting the following error. </p> <blockquote> <p>INFO: Initializing ProtocolHandler ["http-apr-8080"] Mar 01, 2014 12:18:22 PM org.apache.coyote.AbstractProtocol init SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-apr-8080"] java.lang.Exception: Socket bind failed: [730013] An attempt was made to access a socket in a way forbidden by its access permissions.<br> at org.apache.tomcat.util.net.AprEndpoint.bind(AprEndpoint.java:430) at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640) at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434) at org.apache.catalina.connector.Connector.initInternal(Connector.java:981) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:814) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) at org.apache.catalina.startup.Catalina.load(Catalina.java:639) at org.apache.catalina.startup.Catalina.load(Catalina.java:664) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)<br> Mar 01, 2014 12:18:22 PM org.apache.catalina.core.StandardService initInternal SEVERE: Failed to initialize connector [Connector[HTTP/1.1-8080]] org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-8080]] at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106) at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:814) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) at org.apache.catalina.startup.Catalina.load(Catalina.java:639) at org.apache.catalina.startup.Catalina.load(Catalina.java:664) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455) Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed at org.apache.catalina.connector.Connector.initInternal(Connector.java:983) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102) ... 12 more Caused by: java.lang.Exception: Socket bind failed: [730013] An attempt was made to access a socket in a way forbidden by its access permissions.<br> at org.apache.tomcat.util.net.AprEndpoint.bind(AprEndpoint.java:430) at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640) at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434) at org.apache.catalina.connector.Connector.initInternal(Connector.java:981) ... 13 more</p> </blockquote> <p>When I run the url <code>http://localhost:8080</code>, I get the prompt for authentication. If i give default username and password as 'tomcat', it prompts me again without successful login.<br> Here is my <strong>tomcat-users.xml</strong> file </p> <pre><code> &lt;role rolename="tomcat"/&gt; &lt;role rolename="manager-gui"/&gt; &lt;user username="tomcat" password="tomcat" roles="tomcat,manager-gui"/&gt; </code></pre> <p><strong>Can anybody help me please?</strong></p>
22,115,305
5
0
null
2014-03-01 07:09:43.197 UTC
4
2016-09-27 17:15:18.183 UTC
2016-02-19 11:07:22.35 UTC
null
3,772,197
null
1,866,883
null
1
11
tomcat7
48,643
<p>You may have another instance of Tomcat already running in the background and using port 8080. Try shutting it down with <code>shutdown.bat</code>, or look for a java process in the Windows Task Manager. You can also reboot if you really want to be sure that there's no other instance running.</p>
37,276,932
What the difference between [FromRoute] and [FromBody] in a Web API?
<p>What the difference between <code>[FromRoute]</code> and <code>[FromBody]</code> in a Web API?</p> <pre><code>[Route("api/Settings")] public class BandwidthController : Controller { // GET: api/Settings [HttpGet] public IEnumerable&lt;Setting&gt; GetSettings() { return _settingRespository.GetAllSettings(); } // GET: api/Settings/1 [HttpGet("{facilityId}", Name = "GetTotalBandwidth")] public IActionResult GetTotalBandwidth([FromRoute] int facilityId) { if (!ModelState.IsValid) { return HttpBadRequest(ModelState); } } } </code></pre> <p>Also for <code>PUT</code>:</p> <pre><code>// PUT: api/Setting/163/10 [HttpPut] public void UpdateBandwidthChangeHangup([FromRoute] int facilityId, int bandwidthChange) { _settingRespository.UpdateBandwidthHangup(facilityId, bandwidthChange); } </code></pre> <p>Can I use <code>[FromBody]</code>?</p>
37,277,419
1
0
null
2016-05-17 12:59:21.913 UTC
9
2019-10-29 15:28:09.877 UTC
2019-10-29 15:28:09.877 UTC
user1108948
7,680,801
user1108948
null
null
1
34
asp.net|asp.net-web-api
62,103
<blockquote> <h3><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.frombodyattribute?view=aspnetcore-2.0" rel="noreferrer">FromBody</a></h3> <p>Specifies that a parameter or property should be bound using the request body.</p> </blockquote> <p>When you use <code>FromBody</code> attribute you are specifying that the data is coming from the body of the request body and not from the request URL/URI. You cannot use this attribute with <code>HttpGet</code> requests, only with PUT,POST,and Delete requests. Also you can only use one <code>FromBody</code> attribute tag per action method in Web API (if this has changed in mvc core I could not find anything to support that).</p> <blockquote> <h3><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromrouteattribute?view=aspnetcore-2.0" rel="noreferrer">FromRouteAttribute</a></h3> <p>Summary: Specifies that a parameter or property should be bound using route-data from the current request.</p> </blockquote> <p>Essentially it <code>FromRoute</code> will look at your route parameters and extract / bind the data based on that. As the route, when called externally, is usually based on the URL. In previous version(s) of web api this is comparable to <code>FromUri</code>.</p> <pre><code>[HttpGet(&quot;{facilityId}&quot;, Name = &quot;GetTotalBandwidth&quot;)] public IActionResult GetTotalBandwidth([FromRoute] int facilityId) </code></pre> <p>So this would try to bind <code>facilityId</code> based on the route parameter with the same name.</p> <pre><code>Complete route definition: /api/Settings/GetTotalBandwidth/{facilityId} Complete received url: /api/Settings/GetTotalBandwidth/100 </code></pre> <hr /> <h3>Edit</h3> <p>Based on your last question, here is the corresponding code assuming you want 163 to be bound to facilityId and 10 to bandwidthChange parameters.</p> <pre><code>// PUT: api/Setting/163/10 [HttpPut(&quot;{facilityId}/{bandwidthChange}&quot;)] // constructor takes a template as parameter public void UpdateBandwidthChangeHangup([FromRoute] int facilityId, [FromRoute] int bandwidthChange) // use multiple FromRoute attributes, one for each parameter you are expecting to be bound from the routing data { _settingRespository.UpdateBandwidthHangup(facilityId, bandwidthChange); } </code></pre> <p>If you had a complex object in one of the parameters and you wanted to send this as the body of the Http Request then you could use <code>FromBody</code> instead of <code>FromRoute</code> on that parameter. Here is an example taken from the <a href="https://docs.asp.net/en/latest/tutorials/first-web-api.html" rel="noreferrer">Building Your First Web API with ASP.NET Core MVC</a></p> <pre><code>[HttpPut(&quot;{id}&quot;)] public IActionResult Update([FromRoute] string id, [FromBody] TodoItem item); </code></pre> <p>There are also other options in MVC Core like <code>FromHeader</code> and <code>FromForm</code> and <code>FromQuery</code>.</p>
41,604,162
Eslint throws is assigned a value but never used , webpack module
<p>I am importing a script in webpack, it all works but eslint is throwing the error <code>'modal is assigned a value but never used'</code>. Do have to declare the const as a global or export the module to fix the error ? </p> <p>modules.vanillaModal.js :</p> <pre><code>import VanillaModal from 'vanilla-modal'; // Create instance const modal = new VanillaModal({ modal: '.c-modal', modalInner: '.js-modal__inner', modalContent: '.js-modal__content', open: '[rel="js-modal:open"]', close: '[rel="js-modal:close"]', class: 'js-modal--visible', loadClass: 'js-modal--loaded', }); </code></pre> <p>and my webpack entry index.js:</p> <pre><code>require('./modules.vanillaModal.js'); </code></pre>
41,604,210
4
0
null
2017-01-12 02:29:25.73 UTC
null
2022-05-14 09:14:08.333 UTC
null
null
null
null
5,597,188
null
1
10
javascript|webpack|eslint
50,422
<p>This is an eslint rule <a href="http://eslint.org/docs/rules/no-unused-vars" rel="noreferrer">http://eslint.org/docs/rules/no-unused-vars</a>. It prevents you from creating variables that you never use, which causes code clutter or could mean you're using variables that aren't what you think they are.</p> <p>If you're using a poorly designed library where the class constructor has side effects (which it isn't supposed to), and you don't need to do anything with the returned value from the class, I would disable that specific eslint rule for the create line with <a href="https://eslint.org/docs/2.13.1/user-guide/configuring#disabling-rules-with-inline-comments-1" rel="noreferrer">eslint disable comments</a>:</p> <pre><code>// eslint-disable-next-line no-unused-vars const modal = new VanillaModal({ modal: '.c-modal', modalInner: '.js-modal__inner', modalContent: '.js-modal__content', open: '[rel=&quot;js-modal:open&quot;]', close: '[rel=&quot;js-modal:close&quot;]', class: 'js-modal--visible', loadClass: 'js-modal--loaded', }); </code></pre> <p>You can also wrap any block of code with eslint specific comments to disable a rule for that block:</p> <pre><code>/* eslint-disable no-unused-vars */ const modal = new VanillaModal({ ... }); /* eslint-enable no-unused-vars */ </code></pre>
6,031,431
GetProcAddress function in C++
<p>Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do? I use this function ( double GetNumber(double x) ) in "MYDLL.dll"</p> <p>Here is a code which I used:</p> <pre><code>typedef double (*LPGETNUMBER)(double Nbr); HINSTANCE hDLL = NULL; LPGETNUMBER lpGetNumber; hDLL = LoadLibrary(L"MYDLL.DLL"); lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber"); </code></pre>
6,031,589
3
10
null
2011-05-17 13:24:40.757 UTC
9
2017-06-06 10:04:22.087 UTC
2013-11-24 17:38:19.807 UTC
null
759,866
null
748,188
null
1
23
c++|dll|loadlibrary|getprocaddress
70,779
<p>Checking return codes and calling <code>GetLastError()</code> will set you free. You should be checking return codes twice here. You are actually checking return codes zero times.</p> <pre><code>hDLL = LoadLibrary(L"MYDLL.DLL"); </code></pre> <p>Check <code>hDLL</code>. Is it NULL? If so, call <code>GetLastError()</code> to find out why. It may be as simple as "File Not Found".</p> <pre><code>lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber"); </code></pre> <p>If <code>lpGetNumber</code> is NULL, call <code>GetLastError()</code>. It will tell you why the proc address could not be found. There are a few likely scenarios:</p> <ol> <li>There is no <em>exported</em> function named <code>GetNumber</code></li> <li>There is an exported function named <code>GetNumber</code>, but it is not marked <code>extern "c"</code>, resulting in <a href="http://en.wikipedia.org/wiki/Name_mangling" rel="noreferrer">name mangling</a>.</li> <li><code>hDLL</code> isn't a valid library handle.</li> </ol> <p>If it turns out to be #1 above, you need to export the functions by decorating the declaration with <code>__declspec(dllexport)</code> like this:</p> <h2>MyFile.h</h2> <pre><code>__declspec(dllexport) int GetNumber(); </code></pre> <p>If it turns out to be #2 above, you need to do this:</p> <pre><code>extern "C" { __declspec(dllexport) int GetNumber(); }; </code></pre>
5,751,918
ORMLite for Android: Bind DAO with Roboguice
<p>I'm just trying to setup my Android Project with ORMLite. I'm using Roboguice for DI. Now my question is, whether anyone here can help getting those working together.</p> <p>I've setup my helper class extending <code>OrmLiteSqliteOpenHelper</code>. Now I'm wondering how to inject the correct DAO class.</p> <p>A general best practice would be fantastic. Since using <code>OrmLiteBaseActivity</code> shouldn't really apply, since that should be handled by Roboguice. The question is just: How?</p> <p>I'd very much appreciate any help, your experience, best practice etc.</p>
5,781,121
4
1
null
2011-04-22 03:08:41.087 UTC
14
2012-10-28 11:19:23.667 UTC
2012-06-07 17:22:35.843 UTC
null
403,455
null
465,509
null
1
8
android|ormlite|roboguice
4,819
<p>If you're extending from OrmLiteBaseActivity, you won't be able to extend from <a href="http://code.google.com/p/roboguice/source/browse/roboguice/src/main/java/roboguice/activity/RoboActivity.java?r=roboguice-1.1-branch#74" rel="noreferrer">RoboActivity</a>. That's fine, just call the following (assuming roboguice 1.1) to perform injection on your non-roboactivity activity:</p> <pre><code>((InjectorProvider)getApplicationContext()).getInjector().injectMembers(this) </code></pre> <p>Once you have that, you can perform injection of your dao objects. </p> <p>To inject your DAOs, I suggest you follow the pattern established by SystemServiceProvider (<a href="http://code.google.com/p/roboguice/source/browse/roboguice/src/main/java/roboguice/inject/SystemServiceProvider.java?r=roboguice-1.1-branch" rel="noreferrer">class</a> and <a href="http://code.google.com/p/roboguice/source/browse/roboguice/src/main/java/roboguice/config/RoboModule.java?r=roboguice-1.1-branch#90" rel="noreferrer">bindings</a>). So implement a DaoProvider like the following:</p> <pre><code>class DaoProvider&lt;T&gt; implements Provider&lt;T&gt; { protected ConnectionSource conn; protected Class&lt;T&gt; clazz; public DaoProvider( ConnectionSource conn, Class&lt;T&gt; clazz ) { this.conn = conn; this.clazz = clazz; } @Override public T get() { return DaoManager.createDao( conn, clazz ); } } </code></pre> <p>Supply the bindings. You'll need to do one for each DAO type you want to inject:</p> <pre><code>bind(MyDaoObjectType.class).toProvider( new DaoProvider&lt;MyDaoObjectType&gt;(conn,MyDaoObjectType.class)); </code></pre> <p>Then you can inject it into your activity or anywhere else:</p> <pre><code>@Inject MyDaoObjectType myDaoObjectType; </code></pre>
6,169,324
partition string in python and get value of last segment after colon
<p>I need to get the value after the last colon in this example 1234567</p> <pre><code>client:user:username:type:1234567 </code></pre> <p>I don't need anything else from the string just the last id value.</p>
6,169,363
4
0
null
2011-05-29 17:43:43.75 UTC
9
2019-09-26 17:17:53.093 UTC
2015-11-20 19:41:58.267 UTC
null
541,136
null
664,546
null
1
49
python|string
85,486
<pre><code>result = mystring.rpartition(':')[2] </code></pre> <p>If you string does not have any <code>:</code>, the result will contain the original string.</p> <p>An alternative that is supposed to be a little bit slower is:</p> <pre><code>result = mystring.split(':')[-1] </code></pre>
5,637,124
Tab completion in Python's raw_input()
<p>i know i can do this to get the effect of tab completion in python sure. </p> <pre><code>import readline COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1 readline.parse_and_bind("tab: complete") readline.set_completer(complete) raw_input('Enter section name: ') </code></pre> <p>I am now interested in doing tab completion with directories. (/home/user/doc >tab)</p> <p>How would i go about doing such a task?</p>
5,638,688
4
0
null
2011-04-12 14:44:09.67 UTC
35
2022-03-03 05:48:12.52 UTC
2011-04-12 16:10:50.07 UTC
null
525,576
null
525,576
null
1
56
python|raw-input
29,027
<p>Here is a quick example of how to perform incremental completion of file system paths. I've modified your example, organizing it into a class where methods named <code>complete_[name]</code> indicate top-level commands.</p> <p>I've switched the completion function to use the internal readline buffer to determine the state of the overall completion, which makes the state logic a bit simpler. The path completion is in the <code>_complete_path(path)</code> method, and I've hooked up the <strong>extra</strong> command to perform path completions on its arguments. </p> <p>I'm sure the code could be further simplified but it should provide you a decent starting point:</p> <pre><code>import os import re import readline COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] RE_SPACE = re.compile('.*\s+$', re.M) class Completer(object): def _listdir(self, root): "List directory 'root' appending the path separator to subdirs." res = [] for name in os.listdir(root): path = os.path.join(root, name) if os.path.isdir(path): name += os.sep res.append(name) return res def _complete_path(self, path=None): "Perform completion of filesystem path." if not path: return self._listdir('.') dirname, rest = os.path.split(path) tmp = dirname if dirname else '.' res = [os.path.join(dirname, p) for p in self._listdir(tmp) if p.startswith(rest)] # more than one match, or single match which does not exist (typo) if len(res) &gt; 1 or not os.path.exists(path): return res # resolved to a single directory, so return list of files below it if os.path.isdir(path): return [os.path.join(path, p) for p in self._listdir(path)] # exact file match terminates this completion return [path + ' '] def complete_extra(self, args): "Completions for the 'extra' command." if not args: return self._complete_path('.') # treat the last arg as a path and complete it return self._complete_path(args[-1]) def complete(self, text, state): "Generic readline completion entry point." buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() # show all commands if not line: return [c + ' ' for c in COMMANDS][state] # account for last argument ending in a space if RE_SPACE.match(buffer): line.append('') # resolve command to the implementation function cmd = line[0].strip() if cmd in COMMANDS: impl = getattr(self, 'complete_%s' % cmd) args = line[1:] if args: return (impl(args) + [None])[state] return [cmd + ' '][state] results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None] return results[state] comp = Completer() # we want to treat '/' as part of a word, so override the delimiters readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) raw_input('Enter section name: ') </code></pre> <p>Usage:</p> <pre><code>% python complete.py Enter section name: ext&lt;tab&gt; extension extra Enter section name: extra foo&lt;tab&gt; foo.py foo.txt foo/ Enter section name: extra foo/&lt;tab&gt; foo/bar.txt foo/baz.txt Enter section name: extra foo/bar.txt </code></pre> <p><strong>Update</strong> It will complete paths from the root if the user types <code>/</code>:</p> <pre><code>% python complete.py Enter section name: extra /Use&lt;tab&gt; /Users/.localized /Users/Shared/ /Users/user1 /Users/user2 Enter section name: extra /Users/use&lt;tab&gt; /Users/user1 /Users/user2 </code></pre>
34,770,159
How to filter multiple words in Android Studio logcat
<p>I want to see just a couple of words in logcat. In other words, just a given tags. I tried to enable <em>Regex</em> and type <code>[Encoder|Decoder]</code> as filter, but it doesn't work.</p>
34,770,252
2
2
null
2016-01-13 15:10:37.147 UTC
5
2022-04-07 05:02:16.217 UTC
null
null
null
null
946,409
null
1
40
regex|android-studio|logcat|android-logcat
19,895
<p>You should use a <em>grouping</em> construct:</p> <pre><code>(Encoder|Decoder) </code></pre> <p>Actually, you can just use</p> <pre><code>Encoder|Decoder </code></pre> <p>If you use <code>[Encoder|Decoder]</code>, the <em>character class</em> is created that matches any single character <code>E</code>, <code>n</code>, <code>c</code>... <code>|</code>, <code>D</code>... or <code>r</code>.</p> <p>See <a href="http://www.regular-expressions.info/charclass.html"><em>Character Classes or Character Sets</em></a>:</p> <blockquote> <p>With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an <code>a</code> or an <code>e</code>, use <code>[ae]</code>.</p> </blockquote> <p>Another must-read is certainly <a href="http://www.regular-expressions.info/alternation.html"><em>Alternation with The Vertical Bar or Pipe Symbol</em></a>:</p> <blockquote> <p>If you want to search for the literal text <code>cat</code> or <code>dog</code>, separate both options with a vertical bar or pipe symbol: <code>cat|dog</code>. If you want more options, simply expand the list: <code>cat|dog|mouse|fish</code>.</p> </blockquote> <p>When using <a href="http://www.regular-expressions.info/brackets.html"><code>(...)</code></a> you tell the regex engine to group <em>sequences of characters/subpatterns</em> (with capturing ones, the submatches are stored in the memory buffer and you can access them via backreferences, and with non-capturing <code>(?:...)</code> you only group the subpatterns):</p> <blockquote> <p>By placing part of a regular expression inside round brackets or parentheses, you can <em>group that part of the regular expression together</em>. This allows you to apply a <a href="http://www.regular-expressions.info/repeat.html">quantifier</a> to the entire group or to restrict <a href="http://www.regular-expressions.info/alternation.html">alternation</a> to part of the regex.</p> </blockquote>
2,015,159
htaccess redirect for non-www both http and https
<p>I'd like to have:</p> <ul> <li><code>http://example.com</code> redirect to: <code>http://www.example.com</code></li> <li><code>https://example.com</code> redirect to: <code>https://www.example.com</code></li> </ul> <p>And anything that is <code>http://whatever.example.com</code> NOT append the www like <code>http://www.whatever.example.com</code>.</p>
2,015,170
2
0
null
2010-01-06 18:12:09.557 UTC
15
2013-08-03 23:53:03.567 UTC
2013-08-03 23:53:03.567 UTC
user212218
null
null
207,069
null
1
15
http|.htaccess|redirect|https
24,472
<p>Try this rule:</p> <pre><code>RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ RewriteCond %{HTTPS}s ^on(s)| RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre> <p>Here’s an explanation:</p> <ol> <li>The first condition tests if the HTTP header field <em>Host</em> has the required format (contains exactly one period).</li> <li>The second condition tests if the concatenated value of the value of the <em>HTTPS</em> variable (values <code>on</code> and <code>off</code>) and <code>s</code> (so either <code>ons</code> or <code>offs</code>) is equal to <code>ons</code> and captures the <code>s</code>. This means if <code>%{HTTPS}s</code> evaluates to <code>ons</code>, the first matching group is <code>s</code> and empty otherwise.</li> <li>The rule will match all requests as every string has a start (marked with <code>^</code>) and redirects them to the evaluated value of <code>http%1://www.%{HTTP_HOST}%{REQUEST_URI}</code> if both conditions are true. Where <code>%1</code> is the first matching group of the previous condition (<code>s</code> if HTTPS and empty otherwise), <code>%{HTTP_HOST}</code> is the HTTP <em>Host</em> of the request and <code>%{REQUEST_URI}</code> is the absolute URL path that was requested.</li> </ol>
29,312,123
How does the double exclamation (!!) work in javascript?
<p>I'm going through the Discover Meteor demo, and am struggling to figure out how exactly 'return !! userId;' works in <a href="https://github.com/DiscoverMeteor/Microscope/commit/chapter7-2" rel="noreferrer">this section</a>:</p> <pre><code>Posts.allow({ insert: function(userId, doc) { // only allow posting if you are logged in return !! userId; } }); </code></pre>
29,312,197
1
1
null
2015-03-28 00:12:54.233 UTC
42
2021-09-28 21:08:47.54 UTC
2015-03-28 00:28:39.807 UTC
null
179,125
null
4,549,682
null
1
141
javascript
89,547
<p><code>!</code> is the logical negation or &quot;not&quot; operator. <code>!!</code> is <code>!</code> twice. It's a way of casting a &quot;truthy&quot; or &quot;falsy&quot; value to <code>true</code> or <code>false</code>, respectively. Given a boolean, <code>!</code> will negate the value, i.e. <code>!true</code> yields <code>false</code> and vice versa. Given something other than a boolean, the value will first be converted to a boolean and then negated. For example, <code>!undefined</code> will first convert <code>undefined</code> to <code>false</code> and then negate it, yielding <code>true</code>. Applying a second <code>!</code> operator (<code>!!undefined</code>) yields <code>false</code>, so in effect <code>!!undefined</code> converts <code>undefined</code> to <code>false</code>.</p> <p>In JavaScript, the values <code>false</code>, <code>null</code>, <code>undefined</code>, <code>0</code>, <code>-0</code>, <code>NaN</code>, and <code>''</code> (empty string) are &quot;falsy&quot; values. All other values are &quot;truthy.&quot;<a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer"><sup>(1):7.1.2</sup></a> Here's a truth table of <code>!</code> and <code>!!</code> applied to various values:</p> <pre class="lang-none prettyprint-override"><code> value │ !value │ !!value ━━━━━━━━━━━┿━━━━━━━━━━┿━━━━━━━━━━━ false │ ✔ true │ false true │ false │ ✔ true null │ ✔ true │ false undefined │ ✔ true │ false 0 │ ✔ true │ false -0 │ ✔ true │ false 1 │ false │ ✔ true -5 │ false │ ✔ true NaN │ ✔ true │ false '' │ ✔ true │ false 'hello' │ false │ ✔ true </code></pre>
50,264,491
How do I customize nvidia-smi 's output to show PID username?
<p>The output of nvidia-smi shows the list of PIDs which are running on the CPU:</p> <pre><code>Thu May 10 09:05:07 2018 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 108... Off | 00000000:0A:00.0 Off | N/A | | 61% 74C P2 195W / 250W | 5409MiB / 11172MiB | 100% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 5973 C ...master_JPG/build/tools/program_pytho.bin 4862MiB | | 0 46324 C python 537MiB | +-----------------------------------------------------------------------------+ </code></pre> <p>How do I show the usernames associated with each process?</p> <p>This shows the username of an individual PID:</p> <pre><code>ps -u -p $pid </code></pre> <hr /> <p>UPDATE: I've posted the solution that worked for me below. I've also uploaded this to Github as a simple script for those who need detailed GPU information:</p> <p><a href="https://github.com/ManhTruongDang/check-gpu" rel="nofollow noreferrer">https://github.com/ManhTruongDang/check-gpu</a></p>
50,268,786
6
3
null
2018-05-10 02:13:23.283 UTC
11
2022-07-24 10:31:15.16 UTC
2022-07-24 10:31:15.16 UTC
null
365,102
null
4,146,344
null
1
26
cuda|gpu|nvidia|resource-monitor
27,213
<p>This is the best I could come up with:</p> <pre><code>nvidia-smi ps -up `nvidia-smi |tail -n +16 | head -n -1 | sed 's/\s\s*/ /g' | cut -d' ' -f3` </code></pre> <p>Sample output:</p> <pre><code>Thu May 10 15:23:08 2018 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 108... Off | 00000000:0A:00.0 Off | N/A | | 41% 59C P2 251W / 250W | 5409MiB / 11172MiB | 100% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1606 C ...master_JPG/build/tools/program.bin 4862MiB | | 0 15314 C python 537MiB | +-----------------------------------------------------------------------------+ USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND user111+ 1606 134 4.8 32980224 789164 pts/19 Rl+ 15:23 0:08 /home/user111 user2 15314 0.4 10.0 17936788 1647040 pts/16 Sl+ 10:41 1:20 python server_ </code></pre> <p>Short explanation of the script:</p> <ul> <li><p><code>Tail</code> and <code>head</code> to remove redundant lines</p></li> <li><p><code>Sed</code> to remove spaces (after this, each column would only be separated by 1 space)</p></li> <li><p><code>Cut</code> to extract the relevant columns </p></li> </ul> <p>The output is a list of PIDs, each occupying 1 line. We only need to use <code>ps -up</code> to show the relevant information</p> <p>UPDATE: A better solution:</p> <pre><code>ps -up `nvidia-smi |tee /dev/stderr |tail -n +16 | head -n -1 | sed 's/\s\s*/ /g' | cut -d' ' -f3` </code></pre> <p>This way, <code>nvidia-smi</code> would have to be called only once. See also: </p> <p><a href="https://stackoverflow.com/questions/50501077/how-to-output-bash-command-to-stdout-and-pipe-to-another-command-at-the-same-tim/50501204?noredirect=1#comment88026247_50501204">How to output bash command to stdout and pipe to another command at the same time?</a></p> <p>UPDATE 2: I've uploaded this to Github as a simple script for those who need detailed GPU information.</p> <p><a href="https://github.com/ManhTruongDang/check-gpu" rel="nofollow noreferrer">https://github.com/ManhTruongDang/check-gpu</a></p>
32,404,672
Cleanly updating a hierarchy in Entity Framework
<p>I'm submitting a form for a <code>StoredProcedureReport</code>, which has many <code>StoredProcedureParameters</code>. Create works fine, but trying to update has left me asking whether or not Microsoft can seriously be serious.</p> <p>I come from a Rails background where <code>@report.update_attributes(params[:report])</code> will know exactly what to do with whatever association data it finds within. From what I can tell, the .NET equivalent of this is <code>TryUpdateModel</code>, which looked promising. At first. So I tried it with some params like this</p> <pre><code>IDGUID:d70008a5-a1a3-03d2-7baa-e39c5044ad41 StoredProcedureName:GetUsers Name:search again UPDATED StoredProcedureReportParameters[0].IDGUID:d70008a5-aba3-7560-a6ef-30a5524fac72 StoredProcedureReportParameters[0].StoredProcedureReportID:d70008a5-a1a3-03d2-7baa-e39c5044ad41 StoredProcedureReportParameters[0].Name:RowsPerPage StoredProcedureReportParameters[0].Label:rows StoredProcedureReportParameters[0].StoredProcedureReportParameterDataTypeID:a50008a5-2755-54c0-b052-865abf459f7f StoredProcedureReportParameters[0].StoredProcedureReportParameterInputTypeID:a50008a5-2955-a593-d00f-00cd4543babf StoredProcedureReportParameters[0].DefaultValue:10 StoredProcedureReportParameters[0].AllowMultiple:false StoredProcedureReportParameters[0].Hidden:false StoredProcedureReportParameters[1].IDGUID:d70008a5-a7a3-e35e-28b6-36dd9e448ee5 StoredProcedureReportParameters[1].StoredProcedureReportID:d70008a5-a1a3-03d2-7baa-e39c5044ad41 StoredProcedureReportParameters[1].Name:PageNumber StoredProcedureReportParameters[1].Label:page was MODIFIEIIEIEIED!!! StoredProcedureReportParameters[1].StoredProcedureReportParameterDataTypeID:a50008a5-2755-54c0-b052-865abf459f7f StoredProcedureReportParameters[1].StoredProcedureReportParameterInputTypeID:a50008a5-2955-a593-d00f-00cd4543babf StoredProcedureReportParameters[1].DefaultValue:1 StoredProcedureReportParameters[1].AllowMultiple:false StoredProcedureReportParameters[1].Hidden:false </code></pre> <p>I assumed that with all the primary and foreign keys set, EF would know how to update the <code>StoredProcedureReportParameter</code> objects when I do this:</p> <pre><code>var report = context.StoredProcedureReports.FirstOrDefault(r =&gt; r.IDGUID == reportID); if (report != null) { succeeded = TryUpdateModel(report); context.SaveChanges(); } </code></pre> <p>Now, if I place a breakpoint on <code>context.SaveChanges()</code>, my <code>report</code> object and its associated <code>StoredProcedureReportParameters</code> look just like I'd expect them to. The foreign and primary keys are set, ALL the values check out. But <code>SaveChanges</code> raises this error:</p> <blockquote> <p>The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</p> </blockquote> <p>One of the suggestions in this message is that I should assign the foreign-key property a non-null value, but as I stated, <code>StoredProcedureReportID</code> <em>has</em> the correct value on both <code>StoredProcedureReportParameter</code> objects.</p> <p>Other posts I've read that deal with <code>Update</code> operations loop over associations and attach them to the context. Is this really what I'm stuck doing? Is EF really that dense? I'm hoping for a .NET pro to show me the light here. There <em>has</em> to be an easier way than that.</p>
32,407,776
1
1
null
2015-09-04 18:43:57.31 UTC
10
2016-09-09 14:26:29.537 UTC
2015-09-04 19:20:54.15 UTC
null
13,302
null
484,342
null
1
4
asp.net-mvc|entity-framework|updates|crud
11,456
<p>It is not that hard. There are 2 main ways to work using EF: Attached entities and Detached entities.</p> <p>Let's suppose that we have 2 entites:</p> <pre><code>public class Foo { public int FooId { get; set; } public string Description { get; set; } public ICollection&lt;Bar&gt; Bars { get; set; } } public class Bar { public int BarId { get; set; } public string Description { get; set; } } </code></pre> <p><strong>INSERTING</strong></p> <pre><code>var foo = new Foo() { FooId = 1, Description = "as", Bars = new List&lt;Bar&gt;() { new Bar { BarId = 1, Description = "as" }, new Bar { BarId = 2, Description = "as" }, new Bar { BarId = 2, Description = "as" } } }; ctx.Foos.Add(foo); ctx.SaveChanges(); </code></pre> <p>In the above example, EF will recognize the new items, and will insert all of them.</p> <p><strong>UPDATING (ATTACHED)</strong></p> <pre><code>var foo = ctx.Foos.Include("Bars").Where(i =&gt; i.FooId == 1).FirstOrDefault(); foreach (var bar in foo.Bars) { bar.Description = "changed"; } ctx.SaveChanges(); </code></pre> <p>Here we loaded foo and its bars from the context. They are already attached to the context. So, all we need to do is change the values and call <code>SaveChanges()</code>. Everything will work fine.</p> <p><strong>UPDATING (DETACHED)</strong></p> <pre><code>var foo = new Foo { FooId = 1, Description = "changed3", Bars = new List&lt;Bar&gt; { new Bar { BarId = 1, Description = "changed3" }, new Bar { BarId = 2, Description = "changed3" } } }; ctx.Entry(foo).State = EntityState.Modified; foreach (var bar in foo.Bars) { ctx.Entry(bar).State = EntityState.Modified; } ctx.SaveChanges(); </code></pre> <p>Here, we are working with items which already exists in database. However, they were not loaded from EF (they are not attached). EF knows nothing about them. We need to attached all of them manually and tell EF that they are modified.</p> <p><strong>REMOVING (ATTACHED)</strong></p> <pre><code>var foo = ctx.Foos.Include("Bars").Where(i =&gt; i.FooId == 1).FirstOrDefault(); var bar = foo.Bars.First(); foo.Bars.Remove(bar); ctx.SaveChanges(); </code></pre> <p>Load bars from EF and just remove them from the collection.</p> <p><strong>REMOVING (DETACHED)</strong></p> <pre><code>var bar = new Bar { BarId = 1 }; ctx.Entry(bar).State = EntityState.Deleted; ctx.SaveChanges(); </code></pre> <p>Here, Bar was not loaded from the context. So, we have to tell EF that it is deleted.</p> <hr> <p>In your case, you are sending the updated object to an MVC Controller; so, you have to tell EF that <code>StoredProcedureReport</code> and <code>StoredProcedureParameters</code> are modified.</p> <p>If all the properties are being modified you can use:</p> <pre><code>ctx.Entry(foo).State = EntityState.Modified; //remember to do the same in all children objects </code></pre> <p>It will mark all properties as modified. Be aware that if some property was not set on view, it will be updated as an empty value.</p> <p>If not all the properties are being modified, you have to specify which properties are. Like this:</p> <pre><code>context.Entry(foo).Property("Description").IsModified = true; context.Entry(foo).Property("AnotherProperty").IsModified = true; </code></pre> <p>Hope it helps!</p>
32,573,382
How to take ints from user using fgets in C?
<p>I'm a beginner at C. I'm trying to write a program that computes the volume based on user's input of 3 integers using <code>fgets()</code>, and I'm struggling to understand why my code is not working.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int volumn(int a, int b, int c); int main(int argc, char* argv[]){ char* height, width, depth; fgets(&amp;height, 10, stdin); fgets(&amp;width, 10, stdin); fgets(&amp;depth, 10, stdin); printf("\nThe volumn is %d\n", volumn(atoi(&amp;height), atoi(&amp;width), atoi(&amp;depth))); return 0; } int volumn(int a, int b, int c){ return a * b * c; } </code></pre> <p><strong>EDIT</strong>: I'm getting the following errors/warnings when I run the code above:</p> <pre><code>goodbyeworld.c:8:11: warning: incompatible pointer types passing 'char **' to parameter of type 'char *'; remove &amp; [-Wincompatible-pointer-types] fgets(&amp;height, 10, stdin); ^~~~~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/stdio.h:238:30: note: passing argument to parameter here char *fgets(char * __restrict, int, FILE *); ^ goodbyeworld.c:12:48: warning: incompatible pointer types passing 'char **' to parameter of type 'const char *'; remove &amp; [-Wincompatible-pointer-types] printf("\nThe volumn is %d\n", volumn(atoi(&amp;height), atoi(&amp;width), a... ^~~~~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/stdlib.h:132:23: note: passing argument to parameter here int atoi(const char *); ^ 2 warnings generated. </code></pre>
32,573,415
4
2
null
2015-09-14 20:29:29.453 UTC
null
2016-12-24 18:52:25.907 UTC
2015-09-14 23:04:45.477 UTC
null
5,245,267
null
5,245,267
null
1
3
c|pointers|fgets
47,792
<p>First of all, a definition like</p> <pre><code> char* height, width, depth; </code></pre> <p>make <code>height</code> a pointer to <code>char</code> and the rest two as <code>char</code>s.</p> <p>Secondly (not much relevant <em>here</em>, but in general, important), You did not allocate memory to the pointers you want to use (if at all).</p> <p>If you have a fixed input length decided as <code>10</code>, you can simply make all the three variables as array ans use the <em>names</em> directly, like</p> <pre><code>#define VAL 10 char height[VAL] = {0}; char width[VAL] = {0}; char depth[VAL] = {0}; </code></pre> <p>and then</p> <pre><code>fgets(height, 10, stdin); </code></pre> <p>finally, consider using <a href="http://linux.die.net/man/3/strtol" rel="noreferrer"><code>strtol()</code></a> over <code>atoi()</code> for better error handling.</p>
5,819,121
Understanding Java IOException
<p>I need some help with understanding the IOException. I've reviewed a lot of information on the internet, and looked at the technical specifications at Oracle's Java website.</p> <p>Am I correct in my understanding of the IOException class and all of it's sub-classes, that there are no associated "error messages" or "return code" values?</p> <p>So if one wanted to issue some message and/or return code value, one would have to insert them with the IOException catch logic? </p> <p>If the above is true, how would one separate the various IOException subclasses?</p> <p>e.g. If the application detected an IOException, what sort of IOException is it? End-Of-File, File-Is-Closed, File-Not_found, File-In-Use, etc.</p>
5,819,165
5
0
null
2011-04-28 13:09:30.873 UTC
10
2014-01-31 13:17:38.48 UTC
2011-04-28 13:14:33.167 UTC
null
40,342
null
720,815
null
1
18
java|ioexception
69,090
<p>There are no "return code" values in exceptions (in general), but they do contain error messages. And you should handle them in <code>catch</code> blocks, where you can specify the type of exception you want to handle. You can have several <code>catch</code> blocks after a <code>try</code> block, to handle different types of exceptions differently. The catch blocks will be invoked in the order specified, and the first one with a suitable parameter type will handle the exception. So you should catch the more specific exception types first, then the more general ones.</p> <p>Simplistic example:</p> <pre><code>try { ... throw new FileNotFoundException("This is an error message"); ... } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); ... } catch (EOFException e) { System.out.println("End of file reached: " + e.getMessage()); ... } catch (IOException e) { // catch all IOExceptions not handled by previous catch blocks System.out.println("General I/O exception: " + e.getMessage()); e.printStackTrace(); ... } </code></pre> <p>As you see in the last catch block, exceptions store the stack trace of their origin, which can be printed. However, it is usually not a good idea to print such messages directly like here; in real production code, you usually want to log these messages using a logging framework, or display (suitable parts of) them on a UI.</p>
5,872,759
UITableView insert rows without scrolling
<p>I have a list of data that I'm pulling from a web service. I refresh the data and I want to insert the data in the table view above the current data, but I want to keep my current scroll position in the tableview. </p> <p>Right now I accomplish this by inserting a section above my current section, but it actually inserts, scrolls up, and then I have to manually scroll down. I tried disabling scrolling on the table before this, but that didn't work either.</p> <p>This looks choppy and seems hacky. What is a better way to do this?</p> <pre><code>[tableView beginUpdates]; [tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone]; [tableView endUpdates]; NSUInteger iContentOffset = 200; //height of inserted rows [tableView setContentOffset:CGPointMake(0, iContentOffset)]; </code></pre>
5,886,300
6
10
null
2011-05-03 16:38:29.72 UTC
11
2020-02-03 10:56:36.433 UTC
null
null
null
null
315,074
null
1
16
iphone|objective-c|uitableview
21,911
<p>The best way I found to get my desired behavior is to not animate the insertion at all. The animations were causing the choppyness. </p> <p>Instead I am calling:</p> <pre><code>[tableView reloadData]; // set the content offset to the height of inserted rows // (2 rows * 44 points = 88 in this example) [tableView setContentOffset:CGPointMake(0, 88)]; </code></pre> <p>This makes the reload appear at the same time as the content offset change.</p>
5,942,360
How to search and replace with a counter-based expression in Vim?
<p>Is there a way to insert the value from some sort of counter variable in Vim <code>:substitute</code> command?</p> <p>For instance, to convert this document:</p> <pre><code>&lt;SomeElement Id=&quot;F&quot; ... /&gt; &lt;SomeElement Id=&quot;F&quot; ... /&gt; &lt;SomeElement Id=&quot;F&quot; ... /&gt; </code></pre> <p>to this resulting document:</p> <pre><code>&lt;SomeElement Id=&quot;1&quot; ... /&gt; &lt;SomeElement Id=&quot;2&quot; ... /&gt; &lt;SomeElement Id=&quot;3&quot; ... /&gt; </code></pre> <p>I imagine, the command would look like so:</p> <pre><code>:%s/^\(\s*&lt;SomeElement Id=&quot;\)F\(&quot;.*\)$/\1&lt;insert-counter-here&gt;\2/g </code></pre> <p>I am using a very recent Windows build, from their provided installer. I strongly prefer not to install any additional tools. Ideally, I'd like to also avoid having to install scripts to support this, but I'm willing to, if it is the only way to do it.</p>
40,656,861
6
0
null
2011-05-09 20:51:58.8 UTC
10
2022-03-05 15:06:35.29 UTC
2021-01-23 21:45:51.377 UTC
null
254,635
null
232,593
null
1
20
regex|vim|counter|replace
8,160
<p><a href="http://vim.wikia.com/wiki/Making_a_list_of_numbers" rel="noreferrer">Vim wiki instructions</a> seems to be the easiest solution (at least for me).</p> <p>Example below replaces all occurences of <code>PATTERN</code> with <code>REPLACE_[counter]</code> (<code>REPLACE_1</code>, <code>REPLACE_2</code> etc.):</p> <pre><code>:let i=1 | g/PATTERN/s//\='REPLACE_'.i/ | let i=i+1 </code></pre> <p>To answer the question it might look like this:</p> <pre><code>:let i=1 | g/SomeElement Id="F"/s//\='SomeElement Id="'.i.'"'/ | let i=i+1 </code></pre> <h3>Alternative solution</h3> <p>If anyone is interested in a solution with <code>%s</code> syntax I would advise to look at the @ib. answer which is:</p> <pre><code>:let n=[0] | %s/Id="\zsF\ze"/\=map(n,'v:val+1')/g </code></pre>
6,164,167
Get MAC address on local machine with Java
<p>I can use </p> <pre><code>ip = InetAddress.getLocalHost(); NetworkInterface.getByInetAddress(ip); </code></pre> <p>to obtain the mac address, but if I use this code in an offline machine it doesn't work.</p> <p>So, <strong>How can I get the Mac address?</strong></p>
6,164,182
9
6
null
2011-05-28 20:27:00.323 UTC
14
2020-08-11 18:06:06.143 UTC
2011-05-28 20:29:38.433 UTC
null
139,010
null
741,028
null
1
27
java|sockets|mac-address
81,396
<p>With Java 6+, you can use <a href="http://download.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress()" rel="noreferrer"><code>NetworkInterface.getHardwareAddress</code></a>.</p> <p>Bear in mind that a computer can have no network cards, especially if it's embedded or virtual. It can also have more than one. You can get a list of all network cards with <a href="http://download.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getNetworkInterfaces()" rel="noreferrer"><code>NetworkInterface.getNetworkInterfaces()</code></a>.</p>
6,292,164
Using print_r and var_dump with circular reference
<p>I'm using the <a href="http://www.symfony-project.org/" rel="noreferrer">MVC framework Symfony</a>, and it seems a lot of the built-in objects I want to debug have circular references. This makes it impossible to print the variables with <code>print_r()</code> or <code>var_dump()</code> (since they follow circular references ad infinitum or until the process runs out of memory, whichever comes first).</p> <p>Instead of writing my own <code>print_r</code> clone with some intelligence, are there better alternatives out there? I only want to be able to print a variable (object, array or scalar), either to a log file, http header or the web page itself.</p> <p>Edit: to clarify what the problem is, try this code:</p> <pre><code>&lt;?php class A { public $b; public $c; public function __construct() { $this-&gt;b = new B(); $this-&gt;c = new C(); } } class B { public $a; public function __construct() { $this-&gt;a = new A(); } } class C { } ini_set('memory_limit', '128M'); set_time_limit(5); print_r(new A()); #var_dump(new A()); #var_export(new A()); </code></pre> <p>It doesn't work with <code>print_r()</code>, <code>var_dump()</code> or <code>var_export()</code>. The error message is:</p> <blockquote> <p>PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 523800 bytes) in print_r_test.php on line 10</p> </blockquote>
6,293,163
9
3
null
2011-06-09 11:36:28.953 UTC
9
2022-08-01 16:50:06.6 UTC
2011-06-09 12:07:02.21 UTC
null
12,534
null
12,534
null
1
46
php|debugging|circular-reference
23,642
<p>We are using the PRADO Framework and it has a built in class called "TVarDumper" which can handle such complex objects pretty well - it even can format it in nice HTML incl. Syntax Highlighting. You can get that class from <a href="https://github.com/google-code-export/prado3/blob/master/framework/Util/TVarDumper.php" rel="noreferrer">HERE</a>.</p>
46,572,744
How to change permission recursively to folder with AWS s3 or AWS s3api
<p>I am trying to grant permissions to an existing account in s3.</p> <p>The bucket is owned by the account, but the data was copied from another account's bucket.</p> <p>When I try to grant permissions with the command:</p> <pre><code>aws s3api put-object-acl --bucket &lt;bucket_name&gt; --key &lt;folder_name&gt; --profile &lt;original_account_profile&gt; --grant-full-control emailaddress=&lt;destination_account_email&gt; </code></pre> <p>I receive the error:</p> <pre><code>An error occurred (NoSuchKey) when calling the PutObjectAcl operation: The specified key does not exist. </code></pre> <p>while if I do it on a single file the command is successful.</p> <p>How can I make it work for a full folder?</p>
46,577,516
9
1
null
2017-10-04 19:29:40.337 UTC
10
2022-04-06 17:34:28.78 UTC
null
null
null
null
41,977
null
1
24
amazon-web-services|amazon-s3|directory|file-permissions|acl
22,998
<p>You will need to run the command individually for every object.</p> <p>You might be able to short-cut the process by using:</p> <pre><code>aws s3 cp --acl bucket-owner-full-control --metadata Key=Value --profile &lt;original_account_profile&gt; s3://bucket/path s3://bucket/path </code></pre> <p>That is, you copy the files to themselves, but with the added ACL that grants permissions to the bucket owner.</p> <p>If you have sub-directories, then add <code>--recursive</code>.</p>
49,533,543
Spring and scheduled tasks on multiple instances
<p>We have a Spring Boot application, and have scheduled tasks.</p> <p>We want to deploy our application on multiple servers, so will be multiple instances of application.</p> <p>How to configure Spring to run scheduled tasks only on specified servers?</p>
49,533,618
6
3
null
2018-03-28 11:38:50.323 UTC
9
2021-12-15 06:13:45.313 UTC
null
null
null
null
9,271,474
null
1
30
spring|spring-boot|jobs|job-scheduling
40,260
<p>This is a very wide topic. And there are many options to achieve this.</p> <ol> <li><p>You can configure your application to have multiple profiles. For example use another profile 'cron' . And start your application on only one server with this profile. So for example, on a production environment you have three servers (S1, S2, S3), then you could run on S1 with profile prod and cron(<code>-Dspring.profiles.active=prod,cron</code>). And on S2 and S3 just use prod profile(<code>-Dspring.profiles.active=prod</code>).</p> <p>And in code, you can use <code>@Profile(&quot;cron&quot;)</code> on scheduler classes. This way it will be executed only when cron profile is active</p> </li> <li><p>Use a distributed lock. If you have Zookeeper in your environment, you can use this to achieve distributed locking system.</p> </li> <li><p>You can use some database(mysql) and create a sample code to get a lock on one of the table and add an entry. And whichever instance gets the lock, will make an entry in this database and will execute the cron job. You need to put a check in your code, if <code>getLock()</code> is successfull only then proceed with execution. Mysql has utilities like <code>LOCK TABLES</code>, which you could use to get away with concurrent read/writes.</p> </li> </ol> <p>personally I would say, option 2 is the best of all.</p>
49,110,877
How to adjust facet size manually
<p>I have a faceted plot with very diverse data. So some facets have only 1 <code>x</code> value, but some others have 13 <code>x</code> values. I know there is the parameter <code>space='free'</code> which adjusts the width of each facet by the data it represents.</p> <p>My question, is there a possibility to adjust this space manually? Since some of my facets are so small, it is no longer possible to read the labels in the facets. I made a little reproducible example to show what I mean.</p> <pre><code>df &lt;- data.frame(labelx=rep(c('my long label','short'), c(2,26)), labely=rep(c('a','b'), each=14), x=c(letters[1:2],letters[1:26]), y=LETTERS[6:7], i=rnorm(28)) ggplot(df, aes(x,y,color=i)) + geom_point() + facet_grid(labely~labelx, scales='free_x', space='free_x') </code></pre> <p>So depending on your screen, the <code>my long label</code> facet gets compressed and you can no longer read the label.</p> <p>I found a post on the internet which seems to do exactly what I want to do, but this seems to no longer work in <code>ggplot2</code>. The post is from 2010.</p> <p><a href="https://kohske.wordpress.com/2010/12/25/adjusting-the-relative-space-of-a-facet-grid/" rel="noreferrer">https://kohske.wordpress.com/2010/12/25/adjusting-the-relative-space-of-a-facet-grid/</a></p> <p>He suggests to use <code>facet_grid(fac1 + fac2 ~ fac3 + fac4, widths = 1:4, heights = 4:1)</code>, so <code>widths</code> and <code>heights</code> to adjust each facet size manually.</p>
49,225,527
4
1
null
2018-03-05 12:48:27.93 UTC
16
2022-04-27 21:25:09.68 UTC
2018-04-13 22:26:49.02 UTC
null
3,458,744
null
3,737,501
null
1
29
r|ggplot2|facet|ggproto
35,681
<p>You can adjust the widths of a ggplot object using grid graphics</p> <pre><code>g = ggplot(df, aes(x,y,color=i)) + geom_point() + facet_grid(labely~labelx, scales='free_x', space='free_x') library(grid) gt = ggplot_gtable(ggplot_build(g)) gt$widths[4] = 4*gt$widths[4] grid.draw(gt) </code></pre> <p><a href="https://i.stack.imgur.com/nblsZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nblsZ.png" alt="enter image description here"></a></p> <p>With complex graphs with many elements, it can be slightly cumbersome to determine which width it is that you want to alter. In this instance it was grid column 4 that needed to be expanded, but this will vary for different plots. There are several ways to determine which one to change, but a fairly simple and good way is to use <code>gtable_show_layout</code> from the <code>gtable</code> package.</p> <pre><code>gtable_show_layout(gt) </code></pre> <p>produces the following image:</p> <p><a href="https://i.stack.imgur.com/aYKRq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aYKRq.png" alt="enter image description here"></a></p> <p>in which we can see that the left hand facet is in column number 4. The first 3 columns provide room for the margin, the axis title and the axis labels+ticks. Column 5 is the space between the facets, column 6 is the right hand facet. Columns 7 through 12 are for the right hand facet labels, spaces, the legend, and the right margin.</p> <p>An alternative to inspecting a graphical representation of the gtable is to simply inspect the table itself. In fact if you need to automate the process, this would be the way to do it. So lets have a look at the TableGrob:</p> <pre><code>gt # TableGrob (13 x 12) "layout": 25 grobs # z cells name grob # 1 0 ( 1-13, 1-12) background rect[plot.background..rect.399] # 2 1 ( 7- 7, 4- 4) panel-1-1 gTree[panel-1.gTree.283] # 3 1 ( 9- 9, 4- 4) panel-2-1 gTree[panel-3.gTree.305] # 4 1 ( 7- 7, 6- 6) panel-1-2 gTree[panel-2.gTree.294] # 5 1 ( 9- 9, 6- 6) panel-2-2 gTree[panel-4.gTree.316] # 6 3 ( 5- 5, 4- 4) axis-t-1 zeroGrob[NULL] # 7 3 ( 5- 5, 6- 6) axis-t-2 zeroGrob[NULL] # 8 3 (10-10, 4- 4) axis-b-1 absoluteGrob[GRID.absoluteGrob.329] # 9 3 (10-10, 6- 6) axis-b-2 absoluteGrob[GRID.absoluteGrob.336] # 10 3 ( 7- 7, 3- 3) axis-l-1 absoluteGrob[GRID.absoluteGrob.343] # 11 3 ( 9- 9, 3- 3) axis-l-2 absoluteGrob[GRID.absoluteGrob.350] # 12 3 ( 7- 7, 8- 8) axis-r-1 zeroGrob[NULL] # 13 3 ( 9- 9, 8- 8) axis-r-2 zeroGrob[NULL] # 14 2 ( 6- 6, 4- 4) strip-t-1 gtable[strip] # 15 2 ( 6- 6, 6- 6) strip-t-2 gtable[strip] # 16 2 ( 7- 7, 7- 7) strip-r-1 gtable[strip] # 17 2 ( 9- 9, 7- 7) strip-r-2 gtable[strip] # 18 4 ( 4- 4, 4- 6) xlab-t zeroGrob[NULL] # 19 5 (11-11, 4- 6) xlab-b titleGrob[axis.title.x..titleGrob.319] # 20 6 ( 7- 9, 2- 2) ylab-l titleGrob[axis.title.y..titleGrob.322] # 21 7 ( 7- 9, 9- 9) ylab-r zeroGrob[NULL] # 22 8 ( 7- 9,11-11) guide-box gtable[guide-box] # 23 9 ( 3- 3, 4- 6) subtitle zeroGrob[plot.subtitle..zeroGrob.396] # 24 10 ( 2- 2, 4- 6) title zeroGrob[plot.title..zeroGrob.395] # 25 11 (12-12, 4- 6) caption zeroGrob[plot.caption..zeroGrob.397] </code></pre> <p>The relevant bits are</p> <pre><code># cells name # ( 7- 7, 4- 4) panel-1-1 # ( 9- 9, 4- 4) panel-2-1 # ( 6- 6, 4- 4) strip-t-1 </code></pre> <p>in which the names panel-x-y refer to panels in x, y coordinates, and the cells give the coordinates (as ranges) of that named panel in the table. So, for example, the top and bottom left-hand panels both are located in table cells with the column ranges <code>4- 4</code>. (only in column four, that is). The left-hand top strip is also in cell column 4.</p> <p>If you wanted to use this table to find the relevant width programmatically, rather than manually, (using the top left facet, ie <code>"panel-1-1"</code> as an example) you could use </p> <pre><code>gt$layout$l[grep('panel-1-1', gt$layout$name)] # [1] 4 </code></pre>
44,467,828
What techniques can be used to measure performance of pandas/numpy solutions
<h1>Question</h1> <p>How do I measure the performance of the various functions below in a concise and comprehensive way.</p> <h1>Example</h1> <p>Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame({ 'Group': list('QLCKPXNLNTIXAWYMWACA'), 'Value': [29, 52, 71, 51, 45, 76, 68, 60, 92, 95, 99, 27, 77, 54, 39, 23, 84, 37, 99, 87] }) </code></pre> <p>I want to sum up the <code>Value</code> column grouped by distinct values in <code>Group</code>. I have three methods for doing it.</p> <pre><code>import pandas as pd import numpy as np from numba import njit def sum_pd(df): return df.groupby('Group').Value.sum() def sum_fc(df): f, u = pd.factorize(df.Group.values) v = df.Value.values return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index() @njit def wbcnt(b, w, k): bins = np.arange(k) bins = bins * 0 for i in range(len(b)): bins[b[i]] += w[i] return bins def sum_nb(df): b, u = pd.factorize(df.Group.values) w = df.Value.values bins = wbcnt(b, w, u.size) return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index() </code></pre> <h2>Are they the same?</h2> <pre><code>print(sum_pd(df).equals(sum_nb(df))) print(sum_pd(df).equals(sum_fc(df))) True True </code></pre> <h2>How fast are they?</h2> <pre><code>%timeit sum_pd(df) %timeit sum_fc(df) %timeit sum_nb(df) 1000 loops, best of 3: 536 µs per loop 1000 loops, best of 3: 324 µs per loop 1000 loops, best of 3: 300 µs per loop </code></pre>
56,398,618
3
1
null
2017-06-09 23:12:54.8 UTC
22
2019-06-05 14:40:51.333 UTC
2019-06-05 13:59:09.947 UTC
null
2,336,654
null
2,336,654
null
1
25
python|pandas|numpy
1,509
<p>They might not classify as "simple frameworks" because they are third-party modules that need to be installed but there are two frameworks I often use:</p> <ul> <li><a href="https://github.com/MSeifert04/simple_benchmark" rel="noreferrer"><code>simple_benchmark</code></a> (I'm the author of that package)</li> <li><a href="https://github.com/nschloe/perfplot" rel="noreferrer"><code>perfplot</code></a></li> </ul> <p>For example the <code>simple_benchmark</code> library allows to decorate the functions to benchmark:</p> <pre><code>from simple_benchmark import BenchmarkBuilder b = BenchmarkBuilder() import pandas as pd import numpy as np from numba import njit @b.add_function() def sum_pd(df): return df.groupby('Group').Value.sum() @b.add_function() def sum_fc(df): f, u = pd.factorize(df.Group.values) v = df.Value.values return pd.Series(np.bincount(f, weights=v).astype(int), pd.Index(u, name='Group'), name='Value').sort_index() @njit def wbcnt(b, w, k): bins = np.arange(k) bins = bins * 0 for i in range(len(b)): bins[b[i]] += w[i] return bins @b.add_function() def sum_nb(df): b, u = pd.factorize(df.Group.values) w = df.Value.values bins = wbcnt(b, w, u.size) return pd.Series(bins, pd.Index(u, name='Group'), name='Value').sort_index() </code></pre> <p>Also decorate a function that produces the values for the benchmark:</p> <pre><code>from string import ascii_uppercase def creator(n): # taken from another answer here letters = list(ascii_uppercase) np.random.seed([3,1415]) df = pd.DataFrame(dict( Group=np.random.choice(letters, n), Value=np.random.randint(100, size=n) )) return df @b.add_arguments('Rows in DataFrame') def argument_provider(): for exponent in range(4, 22): size = 2**exponent yield size, creator(size) </code></pre> <p>And then all you need to run the benchmark is:</p> <pre><code>r = b.run() </code></pre> <p>After that you can inspect the results as plot (you need the <code>matplotlib</code> library for this):</p> <pre><code>r.plot() </code></pre> <p><a href="https://i.stack.imgur.com/X8zup.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X8zup.png" alt="enter image description here"></a></p> <p>In case the functions are very similar in run-time the percentage difference instead of absolute numbers could be more important:</p> <pre><code>r.plot_difference_percentage(relative_to=sum_nb) </code></pre> <p><a href="https://i.stack.imgur.com/cckCb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cckCb.png" alt="enter image description here"></a></p> <p>Or get the times for the benchmark as <code>DataFrame</code> (this needs <code>pandas</code>)</p> <pre><code>r.to_pandas_dataframe() </code></pre> <pre class="lang-none prettyprint-override"><code> sum_pd sum_fc sum_nb 16 0.000796 0.000515 0.000502 32 0.000702 0.000453 0.000454 64 0.000702 0.000454 0.000456 128 0.000711 0.000456 0.000458 256 0.000714 0.000461 0.000462 512 0.000728 0.000471 0.000473 1024 0.000746 0.000512 0.000513 2048 0.000825 0.000515 0.000514 4096 0.000902 0.000609 0.000640 8192 0.001056 0.000731 0.000755 16384 0.001381 0.001012 0.000936 32768 0.001885 0.001465 0.001328 65536 0.003404 0.002957 0.002585 131072 0.008076 0.005668 0.005159 262144 0.015532 0.011059 0.010988 524288 0.032517 0.023336 0.018608 1048576 0.055144 0.040367 0.035487 2097152 0.112333 0.080407 0.072154 </code></pre> <p>In case you don't like the decorators you could also setup everything in one call (in that case you don't need the <code>BenchmarkBuilder</code> and the <code>add_function</code>/<code>add_arguments</code> decorators):</p> <pre><code>from simple_benchmark import benchmark r = benchmark([sum_pd, sum_fc, sum_nb], {2**i: creator(2**i) for i in range(4, 22)}, "Rows in DataFrame") </code></pre> <p>Here <code>perfplot</code> offers a very similar interface (and result):</p> <pre><code>import perfplot r = perfplot.bench( setup=creator, kernels=[sum_pd, sum_fc, sum_nb], n_range=[2**k for k in range(4, 22)], xlabel='Rows in DataFrame', ) import matplotlib.pyplot as plt plt.loglog() r.plot() </code></pre> <p><a href="https://i.stack.imgur.com/Lu97r.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Lu97r.png" alt="enter image description here"></a></p>
21,900,326
Bootstrap dropdown: events for the 'navbar-toggle'?
<p>Do we have <strong>events</strong> for the <code>navbar-toggle</code> that appears when we are on the smaller screen?</p> <p>For instance,</p> <pre><code>$('#myDropdown').on('shown.bs.navbar-toggle', function () { // do something… }); $('#myDropdown').on('hide.bs.navbar-toggle', function () { // do something… }); </code></pre> <p>html,</p> <pre><code>&lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;!--&lt;a class="navbar-brand" href="#"&gt;Home&lt;/a&gt;--&gt; &lt;/div&gt; </code></pre> <p>Otherwise, how can we detect if that <code>navbar-toggle</code> exists on the smaller screen?</p>
22,830,975
3
0
null
2014-02-20 06:49:16.06 UTC
8
2017-04-08 00:02:23.47 UTC
2014-03-28 09:06:13.593 UTC
null
3,075,363
null
413,225
null
1
39
jquery|html|css|twitter-bootstrap|drop-down-menu
47,867
<p>The <code>navbar-toggle</code> methods emit the Collapse events:</p> <h1>Events</h1> <p>Bootstrap's collapse class exposes a few events for hooking into collapse functionality.</p> <pre><code>Event Type Description show.bs.collapse This event fires immediately when the show instance method is called. shown.bs.collapse This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete). hide.bs.collapse This event is fired immediately when the hide method has been called. hidden.bs.collapse This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete). </code></pre> <h1>Example</h1> <pre><code>$('#myCollapsible').on('hidden.bs.collapse', function () { // do something… }) </code></pre> <p>Docs: <a href="http://getbootstrap.com/javascript/#collapse">http://getbootstrap.com/javascript/#collapse</a></p>
42,485,616
How to check if DynamoDB table exists?
<p>I'm a new user in boto3 and i'm using <code>DynamoDB</code>.</p> <p>I went through over the DynamoDB api and I couldn't find any method which tell me if a table is already exists.</p> <p>What is the best approach dealing this issue? </p> <p>Should I try to create a new table and wrap it using try catch ?</p>
42,486,520
8
1
null
2017-02-27 12:16:04.21 UTC
12
2022-08-13 02:39:05.277 UTC
null
null
null
null
2,354,117
null
1
72
python|amazon-dynamodb|boto3
75,121
<p>From reading the documentation, I can see that there are three methods by which you can check if a table exists.</p> <ol> <li>The <a href="http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_CreateTable.html" rel="noreferrer">CreateTable API</a> throws an error <code>ResourceInUseException</code> if the table already exists. Wrap the create_table method with try except to catch this</li> <li>You can use the <a href="http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Client.list_tables" rel="noreferrer">ListTables API</a> to get the list of table names associated with the current account and endpoint. Check if the table name is present in the list of table names you get in the response.</li> <li>The <a href="http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTable.html" rel="noreferrer">DescribeTable API</a> will throw an error <code>ResourceNotFoundException</code> if the table name you request doesn't exist.</li> </ol> <p>To me, the first option sounds better if you just want to create a table.</p> <p><strong>Edit:</strong> I see that some people are finding it difficult to catch the exceptions. I will put some code below for you to know how to handle exceptions in boto3.</p> <p><strong>Example 1</strong></p> <pre><code>import boto3 dynamodb_client = boto3.client('dynamodb') try: response = dynamodb_client.create_table( AttributeDefinitions=[ { 'AttributeName': 'Artist', 'AttributeType': 'S', }, { 'AttributeName': 'SongTitle', 'AttributeType': 'S', }, ], KeySchema=[ { 'AttributeName': 'Artist', 'KeyType': 'HASH', }, { 'AttributeName': 'SongTitle', 'KeyType': 'RANGE', }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5, }, TableName='test', ) except dynamodb_client.exceptions.ResourceInUseException: # do something here as you require pass </code></pre> <p><strong>Example 2</strong></p> <pre><code>import boto3 dynamodb_client = boto3.client('dynamodb') table_name = 'test' existing_tables = dynamodb_client.list_tables()['TableNames'] if table_name not in existing_tables: response = dynamodb_client.create_table( AttributeDefinitions=[ { 'AttributeName': 'Artist', 'AttributeType': 'S', }, { 'AttributeName': 'SongTitle', 'AttributeType': 'S', }, ], KeySchema=[ { 'AttributeName': 'Artist', 'KeyType': 'HASH', }, { 'AttributeName': 'SongTitle', 'KeyType': 'RANGE', }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5, }, TableName=table_name, ) </code></pre> <p><strong>Example 3</strong></p> <pre><code>import boto3 dynamodb_client = boto3.client('dynamodb') try: response = dynamodb_client.describe_table(TableName='test') except dynamodb_client.exceptions.ResourceNotFoundException: # do something here as you require pass </code></pre>
9,497,703
XPATH selecting the root element
<p>Is there a simple way of moving back to the root node within any given context. The XML document I'm working with is extremely large and would require using ../.. about a dozen times!!</p> <p>Any help is greatly appreciated guys.</p>
9,500,452
4
0
null
2012-02-29 10:52:05.17 UTC
5
2016-04-04 15:15:18.48 UTC
null
null
null
null
1,221,847
null
1
30
xml|xpath
80,683
<p>I'm guessing you are in a predicate here? and want to return to look at data higher up the tree for your condition?</p> <p>You should be able to start with a leading / and then work your way back down e.g</p> <pre><code>/vehicles/cars/car[@id = /vehicles/featuredVehicle/@id] </code></pre>
9,474,446
Get first element in PHP stdObject
<p>I have an object (stored as $videos) that looks like this</p> <pre><code>object(stdClass)#19 (3) { [0]=&gt; object(stdClass)#20 (22) { ["id"]=&gt; string(1) "123" etc... </code></pre> <p>I want to get the ID of just that first element, without having to loop over it.</p> <p>If it were an array, I would do this:</p> <pre><code>$videos[0]['id'] </code></pre> <p>It used to work as this:</p> <pre><code>$videos[0]-&gt;id </code></pre> <p>But now I get an error "Cannot use object of type stdClass as array..." on the line shown above. Possibly due to a PHP upgrade.</p> <p>So how do I get to that first ID without looping? Is it possible?</p> <p>Thanks!</p>
19,921,022
8
0
null
2012-02-28 00:10:58.417 UTC
8
2022-07-26 22:32:05.973 UTC
null
null
null
null
503,546
null
1
78
php|object|multidimensional-array
124,433
<p><strong>Update PHP 7.4</strong></p> <p>Curly brace access syntax is deprecated since PHP 7.4</p> <p><strong>Update 2019</strong></p> <blockquote> <p>Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.</p> </blockquote> <p>Simply iterate its using {}</p> <p>Example:</p> <pre><code>$videos{0}-&gt;id </code></pre> <p>This way your object is not destroyed and you can easily iterate through object.</p> <p>For PHP 5.6 and below use this</p> <pre><code>$videos{0}['id'] </code></pre>
30,912,826
Expose all IDs when using Spring Data Rest
<p>I'd like to expose all IDs using a Spring Rest interface.</p> <p>I know that per default an ID like this will not be exposed via the rest interface:</p> <pre><code> @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private Long id; </code></pre> <p>I'm aware that I can use this to expose the ID for <code>User</code>:</p> <pre><code>@Configuration public class RepositoryConfig extends RepositoryRestMvcConfiguration { @Override protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(User.class); } } </code></pre> <p>But is there an easy way to expose all IDs without manually maintaining a list in this <code>configureRepositoryRestConfiguration</code> method?</p>
33,171,702
14
1
null
2015-06-18 10:26:57.777 UTC
10
2022-05-20 18:42:36.897 UTC
2019-03-10 01:05:04.9 UTC
null
4,071,001
null
4,940,680
null
1
38
java|spring|rest|spring-mvc|spring-data-rest
30,526
<p>Currently, there is no way to do this provided by SDR. <a href="https://jira.spring.io/browse/DATAREST-161" rel="noreferrer">This issue</a> on the SDR Jira tracker gives some explanation as to why this isn't (and perhaps shouldn't) be possible.</p> <p>The argument is basically that since the IDs are already contained within the <code>self</code> links in the response, you don't need to expose them as properties of the object itself.</p> <p>That said, you may be able to use reflection to retrieve all classes that have a <code>javax.persistence.Id</code> annotation and then call <code>RepositoryRestConfiguration#exposeIdsFor(Class&lt;?&gt;... domainTypes)</code>.</p>
34,235,530
How to get high and low envelope of a signal
<p>I have quite a noisy data, and I am trying to work out a high and low envelope to the signal. It is kind of like this example in MATLAB:</p> <p><a href="http://uk.mathworks.com/help/signal/examples/signal-smoothing.html" rel="noreferrer">http://uk.mathworks.com/help/signal/examples/signal-smoothing.html</a></p> <p>in &quot;Extracting Peak Envelope&quot;. Is there a similar function in Python that can do that? My entire project has been written in Python, worst case scenario I can extract my numpy array and throw it into MATLAB and use that example. But I prefer the look of matplotlib... and really cba doing all of those I/O between MATLAB and Python...</p> <p>Thanks,</p>
34,245,942
6
2
null
2015-12-12 02:22:32.94 UTC
16
2021-10-01 23:22:17.193 UTC
2021-10-01 23:22:17.193 UTC
null
7,758,804
user5224720
null
null
1
20
python|matlab|numpy|matplotlib|signal-processing
40,091
<blockquote> <p>Is there a similar function in Python that can do that?</p> </blockquote> <p>As far as I am aware there is no such function in Numpy / Scipy / Python. However, it is not that difficult to create one. The general idea is as follows:</p> <p>Given a vector of values (s):</p> <ol> <li>Find the location of peaks of (s). Let's call them (u)</li> <li>Find the location of troughs of s. Let's call them (l).</li> <li>Fit a model to the (u) value pairs. Let's call it (u_p)</li> <li>Fit a model to the (l) value pairs. Let's call it (l_p)</li> <li>Evaluate (u_p) over the domain of (s) to get the interpolated values of the upper envelope. (Let's call them (q_u))</li> <li>Evaluate (l_p) over the domain of (s) to get the interpolated values of the lower envelope. (Let's call them (q_l)).</li> </ol> <p>As you can see, it is the sequence of three steps (Find location, fit model, evaluate model) but applied twice, once for the upper part of the envelope and one for the lower.</p> <p>To collect the "peaks" of (s) you need to locate points where the slope of (s) changes from positive to negative and to collect the "troughs" of (s) you need to locate the points where the slope of (s) changes from negative to positive. </p> <p>A peak example: s = [4,5,4] 5-4 is positive 4-5 is negative</p> <p>A trough example: s = [5,4,5] 4-5 is negative 5-4 is positive</p> <p>Here is an example script to get you started with plenty of inline comments:</p> <pre><code>from numpy import array, sign, zeros from scipy.interpolate import interp1d from matplotlib.pyplot import plot,show,hold,grid s = array([1,4,3,5,3,2,4,3,4,5,4,3,2,5,6,7,8,7,8]) #This is your noisy vector of values. q_u = zeros(s.shape) q_l = zeros(s.shape) #Prepend the first value of (s) to the interpolating values. This forces the model to use the same starting point for both the upper and lower envelope models. u_x = [0,] u_y = [s[0],] l_x = [0,] l_y = [s[0],] #Detect peaks and troughs and mark their location in u_x,u_y,l_x,l_y respectively. for k in xrange(1,len(s)-1): if (sign(s[k]-s[k-1])==1) and (sign(s[k]-s[k+1])==1): u_x.append(k) u_y.append(s[k]) if (sign(s[k]-s[k-1])==-1) and ((sign(s[k]-s[k+1]))==-1): l_x.append(k) l_y.append(s[k]) #Append the last value of (s) to the interpolating values. This forces the model to use the same ending point for both the upper and lower envelope models. u_x.append(len(s)-1) u_y.append(s[-1]) l_x.append(len(s)-1) l_y.append(s[-1]) #Fit suitable models to the data. Here I am using cubic splines, similarly to the MATLAB example given in the question. u_p = interp1d(u_x,u_y, kind = 'cubic',bounds_error = False, fill_value=0.0) l_p = interp1d(l_x,l_y,kind = 'cubic',bounds_error = False, fill_value=0.0) #Evaluate each model over the domain of (s) for k in xrange(0,len(s)): q_u[k] = u_p(k) q_l[k] = l_p(k) #Plot everything plot(s);hold(True);plot(q_u,'r');plot(q_l,'g');grid(True);show() </code></pre> <p>This produces this output:</p> <p><a href="https://i.stack.imgur.com/DYsVk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DYsVk.png" alt="Indicative output"></a></p> <p>Points for further improvement:</p> <ol> <li><p>The above code does not <em>filter</em> peaks or troughs that may be occuring closer than some threshold "distance" (Tl) (e.g. time). This is similar to the second parameter of <code>envelope</code>. It is easy to add it though by examining the differences between consecutive values of <code>u_x,u_y</code>.</p></li> <li><p>However, a quick improvement over the point mentioned previously is to lowpass filter your data with a moving average filter <strong>BEFORE</strong> interpolating an upper and lower envelope functions. You can do this easily by convolving your (s) with a suitable moving average filter. Without going to a great detail here (can do if required), to produce a moving average filter that operates over N consecutive samples, you would do something like this: <code>s_filtered = numpy.convolve(s, numpy.ones((1,N))/float(N)</code>. The higher the (N) the smoother your data will appear. Please note however that this will shift your (s) values (N/2) samples to the right (in <code>s_filtered</code>) due to something that is called <a href="https://en.wikipedia.org/wiki/Group_delay_and_phase_delay" rel="noreferrer">group delay</a> of the smoothing filter. For more information about the moving average, please see <a href="https://en.wikipedia.org/wiki/Moving_average" rel="noreferrer">this link</a>.</p></li> </ol> <p>Hope this helps. </p> <p>(Happy to ammend the response if more information about the original application is provided. Perhaps the data can be pre-processed in a more suitable way (?) )</p>
10,738,647
How to get all post parameters in Symfony2?
<p>I want to get all post parameters of a <a href="http://symfony.com/" rel="noreferrer">symfony</a> Form.</p> <p>I used :</p> <pre><code>$all_parameter = $this-&gt;get('request')-&gt;getParameterHolder()-&gt;getAll(); </code></pre> <p>and I get this error </p> <pre><code>Fatal error: Call to undefined method Symfony\Component\HttpFoundation\Request::getParameterHolder() in /Library/WebServer/Documents/Symfony/src/Uae/PortailBundle/Controller/NoteController.php on line 95 </code></pre>
10,739,138
2
1
null
2012-05-24 13:39:38.503 UTC
0
2018-06-17 16:15:27.48 UTC
2018-06-17 16:15:27.48 UTC
null
1,414,828
null
1,414,828
null
1
31
php|symfony
60,374
<pre><code>$this-&gt;get('request')-&gt;request-&gt;all() </code></pre>
7,086,920
Removing logging with ProGuard doesn't remove the strings being logged
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/6009078/removing-unused-strings-during-proguard-optimisation">Removing unused strings during ProGuard optimisation</a> </p> </blockquote> <p>I have an Android application with dozens of logging statements. I'd prefer they wouldn't appear in the release version, so I used Proguard with something like this in the <code>proguard.cfg</code> file:</p> <pre><code>-assumenosideeffects class android.util.Log { public static *** d(...); } </code></pre> <p>But the problem is that there are a lot of <code>Log.d("something is " + something)</code>, and although the <code>Log.d()</code> statement is being removed from the bytecode, <strong>the strings are still there</strong>.</p> <p>So, following <a href="https://stackoverflow.com/questions/6009078/removing-unused-strings-during-proguard-optimisation/6023505#6023505">this</a> answer, I created a simple wrapper class, something along the lines of:</p> <pre><code>public class MyLogger { public static void d(Object... msgs) { StringBuilder log = new StringBuilder(); for(Object msg : msgs) { log.append(msg.toString()); } Log.d(TAG, log.toString()); } } </code></pre> <p>Then I edited my <code>proguard.cfg</code>:</p> <pre><code>-assumenosideeffects class my.package.MyLogger { public static *** d(...); } </code></pre> <p><strong>But the strings are still found in the generated bytecode!</strong></p> <p>Other than this, I am using the standard <code>proguard.cfg</code> provided by the Android SDK. Am I doing something wrong?</p> <hr> <p><strong>Edit</strong>: after examining the generated bytecode, I saw that the strings were there, but they were not being appended one to another, as I thought. They were being <strong>stored in an array</strong>. Why? To pass them as variable parameters to my method. It looks like ProGuard doesn't like that, so I modified my logger class like this:</p> <pre><code>public static void d(Object a) { log(a); } public static void d(Object a, Object b) { log(a, b); } (... I had to put like seven d() methods ...) private static void log(Object... msgs) { (same as before) } </code></pre> <p>It's ugly, but now the strings are <strong>nowhere</strong> in the bytecode.</p> <p>Is this some kind of bug/limitation of ProGuard? Or is it just me not understanding how it works?</p>
7,100,548
2
3
null
2011-08-17 01:09:13.85 UTC
9
2012-09-01 07:18:04.053 UTC
2017-05-23 12:16:26.847 UTC
null
-1
null
126,603
null
1
21
android|proguard
9,362
<p>Your solution with different methods for different numbers of arguments is probably the most convenient one. A single method with a variable number of arguments would be nicer, but the current version of ProGuard is not smart enough to remove all the unused code.</p> <p>The java compiler compiles a variable number of arguments as a single array argument. On the invocation side, this means creating an array of the right size, filling out the elements, and passing it to the method. ProGuard sees that the array is being created and then being used to store elements in it. It doesn't realize (yet) that it then isn't used for actual useful operations, with the method invocation being gone. As a result, the array creation and initialization are preserved.</p> <p>It's a good practice to check the processed code if you're expecting some particular optimization.</p>
7,560,285
Check if a field is final in java using reflection
<p>I'm writing a class, which at some point has to have all its <code>Field</code>s assigned from another item of this class.</p> <p>I did it through reflection:</p> <pre><code>for (Field f:pg.getClass().getDeclaredFields()) { f.set(this, f.get(pg)); } </code></pre> <p>The problem is, that this class contains a <code>Field</code>, which is <code>final</code>. I could skip it by name, but to me that seems not elegant at all.</p> <p>What's the best way to check if a <code>Field</code> is <code>final</code> in java using reflection?</p>
7,560,325
2
0
null
2011-09-26 19:33:32.473 UTC
3
2019-03-21 00:04:46.77 UTC
2019-03-21 00:04:46.77 UTC
null
2,361,308
null
847,200
null
1
50
java
20,794
<p>The best and only one way is: <code>Modifier.isFinal(f.getModifiers())</code></p> <p>Reference:</p> <ul> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#getModifiers%28%29" rel="noreferrer"><code>Field.getModifiers</code></a></li> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Modifier.html#isFinal%28int%29" rel="noreferrer"><code>Modifier.isFinal</code></a></li> </ul>
36,917,030
Expand and Collapse tableview cells
<p>I'm able to expand and collapse cells but i wanna call functions (expand and collapse) inside UITableViewCell to change button title.</p> <p><a href="https://i.stack.imgur.com/U3alQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U3alQ.png" alt="Iphone 5"></a></p> <pre> import UIKit class MyTicketsTableViewController: UITableViewController { var selectedIndexPath: NSIndexPath? var extraHeight: CGFloat = 100 override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTicketsTableViewCell return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if(selectedIndexPath != nil && indexPath.compare(selectedIndexPath!) == NSComparisonResult.OrderedSame) { return 230 + extraHeight } return 230.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if(selectedIndexPath == indexPath) { selectedIndexPath = nil } else { selectedIndexPath = indexPath } tableView.beginUpdates() tableView.endUpdates() } } </pre> <pre> import UIKit class MyTicketsTableViewCell: UITableViewCell { @IBOutlet weak var expandButton: ExpandButton! @IBOutlet weak var detailsHeightConstraint: NSLayoutConstraint! var defaultHeight: CGFloat! override func awakeFromNib() { super.awakeFromNib() defaultHeight = detailsHeightConstraint.constant expandButton.button.setTitle("TAP FOR DETAILS", forState: .Normal) detailsHeightConstraint.constant = 30 } func expand() { UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { self.expandButton.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 0.99)) self.detailsHeightConstraint.constant = self.defaultHeight self.layoutIfNeeded() }, completion: { finished in self.expandButton.button.setTitle("CLOSE", forState: .Normal) }) } func collapse() { UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveLinear, animations: { self.expandButton.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 0.0)) self.detailsHeightConstraint.constant = CGFloat(30.0) self.layoutIfNeeded() }, completion: { finished in self.expandButton.button.setTitle("TAP FOR DETAILS", forState: .Normal) }) } } </pre>
36,917,151
4
2
null
2016-04-28 14:02:32.14 UTC
8
2019-11-08 19:57:54.8 UTC
2016-04-28 14:12:04.427 UTC
null
1,557,387
null
1,557,387
null
1
35
ios|swift|uitableview
30,921
<p>If you want the cell to get physically bigger, then where you have your store <code>IndexPath</code>, in <code>heightForRow:</code> use:</p> <pre><code>override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -&gt; CGFloat { if selectedIndexPath == indexPath { return 230 + extraHeight } return 230.0 } </code></pre> <p>Then when you want to expand one in the didSelectRow:</p> <pre><code>selectedIndexPath = indexPath tableView.beginUpdates tableView.endUpdates </code></pre> <p><strong>Edit</strong></p> <p>This will make the cells animate themselves getting bigger, you dont need the extra animation blocks in the cell.</p> <p><strong>Edit 2</strong> </p> <pre><code> override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if(selectedIndexPath == indexPath) { selectedIndexPath = nil if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MyTicketsTableViewCell { cell.collapse() } if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:indexPath.row+1, section: indexPath.section) as? MyTicketsTableViewCell { cell.collapse() } } else { selectedIndexPath = indexPath if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MyTicketsTableViewCell { cell.expand() } if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:indexPath.row+1, section: indexPath.section) as? MyTicketsTableViewCell { cell.expand() } } tableView.beginUpdates() tableView.endUpdates() } </code></pre>
17,884,277
How to implement a DrawerLayout with a visible handle
<p>I have successfully implemented a NavigationDrawer for my application. </p> <p>My app displays a drawer that opens on the left of the screen.</p> <p>My problem is I need to add a button on the left. That button might be clicked or swiped to open the left drawer. That I can do.</p> <p>But the button is supposed to <strong>look like</strong> it's a part of the drawer that would overflow into the screen.</p> <p>That means the button should slide simultaneously as the drawer opens and closes.</p> <p><strong>CLOSED STATE :</strong> </p> <p><img src="https://i.stack.imgur.com/KJWwY.png" alt="enter image description here"></p> <p><strong>OPENING STATE</strong></p> <p><img src="https://i.stack.imgur.com/JixzT.png" alt="enter image description here"></p> <p>I tried adding the button into the left drawer's layout, but it seems you can't make stuff appear outside of its boundaries, and the drawer will always get completely hidden when you close it.</p> <p>Now I'm trying adding it to add a button to the main DrawerLayout and make it align to the right of the left drawer... But no luck... It looks like a DrawerLayout can't have more than two children...</p> <p>Any help will be appreciated.</p> <p>I'm using the Support library (v4) </p> <p>[EDIT] And I am supporting API level 8... So can't use <code>ImageView.setTranslationX</code> or <code>View.OnAttachStateChangeListener</code></p>
18,438,880
2
2
null
2013-07-26 14:38:28.703 UTC
13
2015-11-25 09:33:05.653 UTC
2013-08-20 07:46:12.077 UTC
null
1,491,212
null
1,491,212
null
1
32
android|android-layout|navigation-drawer|drawerlayout
13,437
<p>I found a way of doing this pretty easily thanks to the Aniqroid library written by Mobistry (SO pseudo)</p> <p>I use the SlidingTray class which is a copy of android SlidingDrawer but lets you position the drawer to any corner of the screen.</p> <p>I declared the element via xml</p> <pre><code>&lt;com.sileria.android.view.SlidingTray xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer" android:layout_width="match_parent" android:layout_height="270dp" android:content="@+id/content" android:handle="@+id/handle" &gt; &lt;ImageView android:id="@+id/handle" android:layout_width="320dp" android:layout_height="24dp" android:background="@drawable/tray_btn" /&gt; &lt;LinearLayout android:id="@+id/content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="fill_vertical" android:orientation="vertical" &gt; &lt;/LinearLayout&gt; &lt;/com.sileria.android.view.SlidingTray&gt; </code></pre> <p>And just had to call</p> <pre><code>Kit.init(this); </code></pre> <p>in my main <code>Activity</code> before inflating the layout.</p> <p>I thank aniqroid devs!</p> <p><a href="https://code.google.com/p/aniqroid/" rel="nofollow">https://code.google.com/p/aniqroid/</a></p>
3,715,484
What is the difference between the JSP and the JSTL?
<p>I have learned about servlets and the JSP's before, but I don't know what is the JSTL and the difference between the JSP and the JSTL. </p>
3,715,525
1
2
null
2010-09-15 07:22:45.95 UTC
3
2016-01-20 09:42:37.063 UTC
2014-10-14 18:41:05.59 UTC
null
643,483
null
387,298
null
1
35
jsp|jstl
29,132
<p>JSP is a technology similar to ASP that let you embed Java code inside HTML pages. This code can be inserted by means of &lt;% %> blocks or by means of JSP tags. The last option is generally preferred over the first one, since tags adapt better to own tag representation form of HTML, so your pages will look more readable. JSP lets you even define your own tags (you must write the code that actually implement the logic of those tags in Java). <a href="http://www.oracle.com/technetwork/java/index-jsp-135995.html" rel="noreferrer">JSTL</a> is just a standard tag library provided by Sun (well, now Oracle) to carry out common tasks (such as looping, formatting, etc.).</p>
41,194,021
How can I show progress for a long-running Ansible task?
<p>I have a some Ansible tasks that perform unfortunately long operations - things like running an synchronization operation with an S3 folder. It's not always clear if they're progressing, or just stuck (or the ssh connection has died), so it would be nice to have some sort of progress output displayed. If the command's stdout/stderr was directly displayed, I'd see that, but Ansible captures the output.</p> <p>Piping output back <a href="https://github.com/ansible/ansible/issues/3887" rel="noreferrer">is a difficult problem for Ansible to solve in its current form</a>. But are there any Ansible tricks I can use to provide some sort of indication that things are still moving?</p> <p>Current ticket is <a href="https://github.com/ansible/ansible/issues/4870" rel="noreferrer">https://github.com/ansible/ansible/issues/4870</a></p>
54,420,049
4
1
null
2016-12-16 23:54:58.653 UTC
20
2021-09-25 08:52:29.59 UTC
2017-06-01 11:51:42.713 UTC
null
99,834
null
120,999
null
1
54
ansible|ansible-2.x
49,774
<p>Ansible has since implemented the following:</p> <pre><code>--- # Requires ansible 1.8+ - name: 'YUM - async task' yum: name: docker-io state: installed async: 1000 poll: 0 register: yum_sleeper - name: 'YUM - check on async task' async_status: jid: "{{ yum_sleeper.ansible_job_id }}" register: job_result until: job_result.finished retries: 30 </code></pre> <p>For further information, see the <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html" rel="noreferrer">official documentation</a> on the topic (make sure you're selecting your version of Ansible).</p>
41,083,869
double square brackets side by side in python
<p>I'm completely new at Python and have an assignment coming up. The professor has asked that we look at examples of users coding Pascal's Triangle in Python for something that will be 'similar'. </p> <p>I managed to find several ways to code it but I found several people using some code that I don't understand. </p> <p>Essentially, I'm looking to find out what it means (or does) when you see a list or variable that has two square brackets side by side. Example code:</p> <pre><code>pascalsTriangle = [[1]] rows = int(input("Number of rows:")) print(pascalsTriangle[0]) for i in range(1,rows+1): pascalsTriangle.append([1]) for j in range(len(pascalsTriangle[i-1])-1): pascalsTriangle[i].append(pascalsTriangle[i-1][j]+ pascalsTriangle[i-1][j+1]) pascalsTriangle[i].append(1) print(pascalsTriangle[i]) </code></pre> <p>You'll see that line 7 has this:</p> <pre><code>pascalsTriangle[i].append(pascalsTriangle[i-1][j]+pascalsTriangle[i-1][j+1]) </code></pre> <p>I know that square brackets are lists. I know that square brackets within square brackets are lists within/of lists. Can anyone describe what a square bracket next to a square bracket is doing?</p>
41,083,943
2
2
null
2016-12-11 07:14:12.67 UTC
5
2021-09-02 18:43:06.633 UTC
2016-12-11 20:21:31.927 UTC
null
51,242
null
7,025,873
null
1
14
python|brackets
41,149
<p>If you have a list</p> <pre><code>l = ["foo", "bar", "buz"] </code></pre> <p>Then l[0] is "foo", l[1] is "bar", l[2] is buz.</p> <p>Similarly you could have a list in it instead of strings.</p> <pre><code>l = [ [1,2,3], "bar", "buz"] </code></pre> <p>Now l[0] is [1,2,3]. </p> <p>What if you want to access the second item in that list of numbers? You could say:</p> <pre><code>l[0][1] </code></pre> <p>l[0] first gets you the list, then [1] picks out the second number in it. That's why you have "square bracket next to square bracket".</p>
18,557,275
How to locate and insert a value in a text box (input) using Python Selenium?
<p>I have the following HTML structure and I am trying to use Selenium to enter a value of <code>NUM</code>:</p> <pre><code>&lt;div class=&quot;MY_HEADING_A&quot;&gt; &lt;div class=&quot;TitleA&quot;&gt;My title&lt;/div&gt; &lt;div class=&quot;Foobar&quot;&gt;&lt;/div&gt; &lt;div class=&quot;PageFrame&quot; area=&quot;W&quot;&gt; &lt;span class=&quot;PageText&quot;&gt;PAGE &lt;input id=&quot;a1&quot; type=&quot;txt&quot; NUM=&quot;&quot; /&gt; of &lt;span id=&quot;MAX&quot;&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>Here is the code I have written:</p> <pre><code>head = driver.find_element_by_class_name(&quot;MY_HEADING_A&quot;) frame_elem = head.find_element_by_class_name(&quot;PageText&quot;) # Following is a pseudo code. # Basically I need to enter a value of 1, 2, 3 etc in the textbox field (NUM) # and then hit RETURN key. ## txt = frame_elem.find_element_by_name(&quot;NUM&quot;) ## txt.send_keys(Key.4) </code></pre> <p>How to get this element and enter a value‎‎‎‎‎‎‎? ‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎</p>
18,558,014
2
0
null
2013-09-01 09:59:01.817 UTC
32
2022-03-17 13:56:13.317 UTC
2020-12-16 05:42:01.573 UTC
null
11,744,920
null
243,708
null
1
112
python|python-2.7|selenium-webdriver|form-submit|html-input
244,267
<p>Assuming your page is available under "<a href="http://example.com">http://example.com</a>"</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://example.com") </code></pre> <p>Select element by id:</p> <pre><code>inputElement = driver.find_element_by_id("a1") inputElement.send_keys('1') </code></pre> <p>Now you can simulate hitting ENTER:</p> <pre><code>inputElement.send_keys(Keys.ENTER) </code></pre> <p>or if it is a form you can submit:</p> <pre><code>inputElement.submit() </code></pre>
1,639,338
Why does returning false in the keydown callback does not stop the button click event?
<p>I have a button and the following javascript routine.</p> <pre><code>$("button").keydown( function(key) { switch(key.keyCode) { case 32: //space return false; } } ); </code></pre> <p>as I understood it, the <code>return false;</code> would stop the keypress from being processed. So <code>$("button").click();</code> would not be called. For other keyCodes, this works as expected. For example, if I intercept<code>40</code>, which is the down button, the page is not scrolling.</p> <p>I noticed this behavior in Firefox.</p> <p>Why does the <code>return false;</code> does not stop the button click event on space? What does the javascript spec say about this?</p>
1,648,854
3
6
null
2009-10-28 18:53:47.45 UTC
4
2020-08-11 10:22:32.373 UTC
2018-08-02 11:32:37.383 UTC
null
6,397,155
null
174,896
null
1
15
javascript|jquery|button|keyboard
41,288
<p>Hope this answers your question:</p> <pre><code>&lt;input type="button" value="Press" onkeydown="doOtherStuff(); return false;"&gt; </code></pre> <p><code>return false;</code> successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML. This behaviour is not formally specified anywhere as far as I know.</p> <p>If you instead set an event via an event handler property on the DOM element (e.g. <code>button.onkeydown = function(evt) {...}</code>) or using <code>addEventListener</code>/<code>attachEvent</code> (e.g. <code>button.addEventListener("keydown", function(evt) {...}, false)</code>) then just returning <code>false</code> from that function does not work in every browser and you need to do the <code>returnValue</code> and <code>preventDefault()</code> stuff from my other answer. <code>preventDefault</code> is specified in the <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation" rel="noreferrer">DOM 2 spec</a> and is implemented by most mainstream modern browsers. <code>returnValue</code> is IE-specific. </p>
2,147,299
When to use kernel threads vs workqueues in the linux kernel
<p>There are many ways to schedule work in the linux kernel: timers, tasklets, work queues, and kernel threads. What are the guidelines for when to use one vs another? </p> <p>There are the obvious factors: timer functions and tasklets cannot sleep, so they cannot wait on mutexes, condition variables, etc.</p> <p>What are the other factors in choosing which mechanism to us in a driver? </p> <p>Which are the preferred mechanisms?</p>
2,147,416
3
0
null
2010-01-27 13:50:26.057 UTC
31
2021-06-03 08:05:52.567 UTC
null
null
null
null
230,925
null
1
35
linux|linux-kernel
28,783
<p>As you said, it depends on the task at hand:</p> <p>Work queues defer work into a kernel thread - your work will always run in process context. They are schedulable and can therefore sleep.</p> <p>Normally, there is no debate between work queues or sotftirqs/tasklets; if the deferred work needs to sleep, work queues are used, otherwise softirqs or tasklets are used. Tasklets are also more suitable for interrupt handling (they are given certain assurances such as: a tasklet is never ran later than on the next tick, it's always serialized with regard to itself, etc.).</p> <p>Kernel timers are good when you know exactly when you want something to happen, and do not want to interrupt/block a process in the meantime. They run outside process context, and they are also asynchronous with regard to other code, so they're the source of race conditions if you're not careful.</p> <p>Hope this helps.</p>
19,720,646
Named module vs Unnamed module in RequireJS
<p>We can create a module in requireJS by giving it a name:</p> <pre><code>define("name",[dep],function(dep) { // module definition }); </code></pre> <p>or we can create one excluding the name:</p> <pre><code>define([dep],function(dep) { // module definition }); </code></pre> <p>Which is the better way to create a module? I know RequireJS recommends to avoid assigning module names.</p> <p>But I want to know in what scenarios we do and do not have to give a module a name. Does this affect usage? What are the pros and cons of each way?</p>
19,725,136
2
0
null
2013-11-01 04:10:03.543 UTC
5
2017-05-12 03:26:32.01 UTC
2017-05-12 03:26:32.01 UTC
null
552,067
null
1,627,777
null
1
37
javascript|requirejs
12,794
<p>This is what the requirejs <a href="http://requirejs.org/docs/api.html#modulename">documentation</a> says on the topic of named modules:</p> <blockquote> <p>These are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.</p> </blockquote> <p>But let's say you <strong>want</strong> your module to have a single well-known name that allows always requiring it in the same way from any other module. Do you then need to use the <code>define</code> call with a name? Not at all. You can use <a href="http://requirejs.org/docs/api.html#config-paths"><code>paths</code></a> in your configuration:</p> <pre><code>paths: { 'jquery': 'external/jquery-1.9.1', 'bootstrap': 'external/bootstrap/js/bootstrap.min', 'log4javascript': 'external/log4javascript', 'jquery.bootstrap-growl': 'external/jquery.bootstrap-growl', 'font-awesome': 'external/font-awesome' }, </code></pre> <p>With this configuration, jQuery can be required as <code>"jquery"</code>, Twitter Bootstrap as <code>"bootstrap"</code>, etc. The best practice is to leave calling <code>define</code> with a name to the <a href="http://requirejs.org/docs/optimization.html">optimizer</a>.</p>
568,995
Best way to defend against mysql injection and cross site scripting
<p>At the moment, I apply a 'throw everything at the wall and see what sticks' method of stopping the aforementioned issues. Below is the function I have cobbled together:</p> <pre><code>function madSafety($string) { $string = mysql_real_escape_string($string); $string = stripslashes($string); $string = strip_tags($string); return $string; } </code></pre> <p>However, I am convinced that there is a better way to do this. I am using FILTER_ SANITIZE_STRING and this doesn't appear to to totally secure. </p> <p>I guess I am asking, which methods do you guys employ and how successful are they? Thanks</p>
569,113
4
2
null
2009-02-20 10:11:36.497 UTC
19
2015-08-23 20:16:39.65 UTC
2009-02-20 10:15:05.803 UTC
Assaf
11,208
Drew
31,677
null
1
15
php|sql|security|xss
15,217
<p>Just doing a lot of stuff that you don't really understand, is not going to help you. You need to understand what injection attacks are and exactly how and where you should do what.</p> <p>In bullet points:</p> <ul> <li><a href="http://www.php.net/manual/en/security.magicquotes.disabling.php" rel="nofollow noreferrer">Disable magic quotes</a>. They are an inadequate solution, and they confuse matters.</li> <li>Never embed strings directly in SQL. Use bound parameters, or escape (using <code>mysql_real_escape_string</code>).</li> <li><strong>Don't</strong> unescape (eg. <code>stripslashes</code>) when you retrieve data from the database.</li> <li>When you embed strings in html (Eg. when you <code>echo</code>), you should default to escape the string (Using <code>htmlentities</code> with <code>ENT_QUOTES</code>).</li> <li>If you need to embed html-strings in html, you must consider the source of the string. If it's untrusted, you should pipe it through a filter. <code>strip_tags</code> is in theory what you should use, but it's flawed; Use <a href="http://htmlpurifier.org/" rel="nofollow noreferrer">HtmlPurifier</a> instead.</li> </ul> <p>See also: <a href="https://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php">What&#39;s the best method for sanitizing user input with PHP?</a></p>
246,477
Should you make a self-referencing table column a foreign key?
<p>For example to create a hierarchy of categories you use a column 'parent_id', which points to another category in the same table.</p> <p>Should this be a foreign key? What would the dis/advantages be?</p>
246,487
4
0
null
2008-10-29 11:33:58.737 UTC
4
2015-11-21 11:39:19.607 UTC
null
null
null
wdm
4,196
null
1
36
database|database-design|foreign-keys
26,426
<p>Yes. Ensures that you don't have an orphan (entry with no parent), and depending on usage, if you define a cascading delete, when a parent is deleted, all its children will also be deleted.</p> <p>Disadvantage would be a slight performance hit just like any other foreign key.</p>
1,274,168
Drop Shadow on UITextField text
<p>Is it possible to add a shadow to the text in a <code>UITextField</code>?</p>
4,049,228
4
0
null
2009-08-13 19:44:45.927 UTC
36
2014-09-23 09:03:32.39 UTC
2011-08-22 18:47:39.247 UTC
null
632,736
null
112,521
null
1
55
iphone|objective-c|uikit|uitextfield|shadow
56,442
<p>As of 3.2, you can use the CALayer shadow properties.</p> <pre><code>_textField.layer.shadowOpacity = 1.0; _textField.layer.shadowRadius = 0.0; _textField.layer.shadowColor = [UIColor blackColor].CGColor; _textField.layer.shadowOffset = CGSizeMake(0.0, -1.0); </code></pre>
1,042,099
How do I convert Int/Decimal to float in C#?
<p>How does one convert from an int or a decimal to a float in C#?</p> <p>I need to use a float for a third-party control, but I don't use them in my code, and I'm not sure how to end up with a float.</p>
1,042,104
4
0
null
2009-06-25 03:54:43.07 UTC
7
2017-04-03 16:36:11.717 UTC
2017-04-03 16:34:56.68 UTC
null
63,550
null
3,442
null
1
78
c#|casting|floating-point
322,117
<p>You can just do a cast</p> <pre><code>int val1 = 1; float val2 = (float)val1; </code></pre> <p>or</p> <pre><code>decimal val3 = 3; float val4 = (float)val3; </code></pre>
33,851,692
Golang bad file descriptor
<p>I am getting a bad file descriptor when trying to append to a logging file within my go routine. </p> <p><code>write ./log.log: bad file descriptor</code></p> <p>The file exists and has 666 for permissions. At first I thought well maybe it is because each one of them is trying to open the file at the same time. I implemented a mutex to try and avoid that but got the same issue so I removed it. </p> <pre><code>logCh := make(chan string, 150) go func() { for { msg, ok := &lt;-logCh if ok { if f, err := os.OpenFile("./log.log", os.O_APPEND, os.ModeAppend); err != nil { panic(err) } else { logTime := time.Now().Format(time.RFC3339) if _, err := f.WriteString(logTime + " - " + msg); err != nil { fmt.Print(err) } f.Close() } } else { fmt.Print("Channel closed! \n") break } } }() </code></pre>
33,852,107
3
1
null
2015-11-22 04:46:02.31 UTC
3
2020-02-20 14:49:04.6 UTC
null
null
null
null
2,958,455
null
1
43
go|file-descriptor
41,317
<p>You need to add the <code>O_WRONLY</code> flag :</p> <pre><code>if f, err := os.OpenFile("./log.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { /*[...]*/ } </code></pre> <p>To explain, here is the linux documentation for <code>open</code>: <a href="http://man7.org/linux/man-pages/man2/openat.2.html" rel="noreferrer">http://man7.org/linux/man-pages/man2/openat.2.html</a> :</p> <blockquote> <p>The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read- only, write-only, or read/write, respectively.</p> </blockquote> <p>If you check <a href="https://github.com/golang/go/blob/900ebcfe4d592486dd5bc50f5e8101ba65e32948/src/syscall/zerrors_linux_amd64.go#L660" rel="noreferrer">/usr/local/go/src/syscall/zerrors_linux_amd64.go:660</a>, you can see that:</p> <pre><code>O_RDONLY = 0x0 O_RDWR = 0x2 O_WRONLY = 0x1 </code></pre> <p>So by default you get a read-only file descriptor.</p>
21,558,589
Neo4j sharding aspect
<p>I was looking on the scalability of Neo4j, and read a document written by David Montag in January 2013.</p> <p>Concerning the sharding aspect, he said the 1st release of 2014 would come with a first solution.</p> <p>Does anyone know if it was done or its status if not?</p> <p>Thanks!</p>
21,566,766
2
0
null
2014-02-04 16:55:39.317 UTC
9
2017-12-28 18:43:32.397 UTC
null
null
null
null
3,128,170
null
1
28
neo4j|scalability
14,202
<p><strong>Disclosure:</strong> I'm working as VP Product for Neo Technology, the sponsor of the Neo4j open source graph database.</p> <p>Now that we've just released Neo4j 2.0 (actually 2.0.1 today!) we are embarking on a 2.1 release that is mostly oriented around (even more) performance &amp; scalability. This will increase the upper limits of the graph to an effectively unlimited number of entities, and improve various other things.</p> <p>Let me set some context first, and then answer your question.</p> <p>As you probably saw from the paper, Neo4j's current horizontal-scaling architecture allows read scaling, with writes all going to master and fanning out. This gets you effectively unlimited read scaling, and into the tens of thousands of writes per second. </p> <p>Practically speaking, there are production Neo4j customers (including Snap Interactive and Glassdoor) with around a billion people in their social graph... in all cases behind an active and heavily-hit web site, being handled by comparatively quite modest Neo4j clusters (no more than 5 instances). So that's one key feature: the Neo4j of today an incredible computational density, and so we regularly see fairly small clusters handling a substantially large production workload... with very fast response times.</p> <p>More on the current architecture can be found here: <a href="http://www.neotechnology.com/neo4j-scales-for-the-enterprise/" rel="noreferrer">www.neotechnology.com/neo4j-scales-for-the-enterprise/</a> And a list of customers (which includes companies like Wal-Mart and eBay) can be found here: <a href="http://www.neotechnology.com/customers/" rel="noreferrer">neotechnology.com/customers/</a> One of the world's largest parcel delivery carriers uses Neo4j to route all of their packages, in real time, with peaks of 3000 routing operations per second, and zero downtime. (This arguably is the world's largest and most mission-critical use of a graph database and of a NOSQL database; though unfortunately I can't say who it is.)</p> <p>So in one sense the tl;dr is that if you're not yet as big as Wal-Mart or eBay, then you're probably ok. That oversimplifies it only a bit. There is the 1% of cases where you have sustained transactional write workloads into the 100s of thousands per second. However even in those cases it's often not the right thing to load all of that data into the real-time graph. We usually advise people to do some aggregation or filtering, and bring only the more important things into the graph. Intuit gave a good talk about this. They filter a billion B2B transactions into a much smaller number of aggregate monthly transaction relationships with aggregated counts and currency amounts by direction.</p> <p>Enter sharding... Sharding has gained a lot of popularity these days. This is largely thanks to the other three categories of NOSQL, where joins are an anti-pattern. Most queries involve reading or writing just a single piece of discrete data. Just as joining is an anti-pattern for key-value stores and document databases, sharding is an anti-pattern for graph databases. What I mean by that is... the very best performance will occur when all of your data is available in memory on a single instance, because hopping back and forth all over the network whenever you're reading and writing will slow things significantly down, unless you've been really really smart about how you distribute your data... and even then. Our approach has been twofold:</p> <ol> <li><p>Do as many smart things as possible in order to support extremely high read &amp; write volumes without having to resort to sharding. This gets you the best and most predictable latency and efficiency. In other words: if we can be good enough to support your requirement without sharding, that will <em>always</em> be the best approach. The link above describes some of these tricks, including the deployment pattern that lets you shard your data in memory without having to shard it on disk (a trick we call cache-sharding). There are other tricks along similar lines, and more coming down the pike...</p></li> <li><p>Add a secondary architecture pattern into Neo4j that <em>does</em> support sharding. Why do this if sharding is best avoided? As more people find more uses for graphs, and data volumes continue to increase, we think eventually it will be an important and inevitable thing. This would allow you to run all of Facebook for example, in one Neo4j cluster (a pretty huge one)... not just the social part of the graph, which we can handle today. We've already done a lot of work on this, and have an architecture developed that we believe balances the many considerations. This is a multi-year effort, and while we could very easily release a version of Neo4j that shards naively (that would no doubt be really popular), we probably won't do that. We want to do it right, which amounts to rocket science.</p></li> </ol>
30,404,402
Oracle pl/sql script which increments number
<p>Looking for a way to create an Oracle script using the equivalent of java ++ syntax to increment a variable.</p> <p>Ie:</p> <pre><code>int id=10 DELETE MYTABLE; INSERT INTO MYTABLE(ID, VALUE) VALUES (id++, 'a value'); INSERT INTO MYTABLE(ID, VALUE) VALUES (id++, 'another value'); ... </code></pre> <p>Trying to use a variable and not a sequence so I can rerun this multiple times with the same results.</p>
30,404,447
2
0
null
2015-05-22 19:21:19.783 UTC
2
2015-05-24 01:15:09.343 UTC
null
null
null
null
47,281
null
1
6
oracle|plsql
40,311
<p>PL/SQL doesn't have the <code>++</code> syntactic sugar. You'd need to explicitly change the value of the variable.</p> <pre><code>DECLARE id integer := 10; BEGIN DELETE FROM myTable; INSERT INTO myTable( id, value ) VALUES( id, 'a value' ); id := id + 1; INSERT INTO myTable( id, value ) VALUES( id, 'another value' ); id := id + 1; ... END; </code></pre> <p>At that point, and since you want to ensure consistency, you may be better off hard-coding the <code>id</code> values just like you are hard-coding the <code>value</code> values, i.e.</p> <pre><code>BEGIN DELETE FROM myTable; INSERT INTO myTable( id, value ) VALUES( 10, 'a value' ); INSERT INTO myTable( id, value ) VALUES( 11, 'another value' ); ... END; </code></pre>
59,476,912
Testing custom hook: Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
<p>I got a custom hook which I want to test. It receives a redux store dispatch function and returns a function. In order to get the result I'm trying to do:</p> <pre><code>const { result } = renderHook(() =&gt; { useSaveAuthenticationDataToStorages(useDispatch())}); </code></pre> <p>However, I get an error:</p> <blockquote> <p>Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a </p> </blockquote> <p>It happens because of the <code>useDispatch</code> and that there is no store connected. However, I don't have any component here to wrap with a provider.. I just need to test the hook which is simply saving data to a store. </p> <p>How can I fix it?</p>
59,477,049
4
0
null
2019-12-25 09:21:30.493 UTC
5
2021-12-14 20:16:41.173 UTC
2019-12-25 09:44:57.7 UTC
null
1,164,004
null
1,164,004
null
1
23
reactjs|redux|jestjs|react-testing-library
54,933
<p>The react hooks testing library <a href="https://react-hooks-testing-library.com/usage/advanced-hooks" rel="noreferrer">docs</a> go more into depth on this. However, what we essentially are missing is the provider which we can obtain by creating a wrapper. First we declare a component which will be our provider: </p> <pre><code>import { Provider } from 'react-redux' const ReduxProvider = ({ children, reduxStore }) =&gt; ( &lt;Provider store={reduxStore}&gt;{children}&lt;/Provider&gt; ) </code></pre> <p>then in our test we call</p> <pre><code>test("...", () =&gt; { const store = configureStore(); const wrapper = ({ children }) =&gt; ( &lt;ReduxProvider reduxStore={store}&gt;{children}&lt;/ReduxProvider&gt; ); const { result } = renderHook(() =&gt; { useSaveAuthenticationDataToStorages(useDispatch()); }, { wrapper }); // ... Rest of the logic }); </code></pre>
30,369,031
Remove spurious small islands of noise in an image - Python OpenCV
<p>I am trying to get rid of background noise from some of my images. This is the unfiltered image.</p> <p><img src="https://i.stack.imgur.com/CiBlj.png" alt=""></p> <p>To filter, I used this code to generate a mask of what should remain in the image:</p> <pre><code> element = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) mask = cv2.erode(mask, element, iterations = 1) mask = cv2.dilate(mask, element, iterations = 1) mask = cv2.erode(mask, element) </code></pre> <p>With this code and when I mask out the unwanted pixels from the original image, what I get is: <img src="https://i.stack.imgur.com/0WDlX.png" alt=""></p> <p>As you can see, all the tiny dots in the middle area are gone, but a lot of those coming from the denser area are also gone. To reduce the filtering, I tried changing the second parameter of <code>getStructuringElement()</code> to be (1,1) but doing this gives me the first image as if nothing has been filtered. </p> <p>Is there any way where I can apply some filter that is between these 2 extremes?</p> <p>In addition, can anyone explain to me what exactly does <code>getStructuringElement()</code> do? What is a "structuring element"? What does it do and how does its size (the second parameter) affect the level of filtering?</p>
30,380,543
2
1
null
2015-05-21 08:59:11.493 UTC
34
2022-02-02 16:51:22.147 UTC
2017-12-15 15:10:38.72 UTC
null
3,250,829
null
4,652,826
null
1
42
python|image|opencv|image-processing|filtering
52,599
<p>A lot of your questions stem from the fact that you're not sure how morphological image processing works, but we can put your doubts to rest. You can interpret the structuring element as the "base shape" to compare to. 1 in the structuring element corresponds to a pixel that you want to look at in this shape and 0 is one you want to ignore. There are different shapes, such as rectangular (as you have figured out with <code>MORPH_RECT</code>), ellipse, circular, etc.</p> <p>As such, <code>cv2.getStructuringElement</code> returns a structuring element for you. The first parameter specifies the type you want and the second parameter specifies the size you want. In your case, you want a 2 x 2 "rectangle"... which is really a square, but that's fine.</p> <p>In a more bastardized sense, you use the structuring element and scan from left to right and top to bottom of your image and you grab pixel neighbourhoods. Each pixel neighbourhood has its centre exactly at the pixel of interest that you're looking at. The size of each pixel neighbourhood is the same size as the structuring element.</p> <h1>Erosion</h1> <p>For an erosion, you examine all of the pixels in a pixel neighbourhood that are touching the structuring element. If <strong>every non-zero pixel</strong> is touching a structuring element pixel that is 1, then the output pixel in the corresponding centre position with respect to the input is 1. If there is at least one non-zero pixel that <strong>does not</strong> touch a structuring pixel that is 1, then the output is 0. </p> <p>In terms of the rectangular structuring element, you need to make sure that every pixel in the structuring element is touching a non-zero pixel in your image for a pixel neighbourhood. If it isn't, then the output is 0, else 1. This effectively eliminates small spurious areas of noise and also decreases the area of objects slightly.</p> <p>The size factors in where the larger the rectangle, the more shrinking is performed. The size of the structuring element is a baseline where any objects that are smaller than this rectangular structuring element, you can consider them as being filtered and not appearing in the output. Basically, choosing a 1 x 1 rectangular structuring element is the same as the input image itself because that structuring element fits all pixels inside it as the pixel is the smallest representation of information possible in an image.</p> <h1>Dilation</h1> <p>Dilation is the opposite of erosion. If there is at least one non-zero pixel that touches a pixel in the structuring element that is 1, then the output is 1, else the output is 0. You can think of this as slightly enlarging object areas and making small islands bigger.</p> <p>The implications with size here is that the larger the structuring element, the larger the areas of the objects will be and the larger the isolated islands become.</p> <hr> <p>What you're doing is an erosion first followed by a dilation. This is what is known as an <strong>opening</strong> operation. The purpose of this operation is to remove small islands of noise while (trying to) maintain the areas of the larger objects in your image. The erosion removes those islands while the dilation grows back the larger objects to their original sizes.</p> <p>You follow this with an erosion again for some reason, which I can't quite understand, but that's ok.</p> <hr> <p>What I would personally do is perform a <strong>closing</strong> operation first which is a dilation followed by an erosion. Closing helps group areas that are close together into a single object. As such, you see that there are some larger areas that are close to each other that should probably be joined before we do anything else. As such, I would do a closing first, then do an <strong>opening</strong> after so that we can remove the isolated noisy areas. Take note that I'm going to make the closing structuring element size <strong>larger</strong> as I want to make sure I get nearby pixels and the opening structuring element size <strong>smaller</strong> so that I don't want to mistakenly remove any of the larger areas.</p> <p>Once you do this, I would mask out any extra information with the original image so that you leave the larger areas intact while the small islands go away.</p> <p>Instead of chaining an erosion followed by a dilation, or a dilation followed by an erosion, use <a href="http://docs.opencv.org/modules/imgproc/doc/filtering.html#morphologyex" rel="noreferrer"><code>cv2.morphologyEx</code></a>, where you can specify <code>MORPH_OPEN</code> and <code>MORPH_CLOSE</code> as the flags.</p> <p>As such, I would personally do this, assuming your image is called <code>spots.png</code>:</p> <pre><code>import cv2 import numpy as np img = cv2.imread('spots.png') img_bw = 255*(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) &gt; 5).astype('uint8') se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5)) se2 = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) mask = cv2.morphologyEx(img_bw, cv2.MORPH_CLOSE, se1) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se2) mask = np.dstack([mask, mask, mask]) / 255 out = img * mask cv2.imshow('Output', out) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('output.png', out) </code></pre> <p>The above code is pretty self-explanatory. First, I read in the image and then I convert the image to grayscale and threshold with an intensity of 5 to create a mask of what is considered object pixels. This is a rather clean image and so anything larger than 5 seems to have worked. For the morphology routines, I need to convert the image to <code>uint8</code> and scale the mask to 255. Next, we create two structuring elements - one that is a 5 x 5 rectangle for the closing operation and another that is 2 x 2 for the opening operation. I run <code>cv2.morphologyEx</code> twice for the opening and closing operations respectively on the thresholded image.</p> <p>Once I do that, I stack the mask so that it becomes a 3D matrix and divide by 255 so that it becomes a mask of <code>[0,1]</code> and then we multiply this mask with the original image so that we can grab the original pixels of the image back and maintaining what is considered a true object from the mask output.</p> <p>The rest is just for illustration. I show the image in a window, and I also save the image to a file called <code>output.png</code>, and its purpose is to show you what the image looks like in this post.</p> <p>I get this:</p> <p><img src="https://i.stack.imgur.com/1JXvU.png" alt="enter image description here"></p> <p>Bear in mind that it isn't perfect, but it's much better than how you had it before. You'll have to play around with the structuring element sizes to get something that you consider as a good output, but this is certainly enough to get you started. Good luck!</p> <hr> <h2>C++ version</h2> <p>There have been some requests to translate the code I wrote above into the C++ version using OpenCV. I have finally gotten around to writing a C++ version of the code and this has been tested on OpenCV 3.1.0. The code for this is below. As you can see, the code is very similar to that seen in the Python version. However, I used <a href="http://docs.opencv.org/3.2.0/d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876" rel="noreferrer"><code>cv::Mat::setTo</code></a> on a copy of the original image and set whatever was not part of the final mask to 0. This is the same thing as performing an element-wise multiplication in Python. </p> <pre><code>#include &lt;opencv2/opencv.hpp&gt; using namespace cv; int main(int argc, char *argv[]) { // Read in the image Mat img = imread("spots.png", CV_LOAD_IMAGE_COLOR); // Convert to black and white Mat img_bw; cvtColor(img, img_bw, COLOR_BGR2GRAY); img_bw = img_bw &gt; 5; // Define the structuring elements Mat se1 = getStructuringElement(MORPH_RECT, Size(5, 5)); Mat se2 = getStructuringElement(MORPH_RECT, Size(2, 2)); // Perform closing then opening Mat mask; morphologyEx(img_bw, mask, MORPH_CLOSE, se1); morphologyEx(mask, mask, MORPH_OPEN, se2); // Filter the output Mat out = img.clone(); out.setTo(Scalar(0), mask == 0); // Show image and save namedWindow("Output", WINDOW_NORMAL); imshow("Output", out); waitKey(0); destroyWindow("Output"); imwrite("output.png", out); } </code></pre> <p>The results should be the same as what you get in the Python version.</p>
20,787,107
Multiple media queries in css not working
<p>I have multiple queries in my stylesheet where the code<code>@media only screen and (min-width : 768px) and (max-width : 1024px) { }</code> works perfectly fine but under it I have <code>@media screen and (min-device-width : 176px) (max-device-width : 360px) {}</code> does not work.</p> <p>CSS:</p> <pre><code>@media only screen and (min-width : 768px) and (max-width : 1024px) { body {background: red; } } @media screen and (min-device-width : 176px) (max-device-width : 360px) { body {background: green; } } </code></pre>
20,787,131
4
1
null
2013-12-26 15:21:24.17 UTC
2
2019-01-14 05:27:44.523 UTC
null
null
null
null
2,798,091
null
1
9
html|css
38,412
<p>You're missing the <code>AND</code> between <code>(min-device-width : 176px) (max-device-width : 360px).</code></p> <pre><code>@media screen and (min-device-width : 176px) and (max-device-width : 360px) { body {background: green; } } </code></pre> <p>The other issues here is you are using <code>min-device-width.</code>(referring to the resolution of the device vs browser width) which is what @NoobEditor is saying below.</p> <p>Are you doing that on purpose? If not you should be using <code>min-width</code> &amp;&amp; <code>max-width</code></p> <hr> <pre><code>@media screen and (min-width : 176px) and (max-width : 360px) { body {background: green; } } </code></pre>
32,407,140
Using a generic Swift class in Objective-C
<p>Let's say I define a generic class in Swift, similar to the following:</p> <pre><code>class MyArray&lt;T&gt; { func addObject(object: T) { // do something... hopefully } } </code></pre> <p>(I know there is a <em>slightly</em> better implementation of array, this is merely an example.)</p> <p>In Swift I can now use this class very easily:</p> <pre><code>let a = MyArray&lt;String&gt;() a.addObject("abc") </code></pre> <p><a href="https://developer.apple.com/library/prerelease/ios/documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_7_0.html">With Xcode 7, we now have generics in Objective-C</a>, so I would assume that I could use this class in Objective-C:</p> <pre><code>MyArray&lt;NSString*&gt; *a = [[MyArray&lt;NSString*&gt; alloc] init]; [a addObject:@"abc"]; </code></pre> <p>However, MyArray is never added to my <code>Project-Swift.h</code> file. Even if I change it to inherit from NSObject, it still doesn't appear in my Swift.h file.</p> <p>Is there any way to create a generic Swift class and then use it in Objective-C?</p> <hr> <p><strong>Update:</strong> If I try to inherit from NSObject and annotate with @objc:</p> <pre><code>@objc(MyArray) class MyArray&lt;T&gt;: NSObject { func addObject(object: T) { // do something... hopefully } } </code></pre> <p>I get the following compiler error:</p> <blockquote> <p>Generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C.</p> </blockquote> <p>Does this mean there is no way to use a generic Swift class in Objective-C? </p> <p>How does one in<em>directly</em> reference the class?</p>
32,408,379
2
2
null
2015-09-04 21:57:29.143 UTC
3
2018-12-14 23:12:32.6 UTC
2015-09-04 23:28:52.9 UTC
null
35,690
null
35,690
null
1
33
ios|objective-c|swift|generics
12,752
<p>Swift generic types cannot be used in Objective-C.</p> <p><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID136" rel="noreferrer">https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID136</a></p> <blockquote> <p>This excludes Swift-only features such as those listed here:</p> <ul> <li>Generics</li> <li>...</li> </ul> </blockquote>
36,330,859
export html table as word file and change file orientation
<p>I have jquery function which exporting html table to word file. Function works great, but I need to rotate a word file to landsacpe orientation. Can somebody help me?</p> <p>Here is js function:</p> <pre><code> &lt;SCRIPT type="text/javascript"&gt; $(document).ready(function () { $("#btnExport").click(function () { var htmltable= document.getElementById('tblExport'); var html = htmltable.outerHTML; window.open('data:application/msword,' + '\uFEFF' + encodeURIComponent(html)); }); }); Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.docx"); </code></pre> <p> </p>
36,337,284
1
3
null
2016-03-31 10:31:05.387 UTC
11
2022-06-14 20:23:49.773 UTC
2016-03-31 12:08:54.377 UTC
null
3,204,551
null
5,119,961
null
1
9
javascript|jquery|html|ms-word|export
34,526
<h2>Export HTML to Microsoft Word</h2> <p>You may set page orientation, paper size, and many other properties by including the CSS in the exported HTML. For a list of available styles see <a href="https://gist.github.com/p3t3r67x0/ac9d052595b406d5a5c1" rel="nofollow noreferrer">MS Office prefixed style properties</a> Some styles have dependencies. For example, to set mso-page-orientation you must also set the size of the page as shown in the code below.</p> <p><strong>Updated:<br></strong> Tested with Word 2010-2013 in FireFox, Chrome, Opera, IE10-11. Minor code changes to make work with Chrome and IE10. Will not work with legacy browsers (IE&lt;10) that lack window.Blob object. Also see this SO post if you receive a &quot;createObjectURL is not a function&quot; error: <a href="https://stackoverflow.com/a/10195751/943435">https://stackoverflow.com/a/10195751/943435</a></p> <p><strong>Update 2022:<br></strong> Fixed broken GitHub link</p> <pre><code> @page WordSection1{ mso-page-orientation: landscape; size: 841.95pt 595.35pt; /* EU A4 */ /* size:11.0in 8.5in; */ /* US Letter */ } div.WordSection1 { page: WordSection1; } </code></pre> <p>To view a complete working demo see: <a href="https://jsfiddle.net/78xa14vz/3/" rel="nofollow noreferrer">https://jsfiddle.net/78xa14vz/3/</a></p> <p>The Javascript used to export to Word:</p> <pre><code> function export2Word( element ) { var html, link, blob, url, css; css = ( '&lt;style&gt;' + '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' + 'div.WordSection1 {page: WordSection1;}' + '&lt;/style&gt;' ); html = element.innerHTML; blob = new Blob(['\ufeff', css + html], { type: 'application/msword' }); url = URL.createObjectURL(blob); link = document.createElement('A'); link.href = url; link.download = 'Document'; // default name without extension document.body.appendChild(link); if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11 else link.click(); // other browsers document.body.removeChild(link); }; </code></pre> <p>And the HTML:</p> <pre><code>&lt;button onclick=&quot;export2Word(window.docx)&quot;&gt;Export&lt;/button&gt; &lt;div id=&quot;docx&quot;&gt; &lt;div class=&quot;WordSection1&quot;&gt; &lt;!-- The html you want to export goes here --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
4,546,547
How do I specify tables in my Markdown document using pandoc syntax?
<p>I have a markdown document I'm processing with the pandoc tool to generate HTML and PDF documents. I'm trying to include a table in the document. Regular markdown doesn't support tables, but pandoc does. I've tried copy-pasting the definition of a table from the pandoc documentation into my source document, but when running it through the pandoc program the resulting document is all crammed into one big table.</p> <p>Can anyone show me a pandoc table that renders properly?</p>
4,565,691
1
0
null
2010-12-28 13:53:24.427 UTC
11
2015-12-05 03:04:37.543 UTC
2015-12-05 03:04:37.543 UTC
null
59,087
null
556,039
null
1
26
text|markdown|pandoc
14,085
<pre><code># Points about Tweedledee and Tweedledum Much has been made of the curious features of Tweedledee and Tweedledum. We propose here to set some of the controversy to rest and to uproot all of the more outlandish claims. . Tweedledee Tweedledum -------- -------------- ---------------- Age 14 14 Height 3'2" 3'2" Politics Conservative Conservative Religion "New Age" Syrian Orthodox --------- -------------- ---------------- Table: T.-T. Data # Mussolini's role in my downfall -------------------------------------------------------------------- *Drugs* *Alcohol* *Tobacco* ---------- ------------- ----------------- -------------------- Monday 3 Xanax 2 pints 3 cigars, 1 hr at hookah bar Tuesday 14 Adderall 1 Boone's Farm, 1 packet Drum 2 Thunderbird Wednesday 2 aspirin Tall glass water (can't remember) --------------------------------------------------------------------- Table: *Tableau des vices*, deluxe edition # Points about the facts In recent years, more and more attention has been paid to opinion, less and less to what were formerly called the cold, hard facts. In a spirit of traditionalism, we propose to reverse the trend. Here are some of our results. ------- ------ ---------- ------- 12 12 12 12 123 123 123 123 1 1 1 1 --------------------------------------- Table: Crucial Statistics # Recent innovations (1): False presentation Some, moved by opinion and an irrational lust for novelty, would introduce a non-factual element into the data, perhaps moving all the facts to the left: ------- ------ ---------- ------- 12 12 12 12 123 123 123 123 1 1 1 1 --------------------------------------- Table: Crucial "Statistics" # Recent innovations (2): Illegitimate decoration Others, preferring their facts to be *varnished*, as we might say, will tend to 'label' the columns Variable Before During After --------- ------ ---------- ------- 12 12 12 12 123 123 123 123 1000 1000 1000 1000 ---------------------------------------- # Recent innovations (3): "Moderate" decoration Or, maybe, to accompany this 'spin' with a centered or centrist representation: Variable Before During After ---------- ------- ---------- ------- 12 12 12 12 123 123 123 123 1 1 1 1 ----------------------------------------- # The real enemy Some even accompany these representations with a bit of leftwing clap-trap, suggesting the facts have drifted right: ------------------------------------------------------ Variable Before During After ---------- ----------- ---------- ------- 12 12 12 12 -- Due to baleful bourgeois influence 123 123 123 123 -- Thanks to the renegade Kautsky 1 1 1 1 -- All a matter of sound Party discipline ------------------------------------------------------- Table: *"The conditions are not ripe, comrades; they are **overripe**!"* # The Truth If comment be needed, let it be thus: the facts have drifted left. ------------------------------------------------------------------------ Variable Before During After ---------- ------------- ---------- ---------------------- 12 12 12 12 (here's (due to (something to do where the rot lapse of with Clinton and set in ) traditional maybe the '60's) values) 123 123 123 123 (too much (A=440?) strong drink) 1 1 1 1 (Trilateral Commission?) -------------------------------------------------------------------------- Table: *The Decline of Western Civilization* </code></pre>
34,769,665
PHP json_encode data with double quotes
<p>I'm using this simple code to transform database query results into JSON format:</p> <pre><code>$result = $mysqli-&gt;query(" SELECT date as a , sum(sales) as b , product as c FROM default_dataset GROUP BY date , product ORDER BY date "); $data = $result-&gt;fetch_all(MYSQLI_ASSOC); echo stripslashes(json_encode($data)); </code></pre> <p>The problem is that if there are double quotes in the data (e.g. in the product column) returned by this query. The json_encode function does not encode the data in a good JSON format.</p> <p>Could someone help me how to escape the double quotes that are returned by the query? Thank you.</p>
34,769,860
6
3
null
2016-01-13 14:49:33.73 UTC
5
2019-10-02 11:46:22.337 UTC
2019-07-24 15:18:29.453 UTC
null
285,587
null
2,022,314
null
1
9
php|json
45,681
<p><code>json_encode</code> already takes care of this, you are breaking the result by calling <code>stripslashes</code>:</p> <pre><code>echo json_encode($data); //properly formed json </code></pre>
15,658,334
vba Vlookup across workbooks
<p>I seem to have an error in the below syntax line. I believe the issue lies with range parameter of workbook book1. I cannot figure out why. Basically I'm tring to vlookup across 2 workbooks.</p> <p>The code is invoked from workbook - book1. Just before this line of code workbook - book2 is activated. Both the workbooks are open. I captured the error code 2015 by replacing the left side with a variant variable.</p> <p>I appreciate any help with this vlookup issue. Thanks.</p> <pre><code> Cells(j, c + 2).value = [VLookup(workbooks(book2).sheets(5).range(Cells(j, c + 1)), workbooks(book1).sheets(4).range(cells(row1+2,1),cells(row2,col1)), 3, false)] </code></pre>
15,660,834
2
4
null
2013-03-27 12:03:30.247 UTC
3
2016-12-26 21:14:00.503 UTC
2018-07-09 18:41:45.953 UTC
null
-1
null
2,000,380
null
1
2
excel|vba
88,315
<p>You've provided only a snippet of code, but first things first let's make sure you have all the variables defined. I have also added a few more to simplify and possibly help trap errors.</p> <pre><code>Sub VlookMultipleWorkbooks() Dim lookFor as String Dim srchRange as Range Dim book1 as Workbook Dim book2 as Workbook 'Set some Workbook variables: Set book1 = Workbooks("Book 1 Name") '&lt;edit as needed Set book2 = Workbooks("Book 2 Name") '&lt;edit as needed 'Set a string variable that we will search for: lookFor = book2.sheets(5).range(Cells(j, c + 1)) 'Define the range to be searched in Book1.Sheets(4): Set srchRange = book1.Sheets(4).Range(cells(row1+2,1).Address, cells(row2,col1).Address) 'This assumes that the Book2 is Open and you are on the desired active worksheet: ActiveSheet.Cells(j, c + 2).value = _ Application.WorksheetFunction.VLookup(lookFor, _ book1.Sheets(4).Range(srchRange.Address), 3, False) End Sub </code></pre>
38,974,889
Can a conversion to string raise an error?
<p>I was wondering if converting to string i.e. <code>str(sth)</code> can raise an exception like for example <code>float(sth)</code> does? I am asking this to know if it is necessary to wrap my code in: </p> <pre><code>try: x = str(value) except ValueError: x = None </code></pre> <p>to be sure that execution does not stop because of conversion failure.</p> <p>Also does this differ in Python 2 and 3, since the <code>str</code> class is different in them??</p>
38,975,059
4
3
null
2016-08-16 12:23:54.84 UTC
5
2016-09-18 08:52:15.613 UTC
2016-08-16 12:50:49.103 UTC
null
4,952,130
null
4,449,586
null
1
30
python|string|python-3.x|casting
5,017
<p>If you encounter a custom class that explicitly raises an exception in <code>__str__</code> (or <code>__repr__</code> if <code>__str__</code> is not defined). Or, for example a class that returns a <code>bytes</code> object from <code>__str__</code>:</p> <pre><code>class Foo: def __str__(self): return b'' str(Foo()) # TypeError: __str__ returned non-string (type bytes) </code></pre> <p>But personally, I have <em>never</em> seen this and I'm pretty sure no one has; it would be daft to do it. Likewise, a silly mistake in the implementation of <code>__str__</code> or edge cases might create another <code>Exception</code>. It is interesting to see how you could push Python to these edge cases (look at <a href="https://stackoverflow.com/a/38982099/4952130"><em>@user2357112</em></a> answer here).</p> <p>Other than that case, no built-ins generally raise an exception in this case since it is defined for all of them in <code>Py2</code> and <code>Py3</code>. </p> <p>For user defined classes <code>str</code> will use <code>object.__str__</code> by default if not defined in Python 3 and, in Python 2, use it if a class is a new style class (inherits from <code>object</code>).</p> <p>If a class is an old style class I <em>believe</em> it is <code>classobj.__str__</code> that is used for classes and <code>instance.__str__</code> for instances. </p> <p>In general, I would not catch this, special cases aren't special enough for this.</p>
26,745,519
Converting dictionary to JSON
<pre><code>r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating'])) </code></pre> <p>I am not able to access my data in the JSON. What am I doing wrong?</p> <pre><code>TypeError: string indices must be integers, not str </code></pre>
32,824,345
6
1
null
2014-11-04 21:38:47.65 UTC
92
2021-11-19 05:21:31.953 UTC
2019-05-28 17:15:01.79 UTC
null
6,862,601
null
1,840,899
null
1
487
python|json|python-2.7|dictionary
742,196
<p><code>json.dumps()</code> converts a dictionary to <code>str</code> object, not a <code>json(dict)</code> object! So you have to load your <code>str</code> into a <code>dict</code> to use it by using <a href="https://docs.python.org/2/library/json.html#json.loads" rel="noreferrer"><strong><code>json.loads()</code></strong></a> method</p> <p>See <code>json.dumps()</code> as a save method and <code>json.loads()</code> as a retrieve method.</p> <p>This is the code sample which might help you understand it more:</p> <pre><code>import json r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) loaded_r = json.loads(r) loaded_r['rating'] #Output 3.5 type(r) #Output str type(loaded_r) #Output dict </code></pre>
53,444,743
Clean ways to do multiple undos in C
<p>Someone will probably say something about exceptions... but in C, what are other ways to do the following cleanly/clearly and without repeating so much code?</p> <pre><code>if (Do1()) { printf("Failed 1"); return 1; } if (Do2()) { Undo1(); printf("Failed 2"); return 2; } if (Do3()) { Undo2(); Undo1(); printf("Failed 3"); return 3; } if (Do4()) { Undo3(); Undo2(); Undo1(); printf("Failed 4"); return 4; } if (Do5()) { Undo4(); Undo3(); Undo2(); Undo1(); printf("Failed 5"); return 5; } Etc... </code></pre> <p>This might be one case for using gotos. Or maybe multiple inner functions...</p>
53,445,049
15
9
null
2018-11-23 10:17:17.887 UTC
5
2021-06-11 19:37:03.363 UTC
2018-11-24 03:12:51.807 UTC
null
63,550
null
1,071,669
null
1
40
c
3,089
<p>Yes, it's quite common to use goto in such cases to avoid repeating yourself.</p> <p>An example:</p> <pre><code>int hello() { int result; if (Do1()) { result = 1; goto err_one; } if (Do2()) { result = 2; goto err_two; } if (Do3()) { result = 3; goto err_three; } if (Do4()) { result = 4; goto err_four; } if (Do5()) { result = 5; goto err_five; } // Assuming you'd like to return 0 on success. return 0; err_five: Undo4(); err_four: Undo3(); err_three: Undo2(); err_two: Undo1(); err_one: printf("Failed %i", result); return result; } </code></pre> <p>As always you probably also want to keep your functions small and batch together the operations in a meaningful manner to avoid a large "undo-code".</p>
6,935,389
how to get iterator to a particular position of a vector
<p>Suppose i have a </p> <pre><code>std::vector&lt;int&gt; v //and ... for(int i =0;i&lt;100;++i) v.push_back(i); </code></pre> <p>now i want an iterator to, let's say 10th element of the vector.</p> <p>without doing the following approach</p> <pre><code>std::vector&lt;int&gt;::iterator vi; vi = v.begin(); for(int i = 0;i&lt;10;i++) ++vi; </code></pre> <p>as this will spoil the advantage of having random access iterator for a vector.</p>
6,935,407
2
1
null
2011-08-04 02:07:31.413 UTC
11
2013-11-17 19:59:11.773 UTC
null
null
null
null
811,335
null
1
34
c++|iterator
50,703
<p>Just add 10 to the iterator. They are intended to "feel" like pointers.</p>
7,317,475
PostgreSQL array_agg order
<p>Table 'animals':</p> <pre><code>animal_name animal_type Tom Cat Jerry Mouse Kermit Frog </code></pre> <p>Query:</p> <pre><code>SELECT array_to_string(array_agg(animal_name),';') animal_names, array_to_string(array_agg(animal_type),';') animal_types FROM animals; </code></pre> <p>Expected result:</p> <pre><code>Tom;Jerry;Kerimt, Cat;Mouse;Frog OR Tom;Kerimt;Jerry, Cat;Frog;Mouse </code></pre> <p>Can I be sure that order in first aggregate function will always be the same as in second. I mean I would't like to get:</p> <pre><code>Tom;Jerry;Kermit, Frog;Mouse,Cat </code></pre>
7,318,299
4
1
null
2011-09-06 09:09:44.053 UTC
25
2021-02-11 21:47:40.98 UTC
2015-12-26 21:53:06.707 UTC
null
2,849,346
null
930,302
null
1
147
postgresql|array-agg
103,955
<p><em>If you are on a PostgreSQL version &lt; 9.0 then:</em></p> <p>From: <a href="http://www.postgresql.org/docs/8.4/static/functions-aggregate.html">http://www.postgresql.org/docs/8.4/static/functions-aggregate.html</a></p> <blockquote> <p>In the current implementation, the order of the input is in principle unspecified. Supplying the input values from a sorted subquery will usually work, however. For example:</p> <p>SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;</p> </blockquote> <p>So in your case you would write:</p> <pre><code>SELECT array_to_string(array_agg(animal_name),';') animal_names, array_to_string(array_agg(animal_type),';') animal_types FROM (SELECT animal_name, animal_type FROM animals) AS x; </code></pre> <p>The input to the array_agg would then be unordered but it would be the same in both columns. And if you like you could add an <code>ORDER BY</code> clause to the subquery.</p>
8,089,725
How can I have different web browsers subscribe to separate channels in a Redis/Node.js/Socket.io pub/sub setup?
<p>I'd like different clients (web browsers) to be able to subscribe to separate Redis channels.</p> <p>I'm able to pass the requested channel from the client page to the node.js server. But, if I have three browsers subscribe each subscribe three separate channels, all three browsers receive messages published to any of the three channels.</p> <p>Here is the client HTML code. I have three separate pages with the channel name hardcoded into it. In this example, the channel is "channel1".</p> <p><strong>client1.html</strong></p> <pre><code>&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt; &lt;script&gt; var socket = io.connect('http://localhost'); socket.on('giveChannel', function () { console.log('sending channel'); socket.emit('sendChannel', "{\"channel\":\"channel\"}"); }); socket.on('message', function (data) { console.log(data); }); &lt;/script&gt; </code></pre> <p>Here is the Node.js file.</p> <p><strong>app.js</strong></p> <pre><code>redis = require('redis'), sys = require('sys'); var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(function (req, res) { var path = url.parse(req.url).pathname; fs.readFile(__dirname + path, function(err, data) { if (err) return null; res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data, 'utf8'); res.end(); }); }); io = require('socket.io').listen(server); io.sockets.on('connection', function (socket) { var rc = redis.createClient(); rc.on("connect", function() { sys.log('connected to redis'); }); rc.on("message", function (channel, message) { sys.log("Sending: " + message); io.sockets.emit('message', message); }); socket.emit('giveChannel'); socket.on('sendChannel', function (msg) { console.log(msg); var data = JSON.parse(msg); console.log(data.channel); rc.subscribe(data.channel); }); }); server.listen(8000, '0.0.0.0'); </code></pre>
8,093,261
1
1
null
2011-11-11 04:35:07.347 UTC
8
2012-02-01 11:04:11.903 UTC
null
null
null
null
24,988
null
1
3
javascript|node.js|redis|socket.io|publish-subscribe
2,746
<p>As per your example APP will open a new redis connection per every user,that doesn't make sense.</p> <p>This use one connection for entire app (you have to make one more connection for publish the data) for sub jobs</p> <p><strong>Client Side</strong> </p> <pre><code> var socket = io.connect('http://localhost:3000'); socket.emit('channel','US'); socket.on('news',function(news){ $("body").append('&lt;br/&gt;' + news); }); socket.on('message',function(msg){ $("body").append('&lt;br/&gt;' + msg); }); </code></pre> <p><strong>Server Side</strong></p> <pre><code>var io = require('socket.io'); var express = require('express'); var app = express.createServer(); io = io.listen(app); app.listen('3000'); var pub = require('node_redis').createClient(); //publish cli var redis = require('node_redis').createClient(); //sub cli redis.psubscribe('*'); redis.on('pmessage',function(pat,ch,msg){ io.sockets.in(ch).emit('news',msg); }); io.sockets.on('connection',function(socket){ console.log('Socket connected: ' + socket.id); socket.on('channel',function(ch){ socket.join(ch) //Publishing data on ch pub.publish(ch,"Hello " + ch); }); socket.on('disconnect',function(){ console.log('Socket dis connected: ' + socket.id); }); }); console.log('Server started @ 3000'); </code></pre>
1,816,880
Why does csvwriter.writerow() put a comma after each character?
<p>This code opens the URL and appends the <code>/names</code> at the end and opens the page and prints the string to <code>test1.csv</code>:</p> <pre><code>import urllib2 import re import csv url = (&quot;http://www.example.com&quot;) bios = [u'/name1', u'/name2', u'/name3'] csvwriter = csv.writer(open(&quot;/test1.csv&quot;, &quot;a&quot;)) for l in bios: OpenThisLink = url + l response = urllib2.urlopen(OpenThisLink) html = response.read() item = re.search('(JD)(.*?)(\d+)', html) if item: JD = item.group() csvwriter.writerow(JD) else: NoJD = &quot;NoJD&quot; csvwriter.writerow(NoJD) </code></pre> <p>But I get this result:</p> <p><code>J,D,&quot;,&quot;, ,C,o,l,u,m,b,i,a, ,L,a,w, ,S,c,h,o,o,l,....</code></p> <p>If I change the string to (&quot;JD&quot;, &quot;Columbia Law School&quot; ....) then I get</p> <p><code>JD, Columbia Law School...)</code></p> <p>I couldn't find in the documentation how to specify the delimeter.</p> <p>If I try to use <code>delimeter</code> I get this error:</p> <pre><code>TypeError: 'delimeter' is an invalid keyword argument for this function </code></pre>
1,816,897
4
2
null
2009-11-29 21:45:43.01 UTC
21
2021-08-20 13:02:27.25 UTC
2021-08-16 20:24:00.91 UTC
null
4,621,513
null
215,094
null
1
120
python|csv
101,219
<p>It expects a sequence (eg: a list or tuple) of strings. You're giving it a single string. A string happens to be a sequence of strings too, but it's a sequence of 1 character strings, which isn't what you want.</p> <p>If you just want one string per row you could do something like this:</p> <pre><code>csvwriter.writerow([JD]) </code></pre> <p>This wraps JD (a string) with a list.</p>
10,469,687
how to pause/resume a thread
<p>How can I pause/resume a thread? Once I <code>Join()</code> a thread, I can't restart it. So how can I start a thread and make it pause whenever the button 'pause' is pressed, and resume it when resume button is pressed?</p> <p>The only thing this thread does, is show some random text in a label control.</p>
10,469,781
4
2
null
2012-05-06 10:06:24.407 UTC
7
2017-04-14 18:33:05.34 UTC
null
null
null
null
405,046
null
1
15
c#|wpf|multithreading|resume
43,760
<p>Maybe the <code>ManualResetEvent</code> is a good choice. A short example:</p> <pre><code>private static EventWaitHandle waitHandle = new ManualResetEvent(initialState: true); // Main thread public void OnPauseClick(...) { waitHandle.Reset(); } public void OnResumeClick(...) { waitHandle.Set(); } // Worker thread public void DoSth() { while (true) { // show some random text in a label control (btw. you have to // dispatch the action onto the main thread) waitHandle.WaitOne(); // waits for the signal to be set } } </code></pre>
36,441,312
How to redirect cron job output to stdout
<p>I have a cron job and its output is now redirected into a file. It looks like the following</p> <p><code>0 9 * * * /bin/sh /bin/cleanup.sh &gt; /home/darkknight/cleanup.log</code></p> <p>Can any one help me to rediect its output to stdout? </p>
41,409,061
3
7
null
2016-04-06 04:06:33.773 UTC
9
2016-12-31 20:14:01.697 UTC
2016-04-07 02:36:29.46 UTC
null
3,302,647
null
3,302,647
null
1
28
linux|unix|cron|crontab
37,864
<p>Running process has a PID and its fd (file descriptor) is mapping to <code>/proc/&lt;PID&gt;/fd</code>. And we can find PID of the running cron process at <code>/var/run/crond.pid</code>.</p> <p>To send cron log to stdout, we could write log to fd number 1 of the process started by cron.</p> <pre><code>0 9 * * * /bin/sh /bin/cleanup.sh &gt; /proc/$(cat /var/run/crond.pid)/fd/1 2&gt;&amp;1 </code></pre>
7,432,146
What is Scala's "powerful" type system?
<p>When Scala is discussed, the type system is always mentioned as one of the primary features. It is referred to as powerful, and the primary reason for the language moniker (Scala being short for "scalable language"). Could someone please explain how Scala typing works/why this unique, and how that contributes to the language being scalable?</p>
7,438,415
5
3
null
2011-09-15 14:03:59.423 UTC
17
2011-09-16 16:59:17.583 UTC
2011-09-15 15:51:25.533 UTC
null
82,474
null
404,917
null
1
30
scala|types
2,843
<p>I don't think the existing answers are appropriate. Scala has a lot of conveniences, but they are not related to the type system being powerful just because they relate to types. In fact, type inference is in direct conflict with the power of the type system -- were it less powerful, one could have full type inference (like in Haskell).</p> <p>So,</p> <ul> <li>Scala has classes with members. (Obvious, but I'm trying to be exhaustive here.)</li> <li>Method ("def") members of a scala class can have zero or more parameter lists, each of which can have zero or more parameters, the last of which might be a vararg.</li> <li>Parameters may be passed by value or by name.</li> <li>Parameters have names and may have default values.</li> <li>Scala has "var" and "val" members (which are, in practice, also methods).</li> <li>Scala has "lazy val" members.</li> <li>Scala has "type" members (type aliases), which may be specified as fixed types or as type boundaries.</li> <li>Scala has abstract classes and members (all of the above members may be abstract).</li> <li>Scala has inner class, traits and objects (Scala's inner class are different than Java's).</li> <li>Scala's members, plus inner stuff, may be overriden.</li> <li>Scala has type inheritance.</li> <li>Scala has traits, providing multiple-inheritance with type linearization.</li> <li>Scala's traits's method members may have abstract override (stackable, aspect-like override).</li> <li>Scala has singleton types.</li> <li>Scala has companion class/objects (related to scope).</li> <li>Scala has private, protected and public scopes for classes, traits, singletons and members.</li> <li>Scala's private and protected scopes can be limited to any enclosing package, class, trait or singleton, plus "this".</li> <li>Scala has self types.</li> <li>Scala has type parameters.</li> <li>Scala's type parameters can be co- and contra-variant, as well as invariant.</li> <li>Scala has type constructors.</li> <li>Scala has higher-order types.</li> <li>Scala has existential types.</li> <li>Scala has structural types.</li> <li>Scala has implicit parameters.</li> <li>Scala has function types, though, since they are simply a class plus syntactic sugar, I don't think it belongs on this list. On the other hand, function types are part of view bounds, so maybe it does.</li> <li>Scala has a top (like almost everyone) and a bottom (like other statically typed fp languages).</li> <li>Scala's "unit" is a type with a value (as opposed to "void" elsewhere).</li> </ul> <p>Next, there are features related to Scala's implicits, which is what merit their inclusion above.</p> <ul> <li>Scala has view bounds, an implicit parameter that acts like another type bound.</li> <li>Scala has context counds, an implicit parameter that acts like another bound.</li> <li>Generally speaking, implicit parameters and type inference can be combined to construct arbitrary complex proofs over the type parameters.</li> </ul> <p>Related to the last comment, implicits and type inference, together, make Scala's type system <em>turing complete</em>. That is, you codify arbitrary programs as types, that will be "run" at compile time by the compiler. Proof <a href="http://michid.wordpress.com/2010/01/29/scala-type-level-encoding-of-the-ski-calculus/" rel="noreferrer">here</a>, by way of SKI Calculus, with a "buggy" infinite loop in the types as further demonstration.</p> <p>The list of features above is quite big and impressive on many points. It is, however, the way Scala combines implicits and type inference to produce static proofs at compile time (such as view bounds and context bounds) that make Scala's type system unique. AFAIK, there is no other language doing that, though there are certainly other languages providing proof capabilities through other means.</p>
7,684,359
How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?
<p>What is the use of <code>tim.tv_sec</code> and <code>tim.tv_nsec</code> in the following?</p> <p>How can I sleep execution for <code>500000</code> microseconds?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main() { struct timespec tim, tim2; tim.tv_sec = 1; tim.tv_nsec = 500; if(nanosleep(&amp;tim , &amp;tim2) &lt; 0 ) { printf("Nano sleep system call failed \n"); return -1; } printf("Nano sleep successfull \n"); return 0; } </code></pre>
7,684,384
7
0
null
2011-10-07 07:41:22.853 UTC
17
2021-09-05 08:37:15.073 UTC
2015-11-10 21:13:40.383 UTC
null
895,245
null
870,565
null
1
84
c|posix|sleep
187,060
<p>Half a second is 500,000,000 nanoseconds, so your code should read:</p> <pre><code>tim.tv_sec = 0; tim.tv_nsec = 500000000L; </code></pre> <p>As things stand, you code is sleeping for 1.0000005s (1s + 500ns).</p>
7,344,497
Android canvas draw rectangle
<p>how to draw empty rectangle with etc. borderWidth=3 and borderColor=black and part within rectangle don't have content or color. Which function in Canvas to use</p> <pre><code>void drawRect(float left, float top, float right, float bottom, Paint paint) void drawRect(RectF rect, Paint paint) void drawRect(Rect r, Paint paint) </code></pre> <p>Thanks.</p> <p>I try this example</p> <pre><code>Paint myPaint = new Paint(); myPaint.setColor(Color.rgb(0, 0, 0)); myPaint.setStrokeWidth(10); c.drawRect(100, 100, 200, 200, myPaint); </code></pre> <p>It draws rectangle and fill it with black color but I want just "frame" around like this image: </p> <p><img src="https://i.stack.imgur.com/2aUXE.png" alt="enter image description here"></p>
8,605,645
7
0
null
2011-09-08 07:18:43.32 UTC
42
2018-09-08 18:47:10.56 UTC
2013-12-07 20:34:14.84 UTC
null
881,229
null
686,222
null
1
115
android|android-canvas
339,657
<p>Try <code>paint.setStyle(Paint.Style.STROKE)</code>?</p>
7,329,166
Changing step values in seekbar?
<p>I have a seekbar, while moving it I want to change values from 0 to 200. I have a TextView, where I display those values while moving the seekbar. But I don't want to have every value from that interval(0,1,2,3,4,5...), but to have 10, 20, 30...so on. So when I move the seekbar, I want to display 10,20,30,40....to 200. Can somebody give me a hint or an example how to do this?</p>
7,329,277
8
1
null
2011-09-07 05:19:25.773 UTC
22
2021-04-20 12:24:40.007 UTC
2021-04-20 12:24:40.007 UTC
null
2,016,562
null
655,275
null
1
54
android|android-seekbar|android-slider
101,124
<p>Try below code</p> <pre><code>SeekBar seekBar = (SeekBar)layout.findViewById(R.id.seekbar); seekBar.setProgress(0); seekBar.incrementProgressBy(10); seekBar.setMax(200); TextView seekBarValue = (TextView)layout.findViewById(R.id.seekbarvalue); seekBarValue.setText(tvRadius.getText().toString().trim()); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progress = progress / 10; progress = progress * 10; seekBarValue.setText(String.valueOf(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); </code></pre> <p><code>setProgress(int)</code> is used to set starting value of the seek bar</p> <p><code>setMax(int)</code> is used to set maximum value of seek bar</p> <p>If you want to set boundaries of the seekbar then you can check the progressbar value in the <code>onProgressChanged</code> method. If the progress is less than or greater than the boundary then you can set the progress to the boundary you defined.</p>
7,542,021
How to get max value of a column using Entity Framework?
<p>To get maximum value of a column that contains integer, I can use the following T-SQL comand</p> <pre><code>SELECT MAX(expression ) FROM tables WHERE predicates; </code></pre> <p>Is it possible to obtain the same result with Entity Framework.</p> <p>Let's say I have the following model</p> <pre><code>public class Person { public int PersonID { get; set; } public int Name { get; set; } public int Age { get; set; } } </code></pre> <p>How do I get the oldest person's age?</p> <pre><code>int maxAge = context.Persons.? </code></pre>
7,542,129
10
0
null
2011-09-24 21:23:42.41 UTC
15
2021-06-18 00:11:51.457 UTC
2015-02-12 18:02:17.837 UTC
null
41,956
null
202,382
null
1
113
c#|sql|entity-framework|max
163,113
<p>Try this <code>int maxAge = context.Persons.Max(p =&gt; p.Age);</code></p> <p>And make sure you have <code>using System.Linq;</code> at the top of your file</p>
7,203,515
How to find a deleted file in the project commit history?
<p>Once upon a time, there was a file in my project that I would now like to be able to get.</p> <p>The problem is: I have no idea of when have I deleted it and on which path it was.</p> <p>How can I locate the commits of this file when it existed?</p>
7,203,551
10
3
null
2011-08-26 10:43:29.447 UTC
375
2022-07-21 21:50:56.553 UTC
2021-09-10 15:24:32.113 UTC
null
542,251
null
330,889
null
1
1,693
git
444,115
<p>If you do not know the exact path you may use</p> <pre><code>git log --all --full-history -- "**/thefile.*" </code></pre> <p>If you know the path the file was at, you can do this:</p> <pre><code>git log --all --full-history -- &lt;path-to-file&gt; </code></pre> <p>This should show a list of commits in all branches which touched that file. Then, you can find the version of the file you want, and display it with...</p> <pre><code>git show &lt;SHA&gt; -- &lt;path-to-file&gt; </code></pre> <p>Or restore it into your working copy with:</p> <p><code>git checkout &lt;SHA&gt;^ -- &lt;path-to-file&gt;</code></p> <p>Note the caret symbol (<code>^</code>), which gets the checkout <em>prior</em> to the one identified, because at the moment of <code>&lt;SHA&gt;</code> commit the file is deleted, we need to look at the previous commit to get the deleted file's contents</p>
14,107,979
Blur specific part of an image (rectangular, circular)?
<p>I want to blur image rectangular or circular. After googling, I found that it is easy to blur whole image but it difficult to blur specific part of image (rectangular, circular). so how it is possible ??? </p> <p>Thanks in advance</p>
14,108,694
4
10
null
2013-01-01 05:12:16.613 UTC
27
2019-11-14 04:57:38.39 UTC
2016-03-22 09:43:42.887 UTC
null
3,766,168
null
1,917,782
null
1
28
iphone|objective-c|ios
10,677
<p><img src="https://i.stack.imgur.com/hwvgC.png" alt="enter image description here"></p> <p>Just set your <code>UIImageView</code> property name as "imageView" and add the following four methods with the same sequence in your implementation file. Also, set your ImageView Mode to 'Redraw'. Add UIImage Category for the blur effect as given or use any custom class, it will work for you.</p> <p>Method 1 - Cropping the Image </p> <pre><code>#pragma mark - Cropping the Image - (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect{ CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect); UIImage *cropped = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return cropped; } </code></pre> <p>Method 2 - Merge the two Images </p> <pre><code>#pragma mark - Marge two Images - (UIImage *) addImageToImage:(UIImage *)img withImage2:(UIImage *)img2 andRect:(CGRect)cropRect{ CGSize size = CGSizeMake(imageView.image.size.width, imageView.image.size.height); UIGraphicsBeginImageContext(size); CGPoint pointImg1 = CGPointMake(0,0); [img drawAtPoint:pointImg1]; CGPoint pointImg2 = cropRect.origin; [img2 drawAtPoint: pointImg2]; UIImage* result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return result; } </code></pre> <p>Method 3 - RoundRect the Image</p> <pre><code>#pragma mark - RoundRect the Image - (UIImage *)roundedRectImageFromImage:(UIImage *)image withRadious:(CGFloat)radious { if(radious == 0.0f) return image; if( image != nil) { CGFloat imageWidth = image.size.width; CGFloat imageHeight = image.size.height; CGRect rect = CGRectMake(0.0f, 0.0f, imageWidth, imageHeight); UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0]; const CGFloat scale = window.screen.scale; UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSaveGState(context); CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect)); CGContextScaleCTM (context, radious, radious); CGFloat rectWidth = CGRectGetWidth (rect)/radious; CGFloat rectHeight = CGRectGetHeight (rect)/radious; CGContextMoveToPoint(context, rectWidth, rectHeight/2.0f); CGContextAddArcToPoint(context, rectWidth, rectHeight, rectWidth/2.0f, rectHeight, radious); CGContextAddArcToPoint(context, 0.0f, rectHeight, 0.0f, rectHeight/2.0f, radious); CGContextAddArcToPoint(context, 0.0f, 0.0f, rectWidth/2.0f, 0.0f, radious); CGContextAddArcToPoint(context, rectWidth, 0.0f, rectWidth, rectHeight/2.0f, radious); CGContextRestoreGState(context); CGContextClosePath(context); CGContextClip(context); [image drawInRect:CGRectMake(0.0f, 0.0f, imageWidth, imageHeight)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } return nil; } </code></pre> <p>Method 4 - Touch Move</p> <pre><code>#pragma mark - Touch Methods - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UIImage *croppedImg = nil; UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self.imageView]; double ratioW=imageView.image.size.width/imageView.frame.size.width ; double ratioH=imageView.image.size.height/imageView.frame.size.height; currentPoint.x *= ratioW; currentPoint.y *= ratioH; double circleSizeW = 30 * ratioW; double circleSizeH = 30 * ratioH; currentPoint.x = (currentPoint.x - circleSizeW/2&lt;0)? 0 : currentPoint.x - circleSizeW/2; currentPoint.y = (currentPoint.y - circleSizeH/2&lt;0)? 0 : currentPoint.y - circleSizeH/2; CGRect cropRect = CGRectMake(currentPoint.x , currentPoint.y, circleSizeW, circleSizeH); NSLog(@"x %0.0f, y %0.0f, width %0.0f, height %0.0f", cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height ); croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect]; // Blur Effect croppedImg = [croppedImg imageWithGaussianBlur9]; // Contrast Effect // croppedImg = [croppedImg imageWithContrast:50]; croppedImg = [self roundedRectImageFromImage:croppedImg withRadious:4]; imageView.image = [self addImageToImage:imageView.image withImage2:croppedImg andRect:cropRect]; } </code></pre> <p>UIImage Category Class</p> <p>UIImage+ImageBlur.h</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface UIImage (ImageBlur) - (UIImage *)imageWithGaussianBlur9; @end </code></pre> <p>UIImage+ImageBlur.m</p> <pre><code>#import "UIImage+ImageBlur.h" @implementation UIImage (ImageBlur) - (UIImage *)imageWithGaussianBlur9 { float weight[5] = {0.1270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162}; // Blur horizontally UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[0]]; for (int x = 1; x &lt; 5; ++x) { [self drawInRect:CGRectMake(x, 0, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[x]]; [self drawInRect:CGRectMake(-x, 0, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[x]]; } UIImage *horizBlurredImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Blur vertically UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); [horizBlurredImage drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[0]]; for (int y = 1; y &lt; 5; ++y) { [horizBlurredImage drawInRect:CGRectMake(0, y, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[y]]; [horizBlurredImage drawInRect:CGRectMake(0, -y, self.size.width, self.size.height) blendMode:kCGBlendModeNormal alpha:weight[y]]; } UIImage *blurredImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // return blurredImage; } @end </code></pre> <p>happy coding....</p>
14,188,273
RSpec gives error 'trait not registered: name'
<p>I tried to test my Rails 3 application on Windows with RSpec. I've wrote tests and factories, but can't solve the issues which raise when I run RSpec on command line. </p> <p>Here is one of the test files: require 'spec_helper'</p> <pre><code>describe "SignIns" do it "can sign in" do user = FactoryGirl.create(:user) visit new_user_session_path fill_in "login", with: user.username fill_in "password", with: user.password click_on "sign in" current_user.username.should == user.username end end </code></pre> <p>And here's the factories.rb:</p> <pre><code>factory :layout do name "layout1" end factory :club do sequence(:name) { |i| "Club #{i}" } contact_name "John Doe" phone "+358401231234" email "#{name}@example.com" association :layout end factory :user do sequence(:username) { |i| "user#{i}" } password 'password' email "[email protected]" club end </code></pre> <p>When I try to run RSpec it gives the following error:</p> <pre><code>trait not registered: name #C: in 'object' #.spec/features/sign_in_spec.rb:11:in 'block (2 levels) in (top(required)) </code></pre> <p>What am I doing wrong?</p>
24,555,269
5
0
null
2013-01-07 00:22:40.44 UTC
3
2022-07-13 14:40:09.777 UTC
2013-01-07 00:29:03.903 UTC
null
1,744,702
null
1,744,702
null
1
29
ruby-on-rails-3|rspec|factory-bot
30,466
<p>I know this is an old question, but in case anyone else ends up here when searching "Trait not registered":</p> <p>When using a dependent attribute like how <code>email</code> depends on <code>name</code> in the <code>:club</code> factory from the question, you need to wrap the attribute in curly braces so it gets lazy evaluated:</p> <pre><code>email {"#{name}@example.com"} </code></pre>
13,901,119
How does vectors multiply act in shader language?
<p>Such as <code>gl_FragColor = v1 * v2</code>, i can't really get how does it multiplies and it seems that the reference give the explanation of vector multiply matrix.<br> ps: The type of <code>v1</code> and <code>v2</code> are both <code>vec4</code>.</p>
13,901,165
1
4
null
2012-12-16 12:05:48.01 UTC
7
2012-12-16 12:29:11.387 UTC
null
null
null
null
674,199
null
1
33
opengl
30,976
<p>The <code>*</code> operator works <a href="http://en.wikibooks.org/wiki/GLSL_Programming/Vector_and_Matrix_Operations#Operators">component-wise</a> for vectors like <code>vec4</code>.</p> <pre><code>vec4 a = vec4(1.0, 2.0, 3.0, 4.0); vec4 b = vec4(0.1, 0.2, 0.3, 0.4); vec4 c = a * b; // vec4(0.1, 0.4, 0.9, 1.6) </code></pre> <p>The <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.30.6.pdf">GLSL Language Specification</a> says under section <em>5.10 Vector and Matrix Operations</em>:</p> <blockquote> <p>With a few exceptions, operations are component-wise. Usually, when an operator operates on a vector or matrix, it is operating independently on each component of the vector or matrix, in a component-wise fashion. [...] The exceptions are matrix multiplied by vector, vector multiplied by matrix, and matrix multiplied by matrix. These do not operate component-wise, but rather perform the correct linear algebraic multiply.</p> </blockquote>
14,220,289
Removing a view controller from UIPageViewController
<p>It's odd that there's no straightforward way to do this. Consider the following scenario:</p> <ol> <li>You have a page view controller with 1 page.</li> <li>Add another page (total 2) and scroll to it.</li> <li><strong>What I want is,</strong> when the user scrolls back to the first page, the 2nd page is now removed and deallocated, and the user can no longer swipe back to that page.</li> </ol> <p>I've tried removing the view controller as a child view controller after the transition is completed, but it still lets me scroll back to the empty page (it doesn't "resize" the page view)</p> <p>Is what I want to do possible?</p>
17,330,606
12
1
null
2013-01-08 17:05:01.67 UTC
42
2019-10-16 13:33:19.623 UTC
2013-01-08 18:22:31.653 UTC
null
458,960
null
458,960
null
1
49
iphone|objective-c|ios|cocoa-touch
32,406
<p>While the answers here are all informative, there is an alternate way of handling the problem, given here:</p> <p><a href="https://stackoverflow.com/questions/12939280/uipageviewcontroller-navigates-to-wrong-page-with-scroll-transition-style">UIPageViewController navigates to wrong page with Scroll transition style</a></p> <p>When I first searched for an answer to this problem, the way I was wording my search wound me up at this question, and not the one I've just linked to, so I felt obligated to post an answer linking to this other question, now that I've found it, and also elaborating a little bit.</p> <p>The problem is described pretty well by matt <a href="https://stackoverflow.com/a/12939384/700471">here</a>: </p> <blockquote> <p>This is actually a bug in UIPageViewController. It occurs only with the scroll style (UIPageViewControllerTransitionStyleScroll) and only after calling setViewControllers:direction:animated:completion: with animated:YES. Thus there are two workarounds:</p> <p>Don't use UIPageViewControllerTransitionStyleScroll.</p> <p>Or, if you call setViewControllers:direction:animated:completion:, use only animated:NO.</p> <p>To see the bug clearly, call setViewControllers:direction:animated:completion: and then, in the interface (as user), navigate left (back) to the preceding page manually. You will navigate back to the wrong page: not the preceding page at all, but the page you were on when setViewControllers:direction:animated:completion: was called.</p> <p>The reason for the bug appears to be that, when using the scroll style, UIPageViewController does some sort of internal caching. Thus, after the call to setViewControllers:direction:animated:completion:, it fails to clear its internal cache. It thinks it knows what the preceding page is. Thus, when the user navigates leftward to the preceding page, UIPageViewController fails to call the dataSource method pageViewController:viewControllerBeforeViewController:, or calls it with the wrong current view controller.</p> </blockquote> <p>This is a good description, not quite the problem noted in this question but very close. Note the line about if you do <code>setViewControllers</code> with <code>animated:NO</code> you will force the UIPageViewController to re-query its data source next time the user pans with a gesture, as it no longer "knows where it is" or what view controllers are next to its current view controller.</p> <p>However, this didn't work for me because there were times when I need to programmatically move the PageView around <em>with</em> an animation.</p> <p>So, my first thought was to call <code>setViewControllers</code> with an animation, and then in the completion block call the method again with whatever view controller was now showing, but with no animation. So the user can pan, fine, but then we call the method again to get the page view to reset.</p> <p>Unfortunately when I tried that I started getting strange "assertion errors" from the page view controller. They look something like this:</p> <blockquote> <p>*** Assertion failure in -[UIPageViewController queuingScrollView: ...</p> </blockquote> <p>Not knowing exactly why this was happening, I backtracked and eventually started using <a href="https://stackoverflow.com/a/16308151/700471">Jai's answer</a> as a solution, creating an entirely new UIPageViewController, pushing it onto a UINavigationController, then popping out the old one. Gross, but it works--mostly. I have been finding I'm still getting occasional Assertion Failures from the UIPageViewController, like this one:</p> <blockquote> <p>*** Assertion failure in -[UIPageViewController queuingScrollView:didEndManualScroll:toRevealView:direction:animated:didFinish:didComplete:], /SourceCache/UIKit_Sim/UIKit-2380.17/UIPageViewController.m:1820 $1 = 154507824 No view controller managing visible view ></p> </blockquote> <p>And the app crashes. Why? Well, searching, I found this <a href="https://stackoverflow.com/questions/12939280/uipageviewcontroller-navigates-to-wrong-page-with-scroll-transition-style">other question</a> that I mentioned up top, and particularly the <a href="https://stackoverflow.com/a/13253884/700471">accepted answer</a> which advocates my original idea, of simply calling <code>setViewControllers: animated:YES</code> and then as soon as it completes calling <code>setViewControllers: animated:NO</code> with the same view controllers to reset the UIPageViewController, but it had the missing element: calling that code back on the main queue! Here's the code:</p> <pre><code>__weak YourSelfClass *blocksafeSelf = self; [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished){ if(finished) { dispatch_async(dispatch_get_main_queue(), ^{ [blocksafeSelf.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];// bug fix for uipageview controller }); } }]; </code></pre> <p>Wow! The only reason this actually made sense to me is because I have watched the the WWDC 2012 Session 211, Building Concurrent User Interfaces on iOS (available <a href="https://developer.apple.com/videos/wwdc/2012/" rel="noreferrer">here</a> with a dev account). I recall now that attempting to modify data source objects that UIKit objects (like UIPageViewController) depend on, and doing it on a secondary queue, can cause some nasty crashes.</p> <p>What I have never seen particularly documented, but must now assume to be the case and read up on, is that the completion block for an animation is performed on a secondary queue, not the main one. So the reason why UIPageViewController was squawking and giving assertion failures, both when I originally attempted to call <code>setViewControllers animated:NO</code> in the completion block of <code>setViewControllers animated:YES</code> and also now that I am simply using a UINavigationController to push on a new UIPageViewController (but doing it, again, in the completion block of <code>setViewControllers animated:YES</code>) is because it's all happening on that secondary queue.</p> <p>That's why that piece of code up there works perfectly, because you come from the animation completion block and send it back over to the main queue so you don't cross the streams with UIKit. Brilliant.</p> <p>Anyway, wanted to share this journey, in case anyone runs across this problem.</p> <p>EDIT: Swift version <a href="https://stackoverflow.com/a/33786397/700471">here</a>, if anyone's interested.</p>
14,141,266
PostgreSQL: FOREIGN KEY/ON DELETE CASCADE
<p>I have two tables like here:</p> <pre><code>DROP TABLE IF EXISTS schemas.book; DROP TABLE IF EXISTS schemas.category; DROP SCHEMA IF EXISTS schemas; CREATE SCHEMA schemas; CREATE TABLE schemas.category ( id BIGSERIAL PRIMARY KEY, name VARCHAR NOT NULL, UNIQUE(name) ); CREATE TABLE schemas.book ( id BIGSERIAL PRIMARY KEY, published DATE NOT NULL, category_id BIGINT NOT NULL REFERENCES schemas.category ON DELETE CASCADE ON UPDATE CASCADE, author VARCHAR NOT NULL, name VARCHAR NOT NULL, UNIQUE(published, author, name), FOREIGN KEY(category_id) REFERENCES schemas.category (id) ); </code></pre> <p>So the logic is simple, after user removes all book under category x, x gets removed from cats, i tried method above but doesn't work, after i clean table book, table category still populated, what's wrong?</p>
14,141,354
4
1
null
2013-01-03 14:55:04.243 UTC
10
2022-05-11 18:53:28.59 UTC
2022-05-11 18:40:21.383 UTC
null
450,917
null
1,831,482
null
1
66
sql|postgresql|cascade
158,697
<p>A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.</p> <p>You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.</p> <pre><code>UPDATE 1: </code></pre> <p><strong>ON DELETE CASCADE</strong> option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.</p> <p>If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.</p> <p><strong>So it's all about what will happen when you delete rows from Parent table not from child table.</strong></p> <p>So in your case when user removes entries from <code>categories</code> table then rows will be deleted from books table. :)</p> <p>Hope this helps you :)</p>
9,303,257
How to decode a Unicode character in a string
<p>How do I decode this string 'Sch\u00f6nen' (<code>@"Sch\u00f6nen"</code>) in C#, I've tried HttpUtility but it doesn't give me the results I need, which is "Schönen".</p>
9,303,629
3
1
null
2012-02-15 23:32:59.793 UTC
2
2020-11-16 17:39:39.997 UTC
2017-03-19 00:44:18.923 UTC
null
477,420
null
694,960
null
1
29
c#
32,659
<p><code>Regex.Unescape</code> did the trick:</p> <pre><code>System.Text.RegularExpressions.Regex.Unescape(@"Sch\u00f6nen"); </code></pre> <p><sub>Note that you need to be careful when testing your variants or writing unit tests: <code>"Sch\u00f6nen"</code> is already <code>"Schönen"</code>. You need <code>@</code> in front of string to treat <code>\u00f6</code> as part of the string.</sub></p>
19,630,570
What does it mean to "ODR-use" something?
<p>This just came up in the context of <a href="https://stackoverflow.com/questions/19630138/the-impact-of-virtual-on-the-use-of-member-of-class-template?noredirect=1#comment29143561_19630138">another question</a>.</p> <p>Apparently member functions in class templates are only instantiated if they are ODR-used. Could somebody explain what exactly that means. The <a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="noreferrer">wikipedia article on One Definition Rule (ODR)</a> doesn't mention "<em>ODR-use</em>".</p> <p>However the standard defines it as</p> <blockquote> <p>A variable whose name appears as a potentially-evaluated expression is <em>odr-used</em> unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied.</p> </blockquote> <p>in [basic.def.odr].</p> <p>Edit: Apparently this is the wrong part and the entire paragraph contains multiple definitions for different things. This might be the relevant one for class template member function:</p> <blockquote> <p>A non-overloaded function whose name appears as a potentially-evaluated expression or a member of a set of candidate functions, if selected by overload resolution when referred to from a potentially-evaluated expression, is odr-used, unless it is a pure virtual function and its name is not explicitly qualified.</p> </blockquote> <p>I do however not understand, how this rule works across multiple compilation units? Are all member functions instantiated if I explicitly instantiate a class template?</p>
19,631,208
2
2
null
2013-10-28 08:58:46.793 UTC
34
2021-07-21 10:54:54.043 UTC
2017-12-11 22:13:50.787 UTC
null
95,966
null
1,994,377
null
1
107
c++|templates|one-definition-rule
20,587
<p>It's just an arbitrary definition, used by the standard to specify when you must provide a definition for an entity (as opposed to just a declaration). The standard doesn't say just "used", because this can be interpreted diversely depending on context. And some ODR-use doesn't really correspond to what one would normally associate with "use"; for example, a virtual function is always ODR-used unless it is pure, even if it isn't actually called anywhere in the program.</p> <p>The full definition is in <a href="http://eel.is/c++draft/basic.def.odr">§3.2</a>, second paragraph, although this contains references to other sections to complete the definition. </p> <p>With regards to templates, ODR-used is only part of question; the other part is instantiation. In particular, §14.7 covers when a template is instantiated. But the two are related: while the text in §14.7.1 (implicit instantiation) is fairly long, the basic principle is that a template will only be instantiated if it is used, and in this context, used means ODR-used. Thus, a member function of a class template will only be instantiated if it is called, or if it is virtual and the class itself is instantiated. The standard itself counts on this in many places: the <code>std::list&lt;&gt;::sort</code> uses <code>&lt;</code> on the individual elements, but you can instantiate a list over an element type which doesn't support <code>&lt;</code>, as long as you don't call <code>sort</code> on it.</p>
19,542,890
How would you forget cached Eloquent models in Laravel?
<p>Theoretical question on Laravel here.</p> <p>So Example of the caching I'd do is:</p> <pre><code>Article::with('comments')-&gt;remember(5)-&gt;get(); </code></pre> <p>Ideally I'd like to have an event for Article updates that when the ID of a instance of that model (that's already cached) is updated I want to forget that key (even if it's the whole result of the query that's forgotten instead of just that one model instance), it is possible to do so?</p> <p>If not is there some way to implement this reasonably cleanly?</p>
20,204,483
4
2
null
2013-10-23 13:22:13.1 UTC
13
2015-12-03 13:51:55.057 UTC
null
null
null
null
795,290
null
1
31
php|caching|laravel|laravel-4
24,704
<p>So i was looking for an answer to the same question as OP but was not really satisfied with the solutions. So i started playing around with this recently and going through the source code of the framework, I found out that the <code>remember()</code> method accepts second param called <code>key</code> and for some reason it has not been documented on their <a href="http://laravel.com/docs/queries#caching-queries">site</a> (Or did i miss that?).</p> <p>Now good thing about this is that, The database builder uses the same cache driver which is configured under <code>app/config/cache.php</code> Or should i say the same cache system that has been documented here - <a href="http://laravel.com/docs/cache">Cache</a>. So if you pass min and key to <code>remember()</code>, you can use the same key to clear the cache using <code>Cache::forget()</code> method and in fact, you can pretty much use all the <code>Cache</code> methods listed on the <a href="http://laravel.com/docs/cache">official site</a>, like <code>Cache::get()</code>, <code>Cache::add()</code>, <code>Cache::put()</code>, etc. But i don't recommend you to use those other methods unless you know what you're doing.</p> <p>Here's an example for you and others to understand what i mean.</p> <p><code>Article::with('comments')-&gt;remember(5, 'article_comments')-&gt;get();</code></p> <p>Now the above query result will be cached and will be associated with the <code>article_comments</code> key which can then be used to clear it anytime (In my case, I do it when i update).</p> <p>So now if i want to clear that cache regardless of how much time it remembers for. I can just do it by calling <code>Cache::forget('article_comments');</code> and it should work just as expected.</p> <p>Hope this helps everyone :)</p>
441,161
How to convert code from C# to PHP
<p>I have a business logic classes that are written in pure C# (without any specific things from this language) and I would convert this code into PHP. I can write my own parser, but think if I could someone did it before me. </p> <p>Could you please tell me where can I find this kind of converter?</p> <p>Ps. As I've written I use only plain C# programming in this language. Only arguments, declarations of variables, equations and control statements.</p>
441,205
5
1
null
2009-01-13 22:44:12.983 UTC
4
2019-06-10 04:04:35.57 UTC
null
null
null
tomaszs
38,940
null
1
11
c#|php|parsing|converter
50,860
<p>I know you're hoping for someone who had experience but in case no one comes forward...</p> <p>You might consider just copy and pasting the code into a PHP script and checking what breaks. Write a parser to fix that, run it across the entire script, and see what's the next thing that breaks. Continue until the script functions as expected.</p> <p>If you're not using any of the more involved .Net classes I can't imagine you'll have too much trouble.</p>
1,257,507
What does this mean const int*& var?
<p>I saw someone using this in one answer:</p> <pre><code>void methodA(const int*&amp; var); </code></pre> <p>I couldn't understand what the argument means.</p> <p>AFAIK:</p> <ul> <li><p><code>const int var</code> =&gt; <code>const int</code> value which can't be changed</p> </li> <li><p><code>const int* var</code> =&gt; pointer to <code>const int</code>, ie <code>*var</code> can't be changed but <code>var</code> can be changed</p> </li> <li><p><code>const int&amp; var</code> =&gt; reference to <code>const int</code>, ie value of <code>var</code> can't be changed</p> </li> </ul> <p>What does <code>const int*&amp; var</code> mean? Is <code>const int&amp; *var</code> also possible?</p> <p>Can you please give some example as well, like what can and can't be done with it?</p> <p><strong>UPDATE</strong>:</p> <p>I am not sure if I am thinking the right way, but I began to think of a reference as an alias of the variable that was passed as argument, so:</p> <p><code>const int * p;</code></p> <p><code>methodA(p)</code> =&gt; here we are passing <code>p</code> as <code>const int *</code> but we don't know if this is pass by value or what, until we see the definition of <code>methodA</code>, so if <code>methodA</code> is like this:</p> <p><code>methodA(const int * &amp; p2)</code> ==&gt; here <code>p2</code> is another name to <code>p</code>, ie <code>p</code> and <code>p2</code> are the same from now on</p> <p><code>methodA(const int* p2)</code> ==&gt; here <code>p2</code> is passed as value, ie <code>p2</code> is just local to this method</p> <p>Please correct me if I am thinking the wrong way. If yes, I might need to study some more about this. Can you please point to some nice references?</p> <p><strong>UPDATE 2</strong>:</p> <p>If some beginner like me wants to know more about this thing, you can use the <strong>c++decl</strong> / <strong>cdecl</strong> program from <a href="https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation/859676#859676">here</a>, which I just discovered to be very useful.</p> <pre><code>$ c++decl Type `help' or `?' for help c++decl&gt; explain const int&amp;* p declare p as pointer to reference to const int c++decl&gt; explain const int*&amp; p declare p as reference to pointer to const int </code></pre> <p>But, as every one here pointed out, the first example isn't legal in C++.</p>
1,257,514
5
0
null
2009-08-10 22:10:42.623 UTC
18
2021-09-23 00:22:49.347 UTC
2021-09-23 00:22:49.347 UTC
null
65,863
null
142,312
null
1
29
c++
36,254
<p>It is a reference to a pointer to an int that is const.</p> <p>There is another post somewhat related, actually, <a href="https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation/859676#859676">here</a>. My answer gives a sorta of general algorithm to figuring these things out.</p> <p>This: <code>const int&amp; *var</code> has no meaning, because you cannot have a pointer to reference.</p> <p>If the const's and pointers are getting in the way, remember you can typedef these things:</p> <pre><code>typedef int* IntPointer; typedef const IntPointer ConstIntPointer; void foo(ConstIntPointer&amp;); // pass by reference void bar(const ConstIntPointer&amp;); // pass by const reference void baz(ConstIntPointer); // pass by value </code></pre> <p>Might make it easier to read.</p> <hr> <p>If you need more help on C++, <a href="https://isocpp.org/faq/" rel="noreferrer">read this</a>. More specifically, <a href="https://isocpp.org/wiki/faq/references" rel="noreferrer">references</a>.</p> <p>References as variables do <em>not</em> take space:</p> <pre><code>int i; // takes sizeof(int) int*pi = &amp;i; // takes sizeof(int*) int&amp; ri = i; // takes no space. // any operations done to ri // are simply done to i </code></pre> <p>References as parameters use pointers to achieve the end effect:</p> <pre><code>void foo(int&amp; i) { i = 12; } void foo_transformed(int *i) { *i = 12; } int main() { int i; foo(i); // same as: foo_transformed(&amp;i); // to the compiler (only sort of) } </code></pre> <p>So it's actually passing the address of <code>i</code> on the stack, so takes <code>sizeof(int*)</code> space on the stack. But don't start thinking about references as pointers. They are <em>not</em> the same.</p>
662,328
What is a simple C or C++ TCP server and client example?
<p>I need to quickly implement a very small C or C++ TCP server/client solution. This is simply to transfer literally an array of bytes from one computer to another - doesn't need to be scalable / over-complicated. The simpler the better. Quick and dirty if you can.</p> <p>I tried to use the code from this tutorial, but I couldn't get it to build using g++ in Linux: <a href="http://www.linuxhowtos.org/C_C++/socket.htm" rel="noreferrer">http://www.linuxhowtos.org/C_C++/socket.htm</a></p> <p>If possible, I'd like to avoid 3rd party libraries, as the system I'm running this on is quite restricted. This must be C or C++ as the existing application is already implemented.</p> <p>Thanks to <strong>emg-2</strong>'s answer, I managed to make the above mentioned code sample compatible with C++ using the following steps:</p> <p>Add these headers to both client and server:</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;unistd.h&gt; </code></pre> <p>In <a href="http://www.linuxhowtos.org/data/6/server.c" rel="noreferrer">server.c</a>, change the type of clilen to socklen_t.</p> <pre><code>int sockfd, newsockfd, portno/*, clilen*/; socklen_t clilen; </code></pre> <p>In <a href="http://www.linuxhowtos.org/data/6/client.c" rel="noreferrer">client.c</a>, change the following line:</p> <pre><code>if (connect(sockfd,&amp;serv_addr,sizeof(serv_addr)) &lt; 0) { ... } </code></pre> <p>To:</p> <pre><code>if (connect(sockfd,(const sockaddr*)&amp;serv_addr,sizeof(serv_addr)) &lt; 0) </code></pre>
662,356
5
0
null
2009-03-19 14:02:28.177 UTC
27
2021-04-28 06:45:52.17 UTC
2017-02-19 18:31:55.153 UTC
Cade Roux
47,775
null
47,775
null
1
48
c++|tcp|client-server
153,868
<p>I've used <a href="https://www.beej.us/guide/bgnet/html" rel="nofollow noreferrer">Beej's Guide to Network Programming</a> in the past. It's in C, not C++, but the examples are good. Go directly to <a href="https://www.beej.us/guide/bgnet/html/#client-server-background" rel="nofollow noreferrer">section 6</a> for the simple client and server example programs.</p>
686,452
Create WCF service for unmanaged C++ clients
<p>I need to get unmanaged Windows C++ clients to talk to a WCF service. C++ clients could be running on Win2000 and later. I have a control over both WCF service and which C++ API is being used. Since it's for a proprietary application, it is preferable to use Microsoft stuff where possible, definitely not GNU licensed APIs. Those of you who have it working, can you share a step-by-step process how to make it working?</p> <p>I have researched following options so far:</p> <ul> <li>WWSAPI - not good, will not work on Win 2000 clients.</li> <li>ATL Server, used <a href="http://icoder.wordpress.com/2007/07/25/consuming-a-wcf-service-with-an-unmanaged-c-client-with-credential-passing/" rel="noreferrer">following guide</a> as a reference. I followed the steps outlined (remove policy refs and flatten WSDL), however the resulting WSDL is still not usable by sproxy</li> </ul> <p>Any more ideas? Please answer only if you actually have it working yourself.</p> <p><strong><em>Edit1</em></strong>: I apologize for anyone who I might have confused: what I was looking for was a way to call WCF service from client(s) where no .NET framework is installed, so using .NET-based helper library is not an option, it must be pure unmanaged C++</p>
687,904
5
2
null
2009-03-26 16:14:10.557 UTC
31
2022-07-12 00:33:25.75 UTC
2009-03-30 15:51:19.61 UTC
galets
14,395
galets
14,395
null
1
60
c++|wcf|web-services|soap|wsdl
53,139
<p>For those who are interested, I found one semi-working ATL Server solution. Following is the host code, notice it is using BasicHttpBinding, it's the only one which works with ATL Server:</p> <pre><code> var svc = new Service1(); Uri uri = new Uri("http://localhost:8200/Service1"); ServiceHost host = new ServiceHost(typeof(Service1), uri); var binding = new BasicHttpBinding(); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), binding, uri); endpoint.Behaviors.Add(new InlineXsdInWsdlBehavior()); host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true }); var mex = host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); host.Open(); Console.ReadLine(); </code></pre> <p>code for InlineXsdInWsdlBehavior could be found <a href="http://www.winterdom.com/weblog/2006/10/03/InlineXSDInWSDLWithWCF.aspx" rel="noreferrer">here</a> . One important change needs to be done to the InlineXsdInWsdlBehavior in order for it to work properly with sproxy when complex types are involved. It is caused by the bug in sproxy, which does not properly scope the namespace aliases, so wsdl cannot have repeating namespace aliases or sproxy will crap out. Here's the functions which needs to change:</p> <pre><code> public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context) { int tnsCount = 0; XmlSchemaSet schemaSet = exporter.GeneratedXmlSchemas; foreach (WsdlDescription wsdl in exporter.GeneratedWsdlDocuments) { // // Recursively find all schemas imported by this wsdl // and then add them. In the process, remove any // &lt;xsd:imports/&gt; // List&lt;XmlSchema&gt; importsList = new List&lt;XmlSchema&gt;(); foreach (XmlSchema schema in wsdl.Types.Schemas) { AddImportedSchemas(schema, schemaSet, importsList, ref tnsCount); } wsdl.Types.Schemas.Clear(); foreach (XmlSchema schema in importsList) { RemoveXsdImports(schema); wsdl.Types.Schemas.Add(schema); } } } private void AddImportedSchemas(XmlSchema schema, XmlSchemaSet schemaSet, List&lt;XmlSchema&gt; importsList, ref int tnsCount) { foreach (XmlSchemaImport import in schema.Includes) { ICollection realSchemas = schemaSet.Schemas(import.Namespace); foreach (XmlSchema ixsd in realSchemas) { if (!importsList.Contains(ixsd)) { var new_namespaces = new XmlSerializerNamespaces(); foreach (var ns in ixsd.Namespaces.ToArray()) { var new_pfx = (ns.Name == "tns") ? string.Format("tns{0}", tnsCount++) : ns.Name; new_namespaces.Add(new_pfx, ns.Namespace); } ixsd.Namespaces = new_namespaces; importsList.Add(ixsd); AddImportedSchemas(ixsd, schemaSet, importsList, ref tnsCount); } } } } </code></pre> <p>Next step is to generate C++ header: </p> <pre><code>sproxy.exe /wsdl http://localhost:8200/Service1?wsdl </code></pre> <p>and then C++ program looks like this:</p> <pre><code>using namespace Service1; CoInitializeEx( NULL, COINIT_MULTITHREADED ); { CService1T&lt;CSoapWininetClient&gt; cli; cli.SetUrl( _T("http://localhost:8200/Service1") ); HRESULT hr = cli.HelloWorld(); //todo: analyze hr } CoUninitialize(); return 0; </code></pre> <p>Resulting C++ code handles complex types pretty decently, except that it cannot assign NULL to the objects.</p>
106,425
Load external JS from bookmarklet?
<p>How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.</p>
106,438
5
0
null
2008-09-19 23:39:49.433 UTC
24
2022-09-10 05:28:52.737 UTC
2015-05-07 23:03:37.693 UTC
null
1,002,260
nilihm
401,774
null
1
75
javascript|load|external|bookmarklet
21,792
<h3>2015 Update</h3> <p><a href="https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy" rel="noreferrer">Content security policy</a> will prevent this from working in many sites now. For example, the code below won't work on Facebook.</p> <h3>2008 answer</h3> <p>Use a bookmarklet that creates a script tag which includes your external JS.</p> <p>As a sample:</p> <pre><code>javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})(); </code></pre>
655,011
Can you create a setup.exe in qt to install your app on a client computer
<p>I have created a desktop app and now I need to install in on a client's computer.</p> <p>However, the client would like to have a wizard to install. Like Visual Studio setup project allows you to add an installer.</p> <p>Does Qt allow you to create an installer or do I need to use a 3rd party installer like InstallShield or Wise?</p>
657,852
6
0
null
2009-03-17 16:33:19.88 UTC
15
2017-01-18 11:55:18.287 UTC
2017-01-18 11:55:18.287 UTC
null
1,908,677
robUK
70,942
null
1
16
qt|installation|qt-installer
26,952
<p>You definitely need a third party installer. A few good ones have already been mentioned. If you decide to go with a paid solution <a href="http://bitrock.com/products_installbuilder_overview.html" rel="noreferrer">bitrock's installer</a> is a perfect choice and they are also Qt centric and their main business is around Qt.</p> <p>As an open source alternative I would suggest <a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NSIS</a></p>
154,762
How can I create XML from Perl?
<p>I need to create XML in Perl. From what I read, <a href="http://search.cpan.org/dist/XML-LibXML" rel="noreferrer">XML::LibXML</a> is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is <a href="http://search.cpan.org/dist/XML-Writer" rel="noreferrer">XML::Writer</a> still maintained? Does anyone like/use it?</p> <p>In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer.</p> <p>Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular.</p> <p>Thanks!</p>
155,010
6
0
null
2008-09-30 20:08:30.243 UTC
9
2022-07-13 12:51:06.52 UTC
2010-01-08 13:21:47.01 UTC
null
2,766,176
pkaeding
4,257
null
1
28
xml|perl
37,392
<p>XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there. </p> <p>As for describing the syntax, one is better to look at the module's documentation (the link is already in the question). To wit:</p> <pre><code>use XML::Writer; my $writer = new XML::Writer(); # will write to stdout $writer-&gt;startTag("greeting", "class" =&gt; "simple"); $writer-&gt;characters("Hello, world!"); $writer-&gt;endTag("greeting"); $writer-&gt;end(); # produces &lt;greeting class='simple'&gt;Hello world!&lt;/greeting&gt; </code></pre>
658,749
How can I determine which w3wp.exe process belongs to which web site?
<p>I have an IIS6 web server that is hosting two application pools. Occasionally, one of the w3wp processes will spike the CPU for a while, and both app pools seem to suffer the consequences. I'm not sure which one is which, and without that information I don't know which application to blame.</p> <p>How can I tell which w3wp belongs to which App Pool?</p>
658,790
6
0
null
2009-03-18 15:25:07.597 UTC
11
2022-04-04 08:38:18.867 UTC
null
null
null
Michael Bray
50,356
null
1
28
iis-6|w3wp
19,571
<p>Goto cmd window then type <code>c:\windows\system32\cscript c:\windows\system32\iisapp.vbs</code>.</p> <p>Now you will get the list of worker processes along with the app pool name.</p>