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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,492,167 | Group query results by month and year in postgresql | <p>I have the following database table on a Postgres server: </p>
<pre><code>id date Product Sales
1245 01/04/2013 Toys 1000
1245 01/04/2013 Toys 2000
1231 01/02/2013 Bicycle 50000
456461 01/01/2014 Bananas 4546
</code></pre>
<p>I would like to create a query that gives the <code>SUM</code> of the <code>Sales</code> column and groups the results by month and year as follows:</p>
<pre><code>Apr 2013 3000 Toys
Feb 2013 50000 Bicycle
Jan 2014 4546 Bananas
</code></pre>
<p>Is there a simple way to do that?</p> | 17,492,310 | 7 | 0 | null | 2013-07-05 15:18:24.213 UTC | 50 | 2021-09-24 05:59:09.193 UTC | 2013-07-05 20:17:43.46 UTC | null | 2,019,415 | null | 2,554,248 | null | 1 | 221 | sql|postgresql | 203,144 | <pre><code>select to_char(date,'Mon') as mon,
extract(year from date) as yyyy,
sum("Sales") as "Sales"
from yourtable
group by 1,2
</code></pre>
<p>At the request of Radu, I will explain that query:</p>
<p><code>to_char(date,'Mon') as mon,</code> : converts the "date" attribute into the defined format of the short form of month.</p>
<p><code>extract(year from date) as yyyy</code> : Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.</p>
<p><code>sum("Sales") as "Sales"</code> : The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.</p>
<p><code>group by 1,2</code> : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.</p> |
26,028,700 | Write to Client UDP Socket in Go | <p>I'm looking for a good solution for a client/server communication with UDP sockets in Go language.</p>
<p>The examples I found on the Internet show me how to send data to the server, but they do not teach how to send them back to the client.</p>
<p>To demonstrate, my program does the following:</p>
<p>My client program creates a socket on the 4444 port, like this:</p>
<pre><code>con, err := net.Dial("udp", "127.0.0.1:4444")
</code></pre>
<p>I sent a string and the local address to the server, so it could print the string and send an OK message. I am using gob for this:</p>
<pre><code>enc := gob.NewEncoder(con)
enc.Encode(Data{"test", con.LocalAddr().String()})
</code></pre>
<p>My Data struct looks like this:</p>
<pre><code>type Data struct{
Msg string
Addr string
}
</code></pre>
<p>My server listens to the 4444 port and decodes the Gob correctly, but how can I send the OK message back? I'm using the client address to do so (on the server .go file):</p>
<pre><code>con, err := net.Dial("udp", data.Addr)
</code></pre>
<p>Then, I get an error code:</p>
<pre><code>write udp 127.0.0.1:35290: connection refused
</code></pre>
<p>When the client tries to connect to the Server's port 4444, the client creates a port with a random number (in this case, 35290) so they can communicate. I know I shouldn't be passing the client's address to the server, but conn.RemoteAddress() does not work. A solution that discovers the client's address would be most appreciated.</p>
<p>Obs.: I know there is ReadFromUDP, so I can read the package. Should I read it, discover the client's address, and send the data to Gob so it can decode it?</p> | 26,032,240 | 3 | 3 | null | 2014-09-25 00:39:18.14 UTC | 7 | 2022-01-06 03:06:56.8 UTC | 2014-09-25 02:07:04.157 UTC | null | 4,017,302 | null | 3,381,662 | null | 1 | 22 | sockets|go|udp|gob | 50,357 | <p>Check the below samples for client/server communication over UDP. The sendResponse routine is for sending response back to client.</p>
<p><strong>udpclient.go</strong></p>
<pre><code>package main
import (
"fmt"
"net"
"bufio"
)
func main() {
p := make([]byte, 2048)
conn, err := net.Dial("udp", "127.0.0.1:1234")
if err != nil {
fmt.Printf("Some error %v", err)
return
}
fmt.Fprintf(conn, "Hi UDP Server, How are you doing?")
_, err = bufio.NewReader(conn).Read(p)
if err == nil {
fmt.Printf("%s\n", p)
} else {
fmt.Printf("Some error %v\n", err)
}
conn.Close()
}
</code></pre>
<p><strong>udpserver.go</strong></p>
<pre><code>package main
import (
"fmt"
"net"
)
func sendResponse(conn *net.UDPConn, addr *net.UDPAddr) {
_,err := conn.WriteToUDP([]byte("From server: Hello I got your message "), addr)
if err != nil {
fmt.Printf("Couldn't send response %v", err)
}
}
func main() {
p := make([]byte, 2048)
addr := net.UDPAddr{
Port: 1234,
IP: net.ParseIP("127.0.0.1"),
}
ser, err := net.ListenUDP("udp", &addr)
if err != nil {
fmt.Printf("Some error %v\n", err)
return
}
for {
_,remoteaddr,err := ser.ReadFromUDP(p)
fmt.Printf("Read a message from %v %s \n", remoteaddr, p)
if err != nil {
fmt.Printf("Some error %v", err)
continue
}
go sendResponse(ser, remoteaddr)
}
}
</code></pre> |
23,300,953 | When debugging in device with ART enabled, android app is slow | <p>i dont know why but a week ago when i am debugging my app in android studio, the app in device is very slow, but if a generate the APK or use the play (Not debug) option works fine..</p>
<p>Anyone have idea why? I think i didnt any change in sdk or in the app to do it this..</p> | 23,301,174 | 1 | 9 | null | 2014-04-25 18:57:04.19 UTC | 5 | 2014-10-16 11:30:32.467 UTC | 2014-06-03 18:29:23.197 UTC | null | 168,868 | null | 988,283 | null | 1 | 28 | android|debugging|art-runtime | 8,872 | <p>When ART is enabled, the device cannot ensure the compiled code matches the bytecode instructions. It therefore cannot step through instructions and therefore lines.</p>
<p>This forces the device to fallback to a very slow interpreter, which possibly doesn't even JIT-compile.</p>
<p>For faster debugging, switch back to Dalvik.</p> |
4,980,348 | When SVN fails to merge and Mercurial succeeds | <p>Before it comes up, I've already looked at several threads on this topic, including these:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/2475831/merging-hg-git-vs-svn/2486662#2486662">Merging: Hg/Git vs. SVN</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/4592740/mercurial-compared-to-private-branches-in-svn">Mercurial compared to private branches in SVN</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/43995/why-is-branching-and-merging-easier-in-mercurial-than-in-subversion">Why is branching and merging easier in Mercurial than in Subversion?</a></p></li>
</ul>
<p>I'm looking at switching to Mercurial (from Subversion) for our development group. Before I do so I'm doing the usual pros / cons list.</p>
<p>One of my "pros" is that merging is superior in Mercurial, but so far I'm failing to find compelling evidence of that. Namely, there is a statement made on HgInit.com that I've been unable to verify:</p>
<blockquote>
<p>For example, if I change a function a little bit, and then move it somewhere else, Subversion doesn’t really remember those steps, so when it comes time to merge, it might think that a new function just showed up out of the blue. Whereas Mercurial will remember those things separately: function changed, function moved, which means that if you also changed that function a little bit, it is much more likely that Mercurial will successfully merge our changes.</p>
</blockquote>
<p>This would be extremely compelling functionality, but as far as I can tell, it's just hot air. I've been unable to verify the above statement. </p>
<p>I created a Mercurial repository, did a Hello World and then cloned it. In one I modified the function, committed it and then moved it, and then committed it. In the other I simply added another output line in the function and committed.</p>
<p>When I merge, I get basically the same merge conflict I would get using Subversion.</p>
<p>I get that mercurial can track <a href="https://stackoverflow.com/questions/2475831/merging-hg-git-vs-svn/2486662#2486662">file renames</a> better and that there are other advantages to DVCS besides merging, but I'm interested in this example. Is Joel Spolsky off-base here, or am I missing something?</p>
<p>I'm not experienced in this area, but it does seem like since Mercurial keeps more information that it <em>could</em>, in theory, do better at merging (if developers also did frequent checkins). For example, I see it as feasible for Mercurial to get contextual changes from comparing multiple changes, e.g., I modify a function, check in, move the function, check in, and Mercurial associates those two pieces.</p>
<p>However, Mercurial's merging doesn't seem to actually take advantage of the added information, and appears to be operate the same way as Subversion. Is this correct?</p> | 4,981,277 | 3 | 5 | null | 2011-02-12 20:11:03.36 UTC | 9 | 2012-03-06 21:07:37.197 UTC | 2017-05-23 11:44:22.297 UTC | null | -1 | null | 614,513 | null | 1 | 19 | svn|mercurial|merge|branching-and-merging | 1,200 | <p>As far as I know, anyone who says Mercurial tracks moving code around in less than file-sized chunks is just wrong. It <em>does</em> track file renames independently from code changes, so if Dave renames a file and Helen changes something in the file, it can automerge that, but as far as I know, Subversion can do that too! (CVS can't.)</p>
<p>But there <em>is</em> a way in which Mercurial's merge logic is dramatically better than Subversion's: it remembers conflict resolutions. Consider this history graph:</p>
<pre><code>base ---> HELEN1 ---> merge1 --> HELEN2 -> merge2
\--> DAVE1 ---/ /
\--> DAVE2 ---------/
</code></pre>
<p>Helen and Dave made changes independently. Helen pulled Dave's tree and merged, then made another change on top of that. Meantime, Dave went on coding without bothering to pull from Helen. Then Helen pulled Dave's tree again. (Maybe Dave is working on the main development trunk, and Helen's off on a feature branch, but she wants to sync up with trunk changes periodically.) When constructing "merge2", Mercurial would remember all of the conflict resolutions done in "merge1" and only show Helen <em>new</em> conflicts, but Subversion would make Helen do the merge all over again from scratch. (There are ways you can avoid having to do that with Subversion, but they all involve extra manual steps. Mercurial handles it for you.)</p>
<p>For more information, read about the <a href="http://wiki.monotone.ca/MarkMerge/" rel="nofollow">mark-merge algorithm</a> which was developed for Monotone and AFAIK is now used by both Mercurial and Git.</p> |
5,197,035 | "Gift App" from inside the app | <p>I noticed that on the latest angry birds update they added a feature to gift your app from inside the app.</p>
<p>Up till now I knew you can gift paid apps from the iTunes itself. Does anybody know what link should I use to access this mechanism from inside the app itself?</p>
<p>Thanks!</p> | 5,199,511 | 3 | 1 | null | 2011-03-04 17:19:07.39 UTC | 32 | 2015-11-26 10:35:12.25 UTC | 2015-11-26 10:35:12.25 UTC | null | 1,505,120 | null | 172,637 | null | 1 | 49 | ios|objective-c|iphone|ipad | 9,630 | <p>If you watch what happens when you click that button, you can see that it initially makes a request to a redirect script on www.angrybirds.com:</p>
<p><a href="http://www.angrybirds.com/redirect.php?device=iphone&product=angrybirds&type=purchasegift" rel="noreferrer">http://www.angrybirds.com/redirect.php?device=iphone&product=angrybirds&type=purchasegift</a></p>
<p>From there you are redirected to a secure url of the form:</p>
<p><a href="https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/giftSongsWizard?gift=1&salableAdamId=343200656&productType=C&pricingParameter=STDQ" rel="noreferrer">https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/giftSongsWizard?gift=1&salableAdamId=343200656&productType=C&pricingParameter=STDQ</a></p>
<p>343200656 is the AppleID for Angry Birds.</p> |
4,977,252 | Why an unnamed namespace is a "superior" alternative to static? | <p>The section $7.3.1.1/2 from the C++ Standard reads:</p>
<blockquote>
<p>The use of the static keyword is
deprecated when declaring objects in a
namespace scope; the unnamed-namespace
provides <strong>a superior alternative.</strong></p>
</blockquote>
<p>I don't understand why an unnamed namespace is considered a superior alternative? What is the rationale? I've known for a long time as to what the standard says, but I've never seriously thought about it, even when I was replying to this question: <a href="https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static">Superiority of unnamed namespace over static?</a></p>
<p>Is it considered superior because it can be applied to user-defined types as well, as I described in my <a href="https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static/4422554#4422554">answer</a>? Or is there some other reason as well, that I'm unaware of? I'm asking this, particularly because that is my reasoning in my answer, while the standard might have something else in mind.</p> | 4,977,525 | 3 | 11 | null | 2011-02-12 09:04:17.867 UTC | 60 | 2017-04-30 14:31:35.413 UTC | 2017-05-23 11:46:49.27 UTC | null | -1 | null | 415,784 | null | 1 | 110 | c++|namespaces|standards|iso | 41,735 | <ul>
<li>As you've mentioned, namespace works for anything, not just for functions and objects.</li>
<li>As Greg has pointed out, <code>static</code> means too many things already.</li>
<li>Namespaces provide a uniform and consistent way of controlling visibility at the global scope. You don't have to use different tools for the same thing.</li>
<li>When using an anonymous namespace, the function/object name will get mangled properly, which allows you to see something like "(anonymous namespace)::xyz" in the symbol table after de-mangling, and not just "xyz" with static linkage.</li>
<li>As pointed out in the comments below, it isn't allowed to use static things as template arguments, while with anonymous namespaces it's fine.</li>
<li>More? Probably, but I can't think of anything else right now.</li>
</ul> |
5,135,900 | Stack around the variable ' ' was corrupted | <pre><code>void GameBoard::enterShips()
{
char location[1];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location;
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
</code></pre>
<p>Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.</p>
<blockquote>
<p>Stack around the variable location was corrupted.</p>
</blockquote>
<p>Ive looked for answers online and have not found anything exclusive.</p>
<p>Any help would be appreciated.</p> | 5,135,934 | 4 | 1 | null | 2011-02-27 20:57:48.167 UTC | 1 | 2011-02-28 06:58:26.24 UTC | 2011-02-27 20:58:55.783 UTC | null | 36,384 | null | 636,824 | null | 1 | 8 | c++ | 70,421 | <p>You are prompting the memory address of <code>location</code> array to your user. You should ask location indices separately:</p>
<pre><code>void GameBoard::enterShips()
{
int location[2];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location[0];
cin >> location[1];
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
</code></pre>
<p>Notice <code>int location[2];</code> since an array of size 1 can only hold one element. I also changed the element type to int. Reading char's from the console will result in ASCII values, which are probably not what you want.</p> |
18,746,569 | Force div element to stay in same place, when page is scrolled | <p>I created a <code>div</code> element, that I placed all the way on the right of my site. The only problem is that its at the top of the site, so if i scroll down it remains there.</p>
<p>How can I force it to remain in the same part of the page, when page is being scrolled?</p>
<p>This is, what I've managed to figure out myself so far:</p>
<pre><code><div style="width: 200px; background-color: #999; z-index: 10; position: absolute; right: 0; top: 0; height: 83px;">
</div>
</code></pre> | 18,746,597 | 5 | 3 | null | 2013-09-11 16:30:22.943 UTC | 11 | 2021-03-23 07:51:55.37 UTC | 2015-01-20 21:02:30.063 UTC | null | 1,469,208 | null | 330,396 | null | 1 | 41 | css|html | 135,844 | <p>Change <code>position:absolute</code> to <code>position:fixed;</code>.</p>
<p>Example can be found <a href="http://jsfiddle.net/HE5SF/2/" rel="noreferrer">in this jsFiddle</a>.</p> |
18,390,266 | How can we truncate float64 type to a particular precision? | <pre><code>package main
import (
"fmt"
"strconv"
)
func main() {
k := 10/3.0
i := fmt.Sprintf("%.2f", k)
f,_ := strconv.ParseFloat(i, 2)
fmt.Println(f)
}
</code></pre>
<p>I had to write the program above to decrease the precision of a go float64 variable to 2.
In this case I was using both strconv and fmt. Is there some other logical method by which it can be done?</p> | 18,418,551 | 12 | 6 | null | 2013-08-22 20:29:57.793 UTC | 10 | 2022-03-04 13:26:30.433 UTC | 2020-02-26 15:53:13.203 UTC | null | 13,860 | null | 1,089,354 | null | 1 | 74 | floating-point|go | 113,681 | <p>You don't need any extra code ... its as simple as </p>
<pre><code>import (
"fmt"
)
func main() {
k := 10 / 3.0
fmt.Printf("%.2f", k)
}
</code></pre>
<p><a href="http://play.golang.org/p/Ek0if-tlvX" rel="noreferrer">Test Code</a> </p> |
15,280,722 | Android Camera Capture using FFmpeg | <p>Am tryin' to take the preview frame generated by the android camera and pass the <code>data[]</code> to ffmpeg input pipe to generate a flv video.
The command that I used was : </p>
<pre><code>ffmpeg -f image2pipe -i pipe: -f flv -vcodec libx264 out.flv
</code></pre>
<p>I've also tried to force the input format to <code>yuv4mpegpipe</code> and <code>rawvideo</code> but with no success...
The default format of the preview frame generated by android-camera is <code>NV21</code>.
The way am invokin' ffmpeg is through the <code>Process API</code> and writing the preview frames <code>data[]</code> to the process' <code>stdin</code>...
The <code>onPreviewFrame()</code> definition is as follows : </p>
<pre><code>public void onPreviewFrame(byte[] data, Camera camera)
{
try
{
processIn.write(data);
}
catch(Exception e)
{
Log.e(TAG, FUNCTION + " : " + e.getMessage());
}
camera.addCallbackBuffer(new byte[bufferSize]);
}
</code></pre>
<p><code>processIn</code> is connected to the <code>ffmpeg</code> process <code>stdin</code> and <code>buffersize</code> is computed based on the documentation provided for <code>addCallbackBuffer()</code>.
Is there something that am doin' wrong...?</p>
<p>Thanks...</p> | 15,290,723 | 1 | 2 | null | 2013-03-07 20:07:24.99 UTC | 8 | 2013-03-08 11:15:13.94 UTC | null | null | null | null | 1,712,427 | null | 1 | 9 | android|ffmpeg|android-camera | 10,383 | <p>Kinda got it working perfectly...
The mistake that seemed to be happenin' was related to the <code>vcodec</code> of the image stream.
Seems that ffmpeg has no provision to decode <code>NV21</code> format images or image stream.
For that had to convert the <code>NV21</code> format preview frame to <code>JPEG</code> and as the images had to streamed in real time to the <code>ffmpeg</code> process ,the conversion had to be <code>On the Fly</code>. The closest reliable solution for <code>On the Fly</code> conversion to <code>JPEG</code> was as follows : </p>
<pre><code>public void onPreviewFrame(byte[] data, Camera camera)
{
if(isFirstFrame)
{
Camera.Parameters cameraParam = camera.getParameters();
Camera.Size previewSize = cameraParam.getPreviewSize();
previewFormat = cameraParam.getPreviewFormat();
frameWidth = previewSize.width;
frameHeight = previewSize.height;
frameRect = new Rect(0, 0, frameWidth, frameHeight);
isFirstFrame = false;
}
previewImage = new YuvImage(data, previewFormat, frameWidth, frameHeight, null);
if(previewImage.compressToJpeg(frameRect, 50, processIn))
Log.d(TAG, "Data : " + data.length);
previewImage = null;
camera.addCallbackBuffer(new byte[bufferSize]);
}
</code></pre>
<p>And the <code>ffmpeg</code> command used was : </p>
<pre><code>ffmpeg -f image2pipe -vcodec mjpeg -i - -f flv -vcodec libx264 out.flv
</code></pre> |
14,962,459 | HTML divs, how to wrap content? | <p>I have 3 div's like on this image: </p>
<p><img src="https://i.stack.imgur.com/uPxjk.png" alt="enter image description here"></p>
<p>div1 has fixed width but variable height, so what I would like is that if div1 height is bigger that the div2 height, the div3 stays under div2 and on the right of the div1, like here:</p>
<p><img src="https://i.stack.imgur.com/e9Nwh.png" alt="enter image description here"></p>
<p>Any idea on how to do this? For the moment, I have created a container:</p>
<pre><code><div class="colcontainer">
<div class="col-left">
{% block news %}{% endblock %}
</div>
<div id="main_content">
<div class="col-right">
{% block rightcol %}{% endblock %}
</div>
<div id="content">
<div class="contentwrap">
<div class="itemwrap">
{% block content %}{% endblock %}
</div>
</div>
</div>
<div class="content-bottom"><div class="content-bottom-left"></div></div>
</div>
</div>
</code></pre>
<p>My CSS is like this: </p>
<pre><code>.col-left {
float:left;
padding:0;
margin:0;
width: 300px;
min-height:198px;
}
.col-right {
text-align:left;
padding:0;
margin:0 0 0 200px;
}
#content {
background: none repeat scroll 0 0 #FFFFFF;
float: left;
margin-top: 10px;
padding: 10px;
width: 980px;
}
</code></pre>
<p>Here is the <a href="http://jsfiddle.net/JRbFy" rel="noreferrer">JSFiddle demo</a></p> | 14,963,002 | 10 | 3 | null | 2013-02-19 16:28:21.947 UTC | 9 | 2016-04-12 15:12:16.29 UTC | 2014-04-08 14:22:53.903 UTC | null | 340,390 | null | 1,018,270 | null | 1 | 15 | html|css | 99,009 | <p>As CSS doesn't provide anything for that job yet, you will have to use Javascript.</p>
<p>I would firstly create a page like on your first picture.
Then I would use</p>
<pre><code>$("#div").height()
</code></pre>
<p>, which returns the height of your div and compare this to your second div's height:</p>
<pre><code>if($("#div1").height() > $("div2").height())
//change website...
</code></pre>
<p>In the if body put the required css changes... That should do the trick.</p> |
43,479,464 | How to Import a Single Lodash Function? | <p>Using webpack, I'm trying to import <a href="https://lodash.com/docs/4.17.4#isEqual" rel="noreferrer">isEqual</a> since <code>lodash</code> seems to be importing everything. I've tried doing the following with no success:</p>
<pre><code>import { isEqual } from 'lodash'
import isEqual from 'lodash/lang'
import isEqual from 'lodash/lang/isEqual'
import { isEqual } from 'lodash/lang'
import { isEqual } from 'lodash/lang'
</code></pre> | 43,479,515 | 10 | 3 | null | 2017-04-18 18:16:43.16 UTC | 31 | 2022-02-12 15:57:13.48 UTC | 2019-01-15 08:24:38.763 UTC | null | 1,253,156 | null | 4,852,449 | null | 1 | 190 | javascript|lodash | 125,380 | <p>You can install <code>lodash.isequal</code> as a single module without installing the whole <em>lodash</em> package like so:</p>
<pre><code>npm install --save lodash.isequal
</code></pre>
<p>When using ECMAScript 5 and CommonJS modules, you then import it like this:</p>
<pre><code>var isEqual = require('lodash.isequal');
</code></pre>
<p>Using ES6 modules, this would be:</p>
<pre><code>import isEqual from 'lodash.isequal';
</code></pre>
<p>And you can use it in your code:</p>
<pre><code>const obj1 = {username: 'peter'};
const obj2 = {username: 'peter'};
const obj3 = {username: 'gregory'};
isEqual(obj1, obj2) // returns true
isEqual(obj1, obj3) // returns false
</code></pre>
<p>Source: <a href="https://www.npmjs.com/package/lodash.isequal" rel="noreferrer">Lodash documentation</a></p>
<p>After importing, you can use the <code>isEqual</code> function in your code. Note that it is not a part of an object named <code>_</code> if you import it this way, so you
<em>don't</em> reference it with <code>_.isEqual</code>, but directly with <code>isEqual</code>.</p>
<p><strong>Alternative: Using <code>lodash-es</code></strong></p>
<p>As pointed out by <a href="https://stackoverflow.com/a/50402664/1253156">@kimamula</a>:</p>
<p>With webpack 4 and <a href="https://www.npmjs.com/package/lodash-es" rel="noreferrer">lodash-es</a> 4.17.7 and higher, this code works.</p>
<pre><code>import { isEqual } from 'lodash-es';
</code></pre>
<p>This is because webpack 4 supports the <a href="https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free" rel="noreferrer">sideEffects</a> flag and <code>lodash-es</code> 4.17.7 and higher includes the flag (which is set to <code>false</code>).</p>
<p><strong>Why Not Use the Version With the Slash?</strong>
Other answers to this question suggest that you can also use a dash instead of a dot, like so:</p>
<pre><code>import isEqual from 'lodash/isequal';
</code></pre>
<p>This works, too, but there are two minor drawbacks:</p>
<ul>
<li>You have to install the whole <em>lodash</em> package (<code>npm install --save lodash</code>), not just the small separate <em>lodash.isequal</em> package; storage space is cheap and CPUs are fast, so you may not care about this</li>
<li>The resulting bundle when using tools like webpack will be slightly bigger; I found out that bundle sizes with a minimal code example of <code>isEqual</code> are on average 28% bigger (tried webpack 2 and webpack 3, with or without Babel, with or without Uglify)</li>
</ul> |
7,974,102 | Is it possible to pass-through parameter values in Moq? | <p>I need to mock <code>HttpResponseBase.ApplyAppPathModifier</code> in such a way that the parameter <code>ApplyAppPathModifier</code> is called with is automatically returned by the mock.</p>
<p>I have the following code:</p>
<pre><code>var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(/*capture this param*/))
.Returns(/*return it here*/);
</code></pre>
<p>Any ideas?</p>
<p><strong>EDIT:</strong></p>
<p>Found a solution on the first page of Moq documentation (<a href="http://code.google.com/p/moq/wiki/QuickStart" rel="noreferrer">http://code.google.com/p/moq/wiki/QuickStart</a>):</p>
<pre><code>var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.IsAny<string>)
.Returns((string value) => value);
</code></pre>
<p>I suddenly feel a lot stupider, but I guess this is what happens when you write code at 23:30</p> | 7,974,112 | 2 | 2 | null | 2011-11-01 23:19:59.207 UTC | 4 | 2011-11-01 23:32:13.683 UTC | 2011-11-01 23:32:13.683 UTC | null | 169 | null | 169 | null | 1 | 31 | c#|testing|mocking|moq | 12,030 | <p>Use <code>It</code>:</p>
<pre><code>It.Is<MyClass>(mc=>mc == myValue)
</code></pre>
<p>Here you can check the expectation: the value you expect to receive.
In terms of return, just return value you need.</p>
<pre><code>var tempS = string.Empty;
var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.Is<String>(s=>{
tempS = s;
return s == "value I expect";
})))
.Returns(tempS);
</code></pre> |
8,122,592 | Which book(s) to learn sockets programming and TCP network communication? | <p>I will do a few small projects over the next few months and need some books (preferably) or URLs to learn some basic concepts.</p>
<p>In general one PC or embedded device (which varies by project) collects some user input or data from an external hardware device and transmits it to a remote PC which will enter it into a database.</p>
<p>The back-end will be coded in Delphi using Indy socket components. The front-end <em>might</em> be a PC running a Delphi app using the same Indy sockets, but it might equally be a small controller board, probably programmed in C (with neither Windows nor Linux as an o/s, but with some unforeseeable socket support).</p>
<p>So, what I need is</p>
<ol>
<li>something - probably language agnostic - to get me up to speed on sockets programming</li>
<li>conformation that I can just use a stream and write/read to define my own protocol (over TCP/IP) which will be very simple </li>
<li>some overview of general networking (TCP?) concepts; maybe a little on security, general client/server stuff (for instance, I can send some from clients to the server and send a reply, but am not so sure about server initiated communication to a single server or a broadcast to all clients) </li>
<li>anything else?</li>
</ol>
<p>Any recommendations to get me up to speed, at least enough for a small project which would allow me to learn on the job.</p>
<p>Thanks in advance</p> | 8,122,888 | 2 | 2 | null | 2011-11-14 13:53:44.263 UTC | 29 | 2011-11-14 20:35:48.307 UTC | null | null | null | null | 192,910 | null | 1 | 36 | sockets|tcp|network-programming|scada | 35,158 | <p>This is <em>the</em> book to learn TCP/IP, doesn't matter what language you will be using:</p>
<p><a href="http://www.kohala.com/start/tcpipiv1.html" rel="noreferrer"><strong>W. Richard Stevens, TCP/IP Illustrated, Volume 1: The Protocols</strong></a></p>
<p>The following is the C network programmer's bible, highly recommended:</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0131411551" rel="noreferrer" rel="nofollow noreferrer"><strong>W. Richard Stevens, Unix Network Programming, Volume 1: The Sockets Networking API</strong></a></p>
<p>Out of online resources, <a href="http://beej.us/guide/bgnet/" rel="noreferrer"><strong>Beej's Guide to Network Programming</strong></a> tops the list.</p> |
14,536,139 | How to input a string in a 2d array in C? | <p>If i want to take an input in a 2d array with each string in one row, and the next in the other(i.e. change the row on pressing enter). How can i do that in C. C doesnt seem to have convenient "String" Handling. I obviously mean doing so without the use of getchar().</p> | 14,536,859 | 3 | 1 | null | 2013-01-26 10:40:15.42 UTC | 3 | 2013-01-27 06:09:47.813 UTC | null | null | null | null | 1,803,855 | null | 1 | 2 | c|string|multidimensional-array | 67,676 | <pre><code>#include<stdio.h>
main()
{
char student_name[5][25];
int i;
for(i=0;i<5;i++)
{
printf("\nEnter a string %d: ",i+1);
scanf(" %[^\n]",student_name[i]);
}
}
</code></pre>
<p>u can read strings using 2d array without using getchar() by putting space in scanf(" %[^\n]")
; before %[^\n]! </p> |
8,797,597 | Timezone Strategy | <p>I am building a MVC 3 application where the users may not be in the same time zone, so my intent was to store everything in UTC and convert from UTC to local time in the views and localtime to UTC on submissions.</p>
<p>Doing some browsing though there doesn't seem to be a lot of good solutions to this. To be honest, I sort of expected an attribute to be available to auto convert UTC time into local time at least, but it seems not to exist.</p>
<p>I feel like just trying to be diligent about manually converting every input to UTC and manually converting every view to local time display will be very error prone and lead to difficult to detect bugs where the time is not converted to or from.</p>
<p>Any suggestions on how to deal with this as a general strategy?</p>
<p><strong><em>EDIT</em></strong>
Everyone seems very stuck on the "how do I get the client timezone" piece, which as I mention in one of the comments is not my concern. I am fine with a user setting that determines their timezone, so assume I already know what the client time zone is...that doesn't address my problem.</p>
<p>Right now, on each view when I render a date, I would need to call a method to render it in the local time zone from utc. Every time I send a date for submission to the server I need to convert it from the local timezone to UTC. If I forget to do this there will be problems...either a submitted date will be wrong or client side reports and filters will be wrong.</p>
<p>What I was hoping existed was a more automated method, especially since the view model is strongly typed in MVC 3 I was hoping for sum magic to be able to at least automatically render in a time zone, if not handle the submission, just like the date format or range can be controlled by an attribute.</p>
<p>So like</p>
<pre><code>[DateRange]
Public DateTime MyDate
</code></pre>
<p>I could have something like </p>
<pre><code>[ConvertToUTC(offset)]
Public DateTime MyDate
</code></pre>
<p>Anyway, I guess it look like my only approach would be to write a custom data annotation to render it in a time zone, and a override on the MVC 3 model binder so incoming dates are converted unless I want to wrap ever date in a method call. So unless anyone has further comments or suggestions it will be one of those two options, I'm just surprised something doesn't exist already to do this.</p>
<p>If I do implement a solution I will be sure to post it.</p>
<p><strong><em>Edit 2</em></strong>
Something like This <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx</a> for MVC 3 views and view models is what I am looking for.</p>
<p><strong><em>Final Edit</em></strong>
I marked epignosisx answer as correct, but also have a few comments to add.
I found something similar here:
<a href="http://dalldorf.com/blog/2011/06/mvc3-timezones-1/" rel="noreferrer">http://dalldorf.com/blog/2011/06/mvc3-timezones-1/</a>
With an implementation of getting the timezone from the client by placing it in the cookie for people that want that in part 2 (link below since the link on the first part of the article to part 2 doesn't work)
<a href="http://dalldorf.com/blog/2011/09/mvc3-timezones-2/" rel="noreferrer">http://dalldorf.com/blog/2011/09/mvc3-timezones-2/</a></p>
<p>Its important to note with these approaches that you MUST you Editfor and Displayfor instead of things like TextForFor as only EditFor and DisplayFor make use of the metadata providers used to tell MVC how to display the property of that type on the model. If you access the model values directly in the view (@Model.MyDate) no conversion will take place.</p> | 8,860,537 | 4 | 5 | null | 2012-01-10 01:41:42.66 UTC | 12 | 2012-01-14 18:05:52.447 UTC | 2012-01-14 18:05:52.447 UTC | null | 474,904 | null | 474,904 | null | 1 | 22 | c#|javascript|asp.net-mvc-3|timezone|utc | 5,919 | <p>You could handle the problem of converting UTC to user local time by using website-wide DisplayTemplate for DateTime. </p>
<p>From your Views you would use @Html.DisplayFor(n => n.MyDateTimeProperty)</p>
<p>The second problem is tougher to tackle. To convert from user local time to UTC you could override the <strong>DefaultModelBinder</strong>. Specifically the method <strong>SetProperty</strong>. Here is a naive implementation that demonstrates the point. It only applies for <strong>DateTime</strong> but could easily be extended to <strong>DateTime?</strong>. Then set it up as your Default binder in the Global.asax</p>
<pre><code>public class MyDefaultModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
//special case for DateTime
if(propertyDescriptor.PropertyType == typeof(DateTime))
{
if (propertyDescriptor.IsReadOnly)
{
return;
}
try
{
if(value != null)
{
DateTime dt = (DateTime)value;
propertyDescriptor.SetValue(bindingContext.Model, dt.ToUniversalTime());
}
}
catch (Exception ex)
{
string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
bindingContext.ModelState.AddModelError(modelStateKey, ex);
}
}
else
{
//handles all other types
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
}
</code></pre> |
5,410,745 | How can I get a list of the items stored in html 5 local storage from javascript? | <p>How can I get a list of the items stored in html 5 local storage from javascript?</p> | 5,410,827 | 6 | 0 | null | 2011-03-23 19:44:31.183 UTC | 15 | 2021-01-05 19:38:55.663 UTC | 2011-03-23 19:54:54.463 UTC | null | 476,945 | null | 243,494 | null | 1 | 50 | javascript|html | 66,176 | <p>From <a href="http://diveintohtml5.info/storage.html" rel="noreferrer">HTML5 reference</a>: </p>
<blockquote>
<p>Like other JavaScript objects, you
can treat the localStorage object as
an associative array. Instead of using
the getItem() and setItem() methods,
you can simply use square brackets.</p>
</blockquote>
<pre><code>localStorage.setItem('test', 'testing 1');
localStorage.setItem('test2', 'testing 2');
localStorage.setItem('test3', 'testing 3');
for(var i in localStorage)
{
console.log(localStorage[i]);
}
//test for firefox 3.6 see if it works
//with this way of iterating it
for(var i=0, len=localStorage.length; i<len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
console.log(key + " => " + value);
}
</code></pre>
<p>This will output: </p>
<pre><code>testing 3
testing 2
testing 1
test3 => testing 3
test2 => testing 2
test => testing 1
</code></pre>
<p>Here is the <a href="http://jsfiddle.net/kjy112/4XnpD/" rel="noreferrer">JSFiddle Demo</a></p> |
5,158,790 | Should I use a data.frame or a matrix? | <p>When should one use a <code>data.frame</code>, and when is it better to use a <code>matrix</code>?</p>
<p>Both keep data in a rectangular format, so sometimes it's unclear.</p>
<p>Are there any general rules of thumb for when to use which data type?</p> | 5,159,049 | 6 | 1 | null | 2011-03-01 18:36:16.523 UTC | 61 | 2018-10-25 06:39:46.707 UTC | 2016-03-23 14:21:54.937 UTC | null | 3,576,984 | null | 639,884 | null | 1 | 161 | r|matrix|dataframe|r-faq | 94,818 | <p>Part of the answer is contained already in your question: You use data frames if columns (variables) can be expected to be of different types (numeric/character/logical etc.). Matrices are for data of the same type. </p>
<p>Consequently, the choice matrix/data.frame is only problematic if you have data of the same type.</p>
<p>The answer depends on what you are going to do with the data in data.frame/matrix. If it is going to be passed to other functions then the expected type of the arguments of these functions determine the choice.</p>
<p>Also:</p>
<p>Matrices are more memory efficient:</p>
<pre><code>m = matrix(1:4, 2, 2)
d = as.data.frame(m)
object.size(m)
# 216 bytes
object.size(d)
# 792 bytes
</code></pre>
<p>Matrices are a necessity if you plan to do any linear algebra-type of operations.</p>
<p>Data frames are more convenient if you frequently refer to its columns by name (via the compact $ operator).</p>
<p>Data frames are also IMHO better for reporting (printing) tabular information as you can apply formatting to each column separately.</p> |
5,379,794 | is Java HashSet thread-safe for read only? | <p>If I have an instance of an HashSet after I ran it through Collections.unmodifiableSet(), is it thread-safe?</p>
<p>I'm asking this since Set documentation states that it's not, but I'm only performing read operations.</p> | 5,379,832 | 7 | 1 | null | 2011-03-21 15:25:21.46 UTC | 8 | 2014-02-19 01:13:12.99 UTC | null | null | null | null | 109,318 | null | 1 | 33 | java|concurrency|hashset | 38,721 | <p>From the Javadoc:</p>
<blockquote>
<p>Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally</p>
</blockquote>
<p>Reading doesn't modify a set, therefore you're fine.</p> |
4,857,855 | Extending Devise SessionsController to authenticate using JSON | <p>I am trying to build a rails API for an iphone app. Devise works fine for logins through the web interface but I need to be able to create and destroy sessions using REST API and I want to use JSON instead of having to do a POST on the sessions controller and having to parse the HTML and deal with a redirect.</p>
<p>I thought I could do something like this:</p>
<pre><code>class Api::V1::SessionsController < Devise::SessionsController
def create
super
end
def destroy
super
end
end
</code></pre>
<p>and in config/routes.rb I added:</p>
<pre><code>namespace :api do
namespace :v1 do
resources :sessions, :only => [:create, :destroy]
end
end
</code></pre>
<p>rake routes shows the routes are setup properly:</p>
<pre><code> api_v1_sessions POST /api/v1/sessions(.:format) {:action=>"create", :controller=>"api/v1/sessions"}
api_v1_session DELETE /api/v1/sessions/:id(.:format) {:action=>"destroy", :controller=>"api/v1/sessions"}
</code></pre>
<p>When I POST to /user/sessions everything works fine. I get some HTML and a 302.</p>
<p>Now if I POST to /api/v1/sessions I get:</p>
<blockquote>
<p>Unknown action
AbstractController::ActionNotFound</p>
</blockquote>
<pre><code>curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/v1/sessions -d "{'user' : { 'login' : 'test', 'password' : 'foobar'}}"
</code></pre> | 4,975,442 | 7 | 1 | null | 2011-02-01 00:59:38.623 UTC | 49 | 2014-06-08 21:51:02.353 UTC | 2011-07-31 16:21:52.47 UTC | null | 38,795 | null | 576,108 | null | 1 | 48 | ruby-on-rails|ruby|authentication|devise | 31,140 | <p>This is what finally worked.</p>
<pre><code>class Api::V1::SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html { super }
format.json {
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
render :status => 200, :json => { :error => "Success" }
}
end
end
def destroy
super
end
end
</code></pre>
<p>Also change routes.rb, remember the order is important.</p>
<pre><code>devise_for :users, :controllers => { :sessions => "api/v1/sessions" }
devise_scope :user do
namespace :api do
namespace :v1 do
resources :sessions, :only => [:create, :destroy]
end
end
end
resources :users
</code></pre> |
4,973,000 | Adding sub-directory to "View/Shared" folder in ASP.Net MVC and calling the view | <p>I'm currently developing a site using ASP.Net MVC3 with Razor. Inside the "View/Shared" folder, I want to add a subfolder called "Partials" where I can place all of my partial views (for the sake of organizing the site better.</p>
<p>I can do this without a problem as long as I always reference the "Partials" folder when calling the views (using Razor):</p>
<pre><code>@Html.Partial("Partials/{ViewName}")
</code></pre>
<p>My question is if there is a way to add the "Partials" folder to the list that .Net goes through when searching for a view, this way I can call my view without having to reference the "Partials" folder, like so:</p>
<pre><code>@Html.Partial("{ViewName}")
</code></pre>
<p>Thanks for the help!</p> | 4,996,869 | 7 | 0 | null | 2011-02-11 19:07:32.15 UTC | 18 | 2017-04-18 13:36:51.753 UTC | null | null | null | null | 613,536 | null | 1 | 51 | asp.net|asp.net-mvc|asp.net-mvc-2|asp.net-mvc-3|razor | 44,250 | <p>Solved this. To add the "Shared/Partials" sub directory I created to the list of locations searched when trying to locate a Partial View in Razor using:</p>
<pre><code>@Html.Partial("{NameOfView}")
</code></pre>
<p>First create a view engine with RazorViewEngine as its base class and add your view locations as follows. Again, I wanted to store all of my partial views in a "Partials" subdirectory that I created within the default "Views/Shared" directory created by MVC.</p>
<pre><code>public class RDDBViewEngine : RazorViewEngine
{
private static readonly string[] NewPartialViewFormats =
{
"~/Views/{1}/Partials/{0}.cshtml",
"~/Views/Shared/Partials/{0}.cshtml"
};
public RDDBViewEngine()
{
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
}
}
</code></pre>
<p>Note that {1} in the location format is the Controller name and {0} is the name of the view.</p>
<p>Then add that view engine to the MVC ViewEngines.Engines Collection in the Application_Start() method in your global.asax:</p>
<pre><code>ViewEngines.Engines.Add(new RDDBViewEngine());
</code></pre> |
5,025,941 | Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag? | <p>Just wondering if there is a way to get a HTML <code><button></code> element to link to a location without wrapping it in an <code><a href...</code> tag?</p>
<p>Button currently looks like:</p>
<pre><code><button>Visit Page Now</button>
</code></pre>
<p>What I would prefer <strong>not</strong> to have:</p>
<pre><code><a href="link.html"><button>Visit Page Now</button></a>
</code></pre>
<p>The button is not being used within a form so <code><input type="button"></code> is not an option. I am just curious to see if there is a way to link this particular element without needing to wrap it in an <code><a href</code> tag.</p>
<p>Looking forward to hearing some options/opinions.</p> | 5,025,990 | 9 | 4 | null | 2011-02-17 06:57:10.76 UTC | 31 | 2021-04-25 16:26:15.637 UTC | 2015-02-01 16:30:46.04 UTC | null | 3,204,551 | null | 605,812 | null | 1 | 57 | javascript|html|button|hyperlink | 298,967 | <p>Inline Javascript:</p>
<pre><code><button onclick="window.location='http://www.example.com';">Visit Page Now</button>
</code></pre>
<p>Defining a function in Javascript:</p>
<pre><code><script>
function visitPage(){
window.location='http://www.example.com';
}
</script>
<button onclick="visitPage();">Visit Page Now</button>
</code></pre>
<p>or in Jquery</p>
<pre><code><button id="some_id">Visit Page Now</button>
$('#some_id').click(function() {
window.location='http://www.example.com';
});
</code></pre> |
4,862,178 | Remove rows with all or some NAs (missing values) in data.frame | <p>I'd like to remove the lines in this data frame that:</p>
<p>a) <strong>contain <code>NA</code>s across all columns.</strong> Below is my example data frame. </p>
<pre><code> gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA NA
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA NA NA
4 ENSG00000207604 0 NA NA 1 2
5 ENSG00000207431 0 NA NA NA NA
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>Basically, I'd like to get a data frame such as the following.</p>
<pre><code> gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>b) <strong>contain <code>NA</code>s in only some columns</strong>, so I can also get this result:</p>
<pre><code> gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre> | 4,862,502 | 17 | 0 | null | 2011-02-01 11:52:31.15 UTC | 432 | 2022-02-08 16:11:28.137 UTC | 2018-08-12 12:32:28.28 UTC | null | 2,204,410 | null | 525,563 | null | 1 | 1,039 | r|dataframe|filter|missing-data|r-faq | 2,160,968 | <p>Also check <a href="http://stat.ethz.ch/R-manual/R-patched/library/stats/html/complete.cases.html" rel="noreferrer"><code>complete.cases</code></a> :</p>
<pre><code>> final[complete.cases(final), ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p><code>na.omit</code> is nicer for just removing all <code>NA</code>'s. <code>complete.cases</code> allows partial selection by including only certain columns of the dataframe:</p>
<pre><code>> final[complete.cases(final[ , 5:6]),]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>Your solution can't work. If you insist on using <code>is.na</code>, then you have to do something like:</p>
<pre><code>> final[rowSums(is.na(final[ , 5:6])) == 0, ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
</code></pre>
<p>but using <code>complete.cases</code> is quite a lot more clear, and faster.</p> |
41,676,054 | How to add fonts to create-react-app based projects? | <p>I'm using <a href="https://github.com/facebook/create-react-app" rel="noreferrer">create-react-app</a> and prefer not to <code>eject</code>.</p>
<p>It's not clear where fonts imported via @font-face and loaded locally should go. </p>
<p>Namely, I'm loading</p>
<pre><code>@font-face {
font-family: 'Myriad Pro Regular';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Regular'), url('MYRIADPRO-REGULAR.woff') format('woff');
}
</code></pre>
<p>Any suggestions?</p>
<p>-- EDIT</p>
<p>Including the gist to which Dan referring in his answer</p>
<pre><code>➜ Client git:(feature/trivia-game-ui-2) ✗ ls -l public/static/fonts
total 1168
-rwxr-xr-x@ 1 maximveksler staff 62676 Mar 17 2014 MYRIADPRO-BOLD.woff
-rwxr-xr-x@ 1 maximveksler staff 61500 Mar 17 2014 MYRIADPRO-BOLDCOND.woff
-rwxr-xr-x@ 1 maximveksler staff 66024 Mar 17 2014 MYRIADPRO-BOLDCONDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 66108 Mar 17 2014 MYRIADPRO-BOLDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 60044 Mar 17 2014 MYRIADPRO-COND.woff
-rwxr-xr-x@ 1 maximveksler staff 64656 Mar 17 2014 MYRIADPRO-CONDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 61848 Mar 17 2014 MYRIADPRO-REGULAR.woff
-rwxr-xr-x@ 1 maximveksler staff 62448 Mar 17 2014 MYRIADPRO-SEMIBOLD.woff
-rwxr-xr-x@ 1 maximveksler staff 66232 Mar 17 2014 MYRIADPRO-SEMIBOLDIT.woff
➜ Client git:(feature/trivia-game-ui-2) ✗ cat src/containers/GameModule.css
.GameModule {
padding: 15px;
}
@font-face {
font-family: 'Myriad Pro Regular';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Regular'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-REGULAR.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Condensed';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-COND.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Semibold Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Semibold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Semibold';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Semibold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLD.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Condensed Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-CONDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Condensed Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCONDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Condensed';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCOND.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLD.woff') format('woff');
}
</code></pre> | 41,678,350 | 12 | 5 | null | 2017-01-16 12:04:46.833 UTC | 108 | 2022-09-11 04:50:59.97 UTC | 2018-09-18 18:43:06.933 UTC | null | 3,951,782 | null | 48,062 | null | 1 | 357 | css|reactjs|fonts|webpack|create-react-app | 398,244 | <p>There are two options:</p>
<h3>Using Imports</h3>
<p>This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.</p>
<p>As <a href="https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files" rel="noreferrer">described in “Adding Images, Fonts, and Files”</a>, you need to have a CSS file imported from JS. For example, by default <code>src/index.js</code> imports <code>src/index.css</code>:</p>
<pre><code>import './index.css';
</code></pre>
<p>A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in <code>src/fonts/MyFont.woff</code>, your <code>index.css</code> might include this:</p>
<pre><code>@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
/* other formats include: 'woff2', 'truetype, 'opentype',
'embedded-opentype', and 'svg' */
}
</code></pre>
<p>Notice how we’re using a relative path starting with <code>./</code>. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.</p>
<p>Normally this should be enough.</p>
<h3>Using <code>public</code> Folder</h3>
<p>If for some reason you prefer <em>not</em> to use the build pipeline, and instead do it the “classic way”, you can <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#using-the-public-folder" rel="noreferrer">use the <code>public</code> folder</a> and put your fonts there.</p>
<p>The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.</p>
<p>If you want to do it this way, put the fonts somewhere into the <code>public</code> folder, for example, into <code>public/fonts/MyFont.woff</code>. If you follow this approach, you should put CSS files into <code>public</code> folder as well and <em>not</em> import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like <code>public/index.css</code>. You would have to manually add <code><link></code> to this stylesheet from <code>public/index.html</code>:</p>
<pre><code><link rel="stylesheet" href="%PUBLIC_URL%/index.css">
</code></pre>
<p>And inside of it, you would use the regular CSS notation:</p>
<pre><code>@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}
</code></pre>
<p>Notice how I’m using <code>fonts/MyFont.woff</code> as the path. This is because <code>index.css</code> is in the <code>public</code> folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your <code>homepage</code> field to <code>http://myuser.github.io/myproject</code>, it will be served from <code>/myproject</code>). However <code>fonts</code> are also in the <code>public</code> folder, so they will be served from <code>fonts</code> relatively (either <code>http://mywebsite.example/fonts</code> or <code>http://myuser.github.io/myproject/fonts</code>). Therefore we use the relative path.</p>
<p>Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our <code>index.css</code> file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.</p>
<h3> Which Way to Use?</h3>
<p>Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.</p> |
12,080,087 | How to test the done and fail Deferred Object by using jasmine | <p>Here is the code about the javascript submit request (1).<br>
Here is the test about mocking the ajax request by using jasmine (2).</p>
<p>I would like to mock the server behaviour. Any ideas?<br>
See the comment in (1) and (2) for more details. </p>
<p>P.S.:<br>
Actually in both case the done and the fail Deferred Object of fakeFunction are called.</p>
<hr>
<p>(1)</p>
<pre><code>submitForm: function () {
// the server execute fail only if message.val() is empty
// and I would like to mock this behaviour in (2)
backendController.submitForm(message.val()).done(this.onSuccess).fail(this.onError);
},
backendController.submitForm = function (message) {
return $.ajax({
url: 'some url',
type: 'POST',
dataType: 'json',
data: {
message: message
}
}).done(function () {
//some code;
});
};
</code></pre>
<hr>
<p>(2)</p>
<pre><code>describe('When Submit button handler fired', function () {
var submitFormSpy,
fakeFunction = function () {
this.done = function () {
return this;
};
this.fail = function () {
return this;
};
return this;
};
beforeEach(function () {
submitFormSpy = spyOn(backendController, 'submitForm').andCallFake(fakeFunction);
});
describe('if the message is empty', function () {
beforeEach(function () {
this.view.$el.find('#message').text('');
this.view.$el.find('form').submit();
});
it('backendController.submitForm and fail Deferred Object should be called', function () {
expect(submitFormSpy).toHaveBeenCalled();
// how should I test that fail Deferred Object is called?
});
});
describe('if the message is not empty', function () {
beforeEach(function () {
this.view.$el.find('#message').text('some text');
this.view.$el.find('form').submit();
});
it('backendController.submitForm should be called and the fail Deferred Object should be not called', function () {
expect(submitFormSpy).toHaveBeenCalled();
// how should I test that fail Deferred Object is not called?
});
});
});
</code></pre> | 12,435,465 | 3 | 3 | null | 2012-08-22 19:26:50.073 UTC | 8 | 2013-02-13 04:54:50.767 UTC | 2012-09-14 06:04:27.85 UTC | null | 1,113,216 | null | 1,113,216 | null | 1 | 28 | javascript|jquery|post|jasmine | 19,697 | <p>We actually ran into the same problem, trying to test Deferred objects that represent AJAXed template scripts for on-the-fly templating. Our testing solution involves using the <a href="https://github.com/pivotal/jasmine-ajax">Jasmine-Ajax</a> library in conjunction with Jasmine itself.</p>
<p>So probably it will be something like this:</p>
<pre><code>describe('When Submit button handler fired', function () {
jasmine.Ajax.useMock();
describe('if the message is empty', function () {
beforeEach(function() {
spyOn(backendController, 'submitForm').andCallThrough();
// replace with wherever your callbacks are defined
spyOn(this, 'onSuccess');
spyOn(this, 'onFailure');
this.view.$el.find('#message').text('');
this.view.$el.find('form').submit();
});
it('backendController.submitForm and fail Deferred Object should be called', function () {
expect(backendController.submitForm).toHaveBeenCalledWith('');
mostRecentAjaxRequest().response({
status: 500, // or whatever response code you want
responseText: ''
});
expect( this.onSuccess ).not.toHaveBeenCalled();
expect( this.onFailure ).toHaveBeenCalled();
});
});
</code></pre>
<p>Another thing, if you can, try to break up the functionality so you're not testing the entire DOM-to-response-callback path in one test. If you're granular enough, you can actually test asynchronous Deferred resolutions by using Deferred objects themselves inside your tests!</p>
<p>The key is to actually use Deferred objects within your tests themselves, so that the scope of the <code>expect</code> call is still within your <code>it</code> function block.</p>
<pre><code>describe('loadTemplate', function() {
it('passes back the response text', function() {
jasmine.Ajax.mock();
loadTemplate('template-request').done(function(response) {
expect(response).toBe('foobar');
});
mostRecentAjaxRequest().response({ status:200, responseText:'foobar' });
});
});
</code></pre> |
12,190,147 | Customize dot with image of UIPageControl at index 0 of UIPageControl | <p>I'm a new learner of ios programming. I have tried to search with another example and more questions at stackoverflow but it's not my goal. I want to set an image of dot at index 0 of UIPageControl as similar as iPhone search homescreen. Have any way to do it ? Please explain me with some code or another useful link.</p>
<p>Thanks in advance</p>
<p><img src="https://i.stack.imgur.com/kRj9s.png" alt="enter image description here"></p> | 12,190,526 | 11 | 2 | null | 2012-08-30 04:58:02.48 UTC | 13 | 2021-06-15 20:04:24.683 UTC | null | null | null | null | 1,524,903 | null | 1 | 31 | iphone|ios | 57,944 | <p>Try this link:-</p>
<p>Answer with GrayPageControl:-
<a href="https://stackoverflow.com/questions/3409319/is-there-a-way-to-change-page-indicator-dots-color">Is there a way to change page indicator dots color</a></p>
<p>It is really good and reliable.I also have used this code.</p>
<p>You might have to do some more customization as </p>
<pre><code>-(void) updateDots
{
for (int i = 0; i < [self.subviews count]; i++)
{
UIImageView* dot = [self.subviews objectAtIndex:i];
if (i == self.currentPage) {
if(i==0) {
dot.image = [UIImage imageNamed:@"activesearch.png"];
} else {
dot.image = activeImage;
}
} else {
if(i==0) {
dot.image = [UIImage imageNamed:@"inactivesearch.png"];
} else {
dot.image = inactiveImage;
}
}
}
}
</code></pre> |
12,548,312 | Find all subsets of length k in an array | <p>Given a set <code>{1,2,3,4,5...n}</code> of n elements, we need to find all subsets of length k . </p>
<p>For example, if n = 4 and k = 2, the <code>output</code> would be <code>{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}</code>.</p>
<p>I am not even able to figure out how to start. We don't have to use the inbuilt library functions like next_permutation etc.</p>
<p>Need the algorithm and implementation in either C/C++ or Java.</p> | 12,548,381 | 15 | 1 | null | 2012-09-22 22:50:04.343 UTC | 10 | 2022-04-19 23:11:10.017 UTC | 2021-01-24 09:35:24.59 UTC | null | 1,048,572 | null | 971,683 | null | 1 | 40 | arrays|algorithm|subset|powerset | 57,245 | <p>Recursion is your friend for this task.</p>
<p>For each element - "guess" if it is in the current subset, and recursively invoke with the guess and a smaller superset you can select from. Doing so for both the "yes" and "no" guesses - will result in all possible subsets.
<br>Restraining yourself to a certain length can be easily done in a stop clause.</p>
<p>Java code:</p>
<pre><code>private static void getSubsets(List<Integer> superSet, int k, int idx, Set<Integer> current,List<Set<Integer>> solution) {
//successful stop clause
if (current.size() == k) {
solution.add(new HashSet<>(current));
return;
}
//unseccessful stop clause
if (idx == superSet.size()) return;
Integer x = superSet.get(idx);
current.add(x);
//"guess" x is in the subset
getSubsets(superSet, k, idx+1, current, solution);
current.remove(x);
//"guess" x is not in the subset
getSubsets(superSet, k, idx+1, current, solution);
}
public static List<Set<Integer>> getSubsets(List<Integer> superSet, int k) {
List<Set<Integer>> res = new ArrayList<>();
getSubsets(superSet, k, 0, new HashSet<Integer>(), res);
return res;
}
</code></pre>
<p>Invoking with:</p>
<pre><code>List<Integer> superSet = new ArrayList<>();
superSet.add(1);
superSet.add(2);
superSet.add(3);
superSet.add(4);
System.out.println(getSubsets(superSet,2));
</code></pre>
<p>Will yield:</p>
<pre><code>[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
</code></pre> |
12,304,553 | TCPDF Save file to folder? | <p>I'm using TCPDF to print a receipt and then send it to customer with phpMailer, but I have a problem: </p>
<p><strong>I have no idea how to save the file into a pdf.</strong></p>
<p>I've tried this:</p>
<pre><code>// reset pointer to the last page
$pdf->lastPage();
//Close and output PDF document
$pdf->Output('kuitti'.$ordernumber.'.pdf', 'I');
$this->Output("kuitit");
</code></pre> | 12,304,671 | 12 | 2 | null | 2012-09-06 16:37:31.727 UTC | 12 | 2021-10-24 18:46:11.643 UTC | null | null | null | user1537415 | null | null | 1 | 41 | php|tcpdf | 127,037 | <p>try this</p>
<pre><code>$pdf->Output('kuitti'.$ordernumber.'.pdf', 'F');
</code></pre> |
19,112,031 | Difference between korn and bash shell | <p>I am completely new to Unix. Presently, I have been asked to learn about both <strong>KornShell (ksh)</strong> and <strong>Bash shell</strong>. Can some one please give me a short overview about the two? </p>
<p>Is the term "<strong>shell</strong>" synonymous to "<strong>terminal</strong>"? </p>
<p>I understand that I can read documents about both online. But I believe that an overview from an experienced Unix programmer will help me better understand.</p> | 19,112,167 | 2 | 4 | null | 2013-10-01 09:01:35.127 UTC | 2 | 2014-01-06 17:40:50.533 UTC | 2014-01-06 17:40:50.533 UTC | null | 228,080 | null | 539,085 | null | 1 | 19 | bash|shell|unix|scripting|ksh | 41,976 | <p>Post from UNIX.COM</p>
<p><strong>Shell features</strong></p>
<p>This table below lists most features that I think would make you choose one shell over another. It is not intended to be a definitive list and does not include every single possible feature for every single possible shell. A feature is only considered to be in a shell if in the version that comes with the operating system, or if it is available as compiled directly from the standard distribution. In particular the C shell specified below is that available on SUNOS 4.*, a considerable number of vendors now ship either tcsh or their own enhanced C shell instead (they don't always make it obvious that they are shipping tcsh.</p>
<p><strong>Code:</strong></p>
<pre><code> sh csh ksh bash tcsh zsh rc es
Job control N Y Y Y Y Y N N
Aliases N Y Y Y Y Y N N
Shell functions Y(1) N Y Y N Y Y Y
"Sensible" Input/Output redirection Y N Y Y N Y Y Y
Directory stack N Y Y Y Y Y F F
Command history N Y Y Y Y Y L L
Command line editing N N Y Y Y Y L L
Vi Command line editing N N Y Y Y(3) Y L L
Emacs Command line editing N N Y Y Y Y L L
Rebindable Command line editing N N N Y Y Y L L
User name look up N Y Y Y Y Y L L
Login/Logout watching N N N N Y Y F F
Filename completion N Y(1) Y Y Y Y L L
Username completion N Y(2) Y Y Y Y L L
Hostname completion N Y(2) Y Y Y Y L L
History completion N N N Y Y Y L L
Fully programmable Completion N N N N Y Y N N
Mh Mailbox completion N N N N(4) N(6) N(6) N N
Co Processes N N Y N N Y N N
Builtin artithmetic evaluation N Y Y Y Y Y N N
Can follow symbolic links invisibly N N Y Y Y Y N N
Periodic command execution N N N N Y Y N N
Custom Prompt (easily) N N Y Y Y Y Y Y
Sun Keyboard Hack N N N N N Y N N
Spelling Correction N N N N Y Y N N
Process Substitution N N N Y(2) N Y Y Y
Underlying Syntax sh csh sh sh csh sh rc rc
Freely Available N N N(5) Y Y Y Y Y
Checks Mailbox N Y Y Y Y Y F F
Tty Sanity Checking N N N N Y Y N N
Can cope with large argument lists Y N Y Y Y Y Y Y
Has non-interactive startup file N Y Y(7) Y(7) Y Y N N
Has non-login startup file N Y Y(7) Y Y Y N N
Can avoid user startup files N Y N Y N Y Y Y
Can specify startup file N N Y Y N N N N
Low level command redefinition N N N N N N N Y
Has anonymous functions N N N N N N Y Y
List Variables N Y Y N Y Y Y Y
Full signal trap handling Y N Y Y N Y Y Y
File no clobber ability N Y Y Y Y Y N F
Local variables N N Y Y N Y Y Y
Lexically scoped variables N N N N N N N Y
Exceptions N N N N N N N Y
</code></pre>
<p><strong>Key to the table above.</strong></p>
<p>Y Feature can be done using this shell.</p>
<p>N Feature is not present in the shell.</p>
<p>F Feature can only be done by using the shells function
mechanism.</p>
<p>L The readline library must be linked into the shell to enable
this Feature.</p>
<p><strong>Notes to the table above</strong></p>
<pre><code>1. This feature was not in the original version, but has since become
almost standard.
2. This feature is fairly new and so is often not found on many
versions of the shell, it is gradually making its way into
standard distribution.
3. The Vi emulation of this shell is thought by many to be
incomplete.
4. This feature is not standard but unofficial patches exist to
perform this.
5. A version called 'pdksh' is freely available, but does not have
the full functionality of the AT&T version.
6. This can be done via the shells programmable completion mechanism.
7. Only by specifying a file via the ENV environment variable.
</code></pre> |
3,754,798 | IF ELSE problem COMMAND BATCH | <p>I have problem about IF ELSE in Command Batch script...</p>
<p>In Notepad:<br>
Code:</p>
<pre><code>:CHECKACCOUNT
if /I "%user%"=="insertusername" ( GOTO :ACCOUNT ) ELSE ( GOTO :CHECKPASSACCT )
:CHECKPASSACCT
if /I "%pass%"=="insertpassword" ( GOTO :ACCOUNT ) ELSE ( GOTO :COUNTER )
</code></pre>
<p>In COMMAND:<br>
Code:</p>
<blockquote>
<p>( was unexpected at this time.</p>
</blockquote>
<p>FULL Script Code:</p>
<pre><code>@echo off
::SETTINGS:::::::::::::::::::::::
set filetxt =userpass.txt
set log=logfile.log
set timer=900
::set default = true
::set user = 0
::set pass = 0
:::::::::::::::::::::::::::::::::
:STARTER
ECHO.>>%log%
ECHO ========START========>>%log%
SetLocal EnableDelayedExpansion
Set n=
Set _InputFile=%filetxt%
For /F "tokens=*" %%I IN (%_InputFile%) DO (
Set /a n+=1
Set acct!n!=%%I
)
set router_ip=%acct1%
set user=%acct2%
set pass=%acct3%
GOTO :CHECKFILE1
:CHECKFILE1
CLS
IF EXIST curl.exe ( GOTO :CHECKFILE2 ) else (
ECHO ERROR: curl.exe was not found.>>%log%
ECHO ERROR: curl.exe was not found.
ECHO.
ECHO.
GOTO :PAUSEEXIT
)
:CHECKFILE2
CLS
IF EXIST sleep.exe ( GOTO :CHECKACCOUNT ) else (
ECHO ERROR: sleep.exe was not found.>>%log%
ECHO ERROR: sleep.exe was not found.
ECHO.
ECHO.
GOTO :PAUSEEXIT
)
:CHECKACCOUNT
if /I "%user%"=="insertusername" GOTO ACCOUNT
GOTO CHECKPASSACCT
:CHECKPASSACCT
if /I "%pass%"=="insertpassword" GOTO ACCOUNT
GOTO COUNTER
:ACCOUNT
CLS
::if %default% = true ( GOTO :COUNTER ) ELSE (
ECHO To edit/change USERNAME and PASSWORD... Please type: OPTION
ECHO.
SET /P user="Please enter the username of your Router:"
IF /I %user%==OPTION ( Goto :EDITBAT )
CLS
ECHO To edit/change USERNAME and PASSWORD... Please type: OPTION
ECHO.
SET /P pass="Please enter the password of your Router:"
IF /I %pass%==OPTION ( Goto :EDITBAT )
CLS
set /a i = 1
GOTO :CHECKACCOUNT
::)
:EDITBAT
start /WAIT notepad %filetxt%
set router_ip=%acct1%
set user=%acct2%
set pass=%acct3%
GOTO :CHECKACCOUNT
:COUNTER
IF %i%==0 ( GOTO :RESETROUTER ) ELSE (
ECHO WAIT %i% seconds...
sleep 1
set /a i = i - 1
CLS
GOTO :COUNTER
)
:RESETROUTER
CLS
ECHO READY to RESET....
ECHO Preparing....
sleep 2
sleep 2
CLS
ECHO Processing....
sleep 5
sleep 2
CLS
ECHO Success....
sleep 5
set /a i = %timer%
CLS
GOTO :COUNTER
:PAUSEEXIT
PAUSE
:EXIT
ECHO.>>%log%
ECHO ========END OF LOG FILE========>>%log%
</code></pre> | 3,754,830 | 4 | 0 | null | 2010-09-20 19:25:26.107 UTC | 2 | 2017-03-09 15:53:46.663 UTC | 2010-09-20 20:03:43.033 UTC | null | 453,089 | null | 453,089 | null | 1 | 9 | scripting|batch-file|command|windows-server | 96,837 | <p>You can simplify this down to:</p>
<pre><code>:CHECKACCOUNT
if /I "%user%"=="insertusername" GOTO ACCOUNT
GOTO CHECKPASSACCT
:CHECKPASSACCT
if /I "%pass%"=="insertpassword" GOTO ACCOUNT
GOTO COUNTER
</code></pre>
<p>The <code>ELSE</code> statements aren't needed. Since the <code>IF</code> block will jump somewhere else, placing the second <code>GOTO</code> on the next line or in an <code>ELSE</code> block should be equivalent.</p>
<p>Also, you need the leading colon when defining a <code>GOTO</code> target but not when referring to the target name inside the <code>GOTO</code> statement itself.</p> |
3,539,274 | How do I scale my Scala REST application that uses Akka? | <p>I have a Scala application using Akka that receives REST requests, makes some operations against a database, and responds with some information to the client. As it is, my db operations take a long time and my REST-enabled actor is unable to respond to new requests in the meantime, even though I could run lots of operations concurrently against the DB. I'm using the javax.ws.rs annotations to REST-enable methods in my actor.</p>
<p>The question; what is the best way to enable my application to handle a large number of concurrent requests?</p>
<p><strong>EDIT</strong>: I'll add some sample code.</p>
<pre><code> import se.scalablesolutions.akka.actor._
import javax.ws.rs._
@Path("/test")
class TestService {
@GET
def status() =
actorPool !! Status(session).
getOrElse(<error>Unable to connect to service</error>)
}
class TestActor {
def receive = {
case Status() => {
reply(SomeObject.slowDBMethod)
}
}
}
case class Status()
</code></pre>
<p><strong>EDIT2</strong>: This is what I'm getting in the log. I'm sending the three requests from my browser as fast as I can switch tabs and press F5, but the RS bean still waits for the first request to complete before handling the next.</p>
<pre><code>[INFO] [2010-08-29 16:27:03,232] [akka:event-driven:dispatcher:global-15] c.n.StatusActor: got Slow request
[INFO] [2010-08-29 16:27:06,916] [akka:event-driven:dispatcher:global-10] c.n.StatusActor: got Slow request
[INFO] [2010-08-29 16:27:10,589] [akka:event-driven:dispatcher:global-3] c.n.StatusActor: got Slow request
</code></pre> | 4,503,332 | 4 | 1 | null | 2010-08-21 22:24:47.22 UTC | 10 | 2014-10-08 12:25:20.383 UTC | 2014-10-08 12:25:20.383 UTC | null | 819,887 | null | 309,224 | null | 1 | 12 | scala|rest|jersey|akka|scalability | 3,506 | <p>While I realize this thread is 4+ months stale now, it's worth noting that Akka has a new HTTP module implementation that transfers the request into an actor efficiently. This approach leverages the asynchronous servlet API (also works with Jetty continuations) to enable the suspended request to be passed through the system as a message and resumed at any point; eliminating, for instance, the need to use !! to trigger actor work and respond in the annotated POJO. Likewise, since the request is suspended in the container, and the context is flipped into an actor as quick as possible, there are no threads blocking to handle the response or future.</p>
<p>One naive way the above example might be rewritten today:</p>
<pre><code>class TestEndpoint extends Actor with Endpoint {
def hook(uri:String) = uri == "/test"
def provide(uri:String) = actorOf[TestService].start
override def preStart = {
ActorRegister.actorsFor[classOf[RootEndpoint]).head ! Endpoint.Attach(hook, provide)
}
def receive = handleHttpRequest
}
class TestService extends Actor {
def receive = {
case get:Get =>
get.timeout(SomeObject.TimeoutInSeconds) // for example
get.OK(SomeObject.slowDBMethod)
case other:RequestMethod =>
other.NotAllowed("Invalid method for this endpoint")
}
}
</code></pre>
<p>More documentation can be found on the akka site: <a href="http://doc.akkasource.org/http">http://doc.akkasource.org/http</a></p> |
22,483,214 | Regex - check if input still has chances to become matching | <p>We've got such regexp:</p>
<pre><code>var regexp = /^one (two)+ three/;
</code></pre>
<p>So only string like <code>"one two three"</code> or <code>"one two three four"</code> or <code>"one twotwo three"</code> etc. will match it.</p>
<p>However, if we've got string like</p>
<p><code>"one "</code> - is still <em>'promising'</em> that maybe soon it will match</p>
<p>but this string:
<code>"one three"</code> will never match no matter what we'll do.</p>
<p>Is there some way to check if given string have chances to become matching or not?</p>
<p>I need it for some tips during writing when I want to recommend all options that begins with given input (regexp's I'm using are pretty long and I dont want really to mess with them).</p>
<hr>
<p>In other words - I want to check if string has ended during checking and nothing 'not matching' was faced.</p>
<p>In even more other words - Answer would be inside <em>reason of not matching</em>. If reason is end of string - then it would be promissing. However I dont know any way to check why some string didnt match</p> | 41,580,048 | 10 | 5 | null | 2014-03-18 15:03:14.293 UTC | 10 | 2020-07-18 16:07:32.63 UTC | 2014-09-02 12:00:53.44 UTC | null | 2,446,799 | null | 2,446,799 | null | 1 | 29 | javascript|regex | 5,981 | <p>This is a regex feature known as <em>partial matching</em>, it's available in several regex engines such as PCRE, Boost, Java but <em>not</em> in JavaScript.</p>
<p><a href="https://stackoverflow.com/a/22489941/3764814">Andacious's answer</a> shows a very nice way to overcome this limitation, we just need to automate this.</p>
<p>Well... challenge accepted :)</p>
<p>Fortunately, JavaScript has a very limited regex feature set with a simple syntax, so I wrote a simple parser and on-the-fly transformation for this task, based on the features <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet" rel="noreferrer">listed on MDN</a>. This code has been updated to handle ES2018 features.</p>
<p>A couple points of interest:</p>
<ul>
<li>This produces a regex which will almost always match the empty string. Therefore a failed partial match occurs when the result of <code>exec</code> is <code>null</code> or an array whose first element is the empty string</li>
<li>Negative lookaheads are kept as-is. I believe that's the right thing to do. The only ways to fail a match is through them (ie put a <code>(?!)</code> in the regex) and anchors (<code>^</code> and <code>$</code>). Lookbehinds (both positive and negative) are also kept as-is.</li>
<li>The parser assumes a valid input pattern: you can't create a <code>RegExp</code> object from an invalid pattern in the first place. This may break in the future if new regex features are introduced.</li>
<li>This code won't handle backreferences properly: <code>^(\w+)\s+\1$</code> won't yield a partial match against <code>hello hel</code> for instance.</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>RegExp.prototype.toPartialMatchRegex = function() {
"use strict";
var re = this,
source = this.source,
i = 0;
function process () {
var result = "",
tmp;
function appendRaw(nbChars) {
result += source.substr(i, nbChars);
i += nbChars;
};
function appendOptional(nbChars) {
result += "(?:" + source.substr(i, nbChars) + "|$)";
i += nbChars;
};
while (i < source.length) {
switch (source[i])
{
case "\\":
switch (source[i + 1])
{
case "c":
appendOptional(3);
break;
case "x":
appendOptional(4);
break;
case "u":
if (re.unicode) {
if (source[i + 2] === "{") {
appendOptional(source.indexOf("}", i) - i + 1);
} else {
appendOptional(6);
}
} else {
appendOptional(2);
}
break;
case "p":
case "P":
if (re.unicode) {
appendOptional(source.indexOf("}", i) - i + 1);
} else {
appendOptional(2);
}
break;
case "k":
appendOptional(source.indexOf(">", i) - i + 1);
break;
default:
appendOptional(2);
break;
}
break;
case "[":
tmp = /\[(?:\\.|.)*?\]/g;
tmp.lastIndex = i;
tmp = tmp.exec(source);
appendOptional(tmp[0].length);
break;
case "|":
case "^":
case "$":
case "*":
case "+":
case "?":
appendRaw(1);
break;
case "{":
tmp = /\{\d+,?\d*\}/g;
tmp.lastIndex = i;
tmp = tmp.exec(source);
if (tmp) {
appendRaw(tmp[0].length);
} else {
appendOptional(1);
}
break;
case "(":
if (source[i + 1] == "?") {
switch (source[i + 2])
{
case ":":
result += "(?:";
i += 3;
result += process() + "|$)";
break;
case "=":
result += "(?=";
i += 3;
result += process() + ")";
break;
case "!":
tmp = i;
i += 3;
process();
result += source.substr(tmp, i - tmp);
break;
case "<":
switch (source[i + 3])
{
case "=":
case "!":
tmp = i;
i += 4;
process();
result += source.substr(tmp, i - tmp);
break;
default:
appendRaw(source.indexOf(">", i) - i + 1);
result += process() + "|$)";
break;
}
break;
}
} else {
appendRaw(1);
result += process() + "|$)";
}
break;
case ")":
++i;
return result;
default:
appendOptional(1);
break;
}
}
return result;
}
return new RegExp(process(), this.flags);
};
// Test code
(function() {
document.write('<span style="display: inline-block; width: 60px;">Regex: </span><input id="re" value="^one (two)+ three"/><br><span style="display: inline-block; width: 60px;">Input: </span><input id="txt" value="one twotw"/><br><pre id="result"></pre>');
document.close();
var run = function() {
var output = document.getElementById("result");
try
{
var regex = new RegExp(document.getElementById("re").value);
var input = document.getElementById("txt").value;
var partialMatchRegex = regex.toPartialMatchRegex();
var result = partialMatchRegex.exec(input);
var matchType = regex.exec(input) ? "Full match" : result && result[0] ? "Partial match" : "No match";
output.innerText = partialMatchRegex + "\n\n" + matchType + "\n" + JSON.stringify(result);
}
catch (e)
{
output.innerText = e;
}
};
document.getElementById("re").addEventListener("input", run);
document.getElementById("txt").addEventListener("input", run);
run();
}());</code></pre>
</div>
</div>
</p>
<p>I tested it a little bit and it seems to work fine, let me know if you find any bugs.</p> |
22,523,575 | How to insert json array into mysql database | <p>Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.</p>
<p>This is my json data.</p>
<blockquote>
<p>[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]</p>
</blockquote>
<p>This is my Php code.</p>
<pre><code><?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
</code></pre>
<p>My database connection code.</p>
<pre><code> <?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
</code></pre>
<p>
<p>Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.</p> | 22,523,620 | 6 | 7 | null | 2014-03-20 04:32:27.503 UTC | 9 | 2022-01-21 13:16:38.14 UTC | 2014-03-20 04:41:12.297 UTC | null | 3,427,551 | null | 3,427,551 | null | 1 | 16 | php|mysql|arrays|json | 97,785 | <pre><code> $json = file_get_contents('php://input');
$obj = json_decode($json,true);
</code></pre>
<p>I think you are passing the wrong variable. You should pass <code>$json</code> in <code>json_decode</code> as shown above.</p> |
20,723,100 | Why can only a superuser CREATE EXTENSION hstore, but not on Heroku? | <p>When I attempt to enable hstore on my database:</p>
<pre><code>=> CREATE EXTENSION IF NOT EXISTS hstore;
ERROR: permission denied to create extension "hstore"
HINT: Must be superuser to create this extension.
</code></pre>
<p>My user is not a superuser, but <em>is</em> the owner of the database.</p>
<p>According to <a href="http://www.postgresql.org/docs/current/static/sql-createextension.html">the CREATE EXTENSION docs</a>:</p>
<blockquote>
<p>Loading an extension requires the same privileges that would be required to create its component objects. For most extensions this means superuser or database owner privileges are needed. The user who runs CREATE EXTENSION becomes the owner of the extension for purposes of later privilege checks, as well as the owner of any objects created by the extension's script.</p>
</blockquote>
<p>What is hstore doing that requires superuser privileges? Is it affecting parts of the cluster outside the database I'm adding it to?</p>
<hr>
<p>Further confundity:</p>
<p><a href="https://devcenter.heroku.com/articles/heroku-postgresql#connection-permissions">The DB user Heroku Postgres provides is not a superuser</a>:</p>
<blockquote>
<p>Heroku Postgres users are granted all non-superuser permissions on their database. These include <code>SELECT</code>, <code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code>, <code>TRUNCATE</code>, <code>REFERENCES</code>, <code>TRIGGER</code>, <code>CREATE</code>, <code>CONNECT</code>, <code>TEMPORARY</code>, <code>EXECUTE</code>, and <code>USAGE</code>.</p>
</blockquote>
<p>However, <a href="https://devcenter.heroku.com/articles/heroku-postgres-extensions-postgis-full-text-search">that user is able to CREATE EXTENSION hstore</a>:</p>
<blockquote>
<p>To create any supported extension, open a session with heroku pg:psql and run the appropriate command:</p>
<pre><code>$ heroku pg:psql
Pager usage is off.
psql (9.2.4)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
ad27m1eao6kqb1=> CREATE EXTENSION hstore;
CREATE EXTENSION
ad27m1eao6kqb1=>
</code></pre>
</blockquote>
<p>(For context, I'm attempting to set up a <a href="https://github.com/progrium/dokku">Dokku</a> deployment, so the comparison to Heroku is especially important.)</p> | 20,745,157 | 3 | 4 | null | 2013-12-21 20:12:26.767 UTC | 5 | 2021-08-03 02:21:27.47 UTC | 2013-12-21 20:26:16.67 UTC | null | 4,937 | null | 4,937 | null | 1 | 36 | postgresql|heroku|hstore | 25,854 | <p>The hstore extension creates functions that call code from an external dynamic object, which requires superuser privilege. That's why creating the hstore extension requires superuser privilege.</p>
<p>As for Heroku, it is my understanding that they are running with a special extension whitelisting module, which allows users to create certain extensions even though they are not superusers. I believe it is based on this code: <a href="https://github.com/dimitri/pgextwlist" rel="noreferrer">https://github.com/dimitri/pgextwlist</a>. You can try to install that code yourself if you want the same functionality in your databases.</p> |
10,946,624 | Finding IP Address for IPhone | <p>I am working on IPhone. I want to know how to find a ip address of a iphone through USB/3G not on wifi.
I am aware of seeing IP if it is connected through WiFI.(Going through settings and looking under Wifi)
But i need IP through USB / 3G. what i did means i used personal hotspot and i connected my iphone to PC through usb. I got an IP.
But when i added one more Iphone with same hot spot enabled and connected through USB i am getting like unidentified network.</p>
<p>By using whatismyip.com site i am getting an ip . but i cant do anything with it. I am unable to reach my iphone with the provided ip of that site.</p>
<p>So can anyone kindly provide information on how to look for IP of multiple Iphones connected to same PC.</p>
<p>The purpose is to communicate to muliple iphones with their IP's.</p>
<p>Thanks a million in advance.</p> | 19,556,018 | 5 | 0 | null | 2012-06-08 09:52:46.377 UTC | null | 2019-07-25 20:52:58.7 UTC | null | null | null | null | 966,874 | null | 1 | 8 | iphone|ip | 98,005 | <p>Unfortunately the responses are not completely correct. In a 3G/4G network every device gets an IP address, but THAT's NOT the IP address that you see when going to sites like www.whatismyip.com. That's the address that the Telco presents to the external world, not the device IP address. </p>
<p>Telcos such AT&t, Verizon, Telefonica and similar assign a "private" IP address that is only valid in their network. This is similar to the internal IP address that you have in your phone when connect to the house wireless, but if you check in www.whatismyip.com you get the external IP address of your wireless router (You can check that those are different addresses). What Telcos do is known as NAT or PAT. The reason is that the current version of IP has a very limited number of available IP addresses, and all those million of devices cannot get public IP addresses (like the one you see in whatismyip.com). Actually several devices share that external IP address.</p>
<p>Unlike Android devices where you can get the IP that the telco assigned to the device, iOS does not present that information to the user (unless you jailbreak the device or have an App). </p>
<p>Although the address that whatismyip presents is not your real IP, it is the one that the external world recognizes so it suffices for most purposes. </p> |
10,875,750 | Left/right padding for Button.setCompoundDrawablesWithIntrinsicBounds()? | <p>I'm trying to set a left icon on a button with:</p>
<pre><code>setCompoundDrawablesWithIntrinsicBounds(R.drawable.foo, 0, 0, 0);
</code></pre>
<p>but the icon is placed flush up against the left edge of my button, and the text string. Is there a way to specify some left/right padding on the supplied icon so that it isn't right up against the edges?</p>
<p>Thanks</p> | 10,875,862 | 2 | 0 | null | 2012-06-04 02:37:24.543 UTC | 3 | 2016-01-19 15:49:02.387 UTC | null | null | null | null | 291,701 | null | 1 | 26 | android | 53,322 | <p>I believe what you're looking for is <a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android%3adrawablePadding" rel="noreferrer"><code>android:drawablePadding</code></a></p>
<p>Here's an example of using <code>drawablePadding</code> along with <code>paddingLeft</code> and <code>paddingRight</code> to position an image in a button</p>
<pre><code><Button
android:id="@+id/button"
android:layout_width="200dp"
android:layout_height="80dp"
android:drawableLeft="@drawable/ic_launcher"
android:drawablePadding="2dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:text="Test" />
</code></pre>
<p><img src="https://i.stack.imgur.com/gscsj.png" alt="Image example"></p> |
10,943,088 | numpy.max or max ? Which one is faster? | <p>In python, which one is faster ? </p>
<pre><code>numpy.max(), numpy.min()
</code></pre>
<p>or</p>
<pre><code>max(), min()
</code></pre>
<p>My list/array length varies from 2 to 600. Which one should I use to save some run time ?</p> | 10,943,451 | 4 | 2 | null | 2012-06-08 04:31:55.497 UTC | 5 | 2022-01-26 11:42:56.24 UTC | null | null | null | null | 891,373 | null | 1 | 44 | python|numpy|runtime|max|min | 55,376 | <p>Well from my timings it follows if you already have numpy array <code>a</code> you should use <code>a.max</code> (the source tells it's the same as <code>np.max</code> if <code>a.max</code> available). But if you have built-in list then most of the time takes <em>converting</em> it into np.ndarray => that's why <code>max</code> is better in your timings.</p>
<p>In essense: if <code>np.ndarray</code> then <code>a.max</code>, if <code>list</code> and no need for all the machinery of <code>np.ndarray</code> then standard <code>max</code>.</p> |
11,278,995 | Why doesn't NSOrderedSet inherit from NSSet? | <p>Surely an ordered set is a more-specific case of a set, so why does <code>NSOrderedSet</code> inherit from <code>NSObject</code> rather than <code>NSSet</code>?</p> | 11,279,208 | 1 | 4 | null | 2012-07-01 01:41:53.43 UTC | 14 | 2012-07-01 02:48:19.093 UTC | null | null | null | null | 461,492 | null | 1 | 51 | objective-c|ios|nsset|nsorderedset | 5,746 | <p>I went through the interface of <code>NSSet</code> and you're right, ordered sets appear to satisfy the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov substitution principle</a> and could therefor inherit from <code>NSSet</code>.</p>
<p>There is one little method that breaks this: <code>mutableCopy</code>. The return value of <code>mutableCopy</code> must be an <code>NSMutableSet</code>, but <code>NSMutableOrderedSet</code> should inherit from <code>NSOrderedSet</code>. You can't have both.</p>
<p>Let me explain with some code. First, let's look at the correct behaviour of <code>NSSet</code> and <code>NSMutableSet</code>:</p>
<pre><code>NSSet* immutable = [NSSet set];
NSMutableSet* mutable = [immutable mutableCopy];
[mutable isKindOfClass:[NSSet class]]; // YES
[mutable isKindOfClass:[NSMutableSet class]]; // YES
</code></pre>
<p>Now, let's pretend <code>NSOrderedSet</code> inherits from <code>NSSet</code>, and <code>NSMutableOrderedSet</code> inherits from <code>NSOrderedSet</code>:</p>
<pre><code>//Example 1
NSOrderedSet* immutable = [NSOrderedSet orderedSet];
NSMutableOrderedSet* mutable = [immutable mutableCopy];
[mutable isKindOfClass:[NSSet class]]; // YES
[mutable isKindOfClass:[NSMutableSet class]]; // NO (this is the problem)
</code></pre>
<p>What if <code>NSMutableOrderedSet</code> inherited from <code>NSMutableSet</code> instead? Then we get a different problem:</p>
<pre><code>//Example 2
NSOrderedSet* immutable = [NSOrderedSet orderedSet];
NSMutableOrderedSet* mutable = [immutable mutableCopy];
[mutable isKindOfClass:[NSSet class]]; // YES
[mutable isKindOfClass:[NSMutableSet class]]; // YES
[mutable isKindOfClass:[NSOrderedSet class]]; // NO (this is a problem)
</code></pre>
<p>In Example 1, you wouldn't be able to pass an <code>NSOrderedSet</code> into a function expecting an <code>NSSet</code> because the behaviour is different. Basically, it's a backwards compatibility problem.</p>
<p>In Example 2, you can't pass an <code>NSMutableOrderedSet</code> into a function expecting an <code>NSOrderedSet</code> because the former doesn't inherit from the latter.</p>
<p>All of this is because <code>NSMutableOrderedSet</code> can't inherit from both <code>NSMutableSet</code> and <code>NSOrderedSet</code> because Objective-C doesn't have multiple inheritance. The way to get around this is to make protocols for <code>NSMutableSet</code> and <code>NSOrderedSet</code>, because then <code>NSMutableOrderedSet</code> can implement both protocols. I guess the Apple developers just though it was simpler without the extra protocols.</p> |
11,140,163 | Plotting a 3d cube, a sphere and a vector in Matplotlib | <p>I search how to plot something with less instruction as possible with Matplotlib but I don't find any help for this in the documentation.</p>
<p>I want to plot the following things:</p>
<ul>
<li>a wireframe cube centered in 0 with a side length of 2</li>
<li>a "wireframe" sphere centered in 0 with a radius of 1</li>
<li>a point at coordinates [0, 0, 0]</li>
<li>a vector that starts at this point and goes to [1, 1, 1]</li>
</ul>
<p>How to do that?</p> | 11,156,353 | 3 | 1 | null | 2012-06-21 14:15:43.44 UTC | 53 | 2020-09-02 15:16:33.497 UTC | 2019-07-17 12:49:32.93 UTC | null | 7,851,470 | null | 882,932 | null | 1 | 96 | python|matplotlib|3d|geometry | 145,729 | <p>It is a little complicated, but you can draw all the objects by the following code:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="b")
# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
# draw a point
ax.scatter([0], [0], [0], color="g", s=100)
# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/rQfnu.png" alt="output_figure"></p> |
12,725,265 | Is it possible to use a for loop in <select> in html? and how? | <p>I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript. </p>
<p>this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.</p>
<p>Thanks</p> | 12,734,637 | 7 | 4 | null | 2012-10-04 10:27:54.893 UTC | 2 | 2022-07-13 08:05:37.627 UTC | 2012-10-04 10:40:32.113 UTC | null | 1,438,482 | null | 1,438,482 | null | 1 | 6 | javascript|html | 44,777 | <p>Lots of answers.... here is another approach <strong>NOT</strong> using document.write OR innerHTML OR jQuery.... </p>
<p>HTML</p>
<pre><code><select id="foo"></select>
</code></pre>
<p>JS</p>
<pre><code>(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
</code></pre>
<p>And here is a <a href="http://jsfiddle.net/rlemon/5J29g/">Fiddle</a> to demo it.</p> |
12,694,569 | how to cleanly remove ndb properties | <p>in my app i need to remove a few of my models properties.<br>
i checked out <a href="https://developers.google.com/appengine/articles/update_schema" rel="noreferrer">this link</a> but the first issue is that the properties are on a <code>polymodel</code> and there is no way im going to switch to an <code>expando</code> for the time to remove the properties, im not even shure what could happen if i change a <code>polymodel</code> to an <code>expando</code>.</p>
<p>so how do i remove properties from existing entities?</p>
<p>i was thinking to set all <code>StringProperty</code> to <code>None</code> and then remove these from the model schema and redeploy.
one of those properties is a <code>BooleanProperty</code>, i can't set this one to <code>None</code> right?!
or an <code>ndb.PickleProperty</code>... how should i remove that?</p>
<p>does anybody know how to get this done properly?</p> | 12,701,172 | 1 | 0 | null | 2012-10-02 16:40:50.383 UTC | 11 | 2012-10-03 02:32:46.257 UTC | 2012-10-02 20:52:43.453 UTC | null | 258,564 | null | 258,564 | null | 1 | 15 | python|google-app-engine|app-engine-ndb|polymodel | 4,622 | <p>If you want to update all your entities the recommended approach is a map/reduce job that reads and rewrites all entities; however it may not be worth it, depending on how much data you have -- the map/reduce isn't free either.</p>
<p>Also be sure you test the map/reduce job on a small subset of the data. It is remarkably subtle to truly remove a property from an entity, even if it's not in the model class any more! The best approach may be:</p>
<pre><code>if 'propname' in ent._properties:
del ent._properties['propname']
ent.put()
</code></pre> |
12,760,709 | Missing Localized Screenshots Error on itunes | <p>I have selected Default Language as "Australian English" as Default language. When I am submitting the binary it showing as rejected"Red Icon" with status "Missing Localized Screenshots". The application is in only single language. I have added screen shots also the application is only for iphone.</p>
<p>When I am looking binary information that is showing as:</p>
<p>Localizations : ( "en-AU" )</p>
<p>Please suggest me where I am making mistake.</p> | 12,760,736 | 11 | 0 | null | 2012-10-06 14:33:22.06 UTC | 3 | 2016-08-17 13:51:56.68 UTC | null | null | null | null | 905,517 | null | 1 | 28 | iphone|ios|binary|itunes | 16,596 | <p>Check if you have screenshots for iPhone 5. I had this same error, when screenshots for iP5 were missing.</p> |
12,927,027 | UICollectionView flowLayout not wrapping cells correctly | <p>I have a <code>UICollectionView</code> with a FLowLayout. It will work as I expect most of the time, but every now and then one of the cells does not wrap properly. For example, the the cell that should be on in the first "column" of the third row if actually trailing in the second row and there is just an empty space where it should be (see diagram below). All you can see of this rouge cell is the left hand side (the rest is cut off) and the place it should be is empty.</p>
<p>This does not happen consistently; it is not always the same row. Once it has happened, I can scroll up and then back and the cell will have fixed itself. Or, when I press the cell (which takes me to the next view via a push) and then pop back, I will see the cell in the incorrect position and then it will jump to the correct position.</p>
<p>The scroll speed seems to make it easier to reproduce the problem. When I scroll slowly, I can still see the cell in the wrong position every now and then, but then it will jump to the correct position straight away.</p>
<p>The problem started when I added the sections insets. Previously, I had the cells almost flush against the collection bounds (little, or no insets) and I did not notice the problem. But this meant the right and left of the collection view was empty. Ie, could not scroll. Also, the scroll bar was not flush to the right.</p>
<p>I can make the problem happen on both Simulator and on an iPad 3.</p>
<p>I guess the problem is happening because of the left and right section insets... But if the value is wrong, then I would expect the behavior to be consistent. I wonder if this might be a bug with Apple? Or perhaps this is due to a build up of the insets or something similar.</p>
<p><img src="https://i.stack.imgur.com/kNVYs.png" alt="Illustration of problem and settings"></p>
<hr>
<p><strong>Follow up</strong>: I have been using <a href="https://stackoverflow.com/a/13389461/377384">this answer</a> below by Nick for over 2 years now without a problem (in case people are wondering if there are any holes in that answer - I have not found any yet). Well done Nick.</p> | 13,389,461 | 12 | 0 | null | 2012-10-17 04:18:06.78 UTC | 53 | 2021-09-28 04:47:54.463 UTC | 2018-09-17 10:52:49.927 UTC | null | 1,033,581 | null | 377,384 | null | 1 | 79 | ios|ios6|uicollectionview|uicollectionviewcell | 45,700 | <p>There is a bug in UICollectionViewFlowLayout's implementation of layoutAttributesForElementsInRect that causes it to return TWO attribute objects for a single cell in certain cases involving section insets. One of the returned attribute objects is invalid (outside the bounds of the collection view) and the other is valid. Below is a subclass of UICollectionViewFlowLayout that fixes the problem by excluding cells outside of the collection view's bounds.</p>
<pre><code>// NDCollectionViewFlowLayout.h
@interface NDCollectionViewFlowLayout : UICollectionViewFlowLayout
@end
// NDCollectionViewFlowLayout.m
#import "NDCollectionViewFlowLayout.h"
@implementation NDCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *newAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if ((attribute.frame.origin.x + attribute.frame.size.width <= self.collectionViewContentSize.width) &&
(attribute.frame.origin.y + attribute.frame.size.height <= self.collectionViewContentSize.height)) {
[newAttributes addObject:attribute];
}
}
return newAttributes;
}
@end
</code></pre>
<p>See <a href="https://gist.github.com/4075682" rel="noreferrer">this</a>.</p>
<p>Other answers suggest returning YES from shouldInvalidateLayoutForBoundsChange, but this causes unnecessary recomputations and doesn't even completely solve the problem.</p>
<p>My solution completely solves the bug and shouldn't cause any problems when Apple fixes the root cause.</p> |
13,180,543 | What is AssemblyInfo.cs used for? | <p>My question is pretty basic. What I'd like to know is what is the <code>AssemblyInfo.cs</code> file used for?</p> | 13,180,570 | 6 | 1 | null | 2012-11-01 15:43:00.54 UTC | 16 | 2020-12-31 04:13:28.037 UTC | 2020-12-31 04:13:28.037 UTC | null | 3,728,901 | null | 991,788 | null | 1 | 136 | .net | 103,157 | <blockquote>
<p>AssemblyInfo.cs contains information about your assembly, like name,
description, version, etc. You can find more details about its content
reading the comments that are included in it.</p>
<p>If you delete it, your assembly will be compiled with no information,
i.e., in the Details tab of the file properties you will see no name,
no description, version 0.0.0.0, etc.</p>
<p>The value associated with assembly:Guid is the ID that will identify
the assembly if it will be exposed as a COM object. So, if your
assembly isn't COM-exposed, you don't need this. It is randomly
generate. In any case, normally, you don't need to modify it.</p>
</blockquote>
<p>Credits goes to : <a href="http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/8955449f-71ac-448e-9ee6-5329fceecd3c" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/8955449f-71ac-448e-9ee6-5329fceecd3c</a></p> |
16,639,484 | How to convert integer into categorical data in R? | <p>My data set has 8 variables and one of them is categorical but R thinks that it is integer (0's and 1's). What I have to do inorder to covert it into categorical?</p>
<pre><code>> str(mydata)
'data.frame': 117 obs. of 8 variables:
$ PRICE: int 2050 2080 2150 2150 1999 1900 1800 1560 1450 1449 ...
$ SQFT : int 2650 2600 2664 2921 2580 2580 2774 1920 2150 1710 ...
$ AGE : int 13 NA 6 3 4 4 2 1 NA 1 ...
$ FEATS: int 7 4 5 6 4 4 4 5 4 3 ...
$ NE : int 1 1 1 1 1 1 1 1 1 1 ...
$ CUST : int 1 1 1 1 1 0 0 1 0 1 ...
$ COR : int 0 0 0 0 0 0 0 0 0 0 ...
$ TAX : int 1639 1088 1193 1635 1732 1534 1765 1161 NA 1010 ...
</code></pre>
<p>COR should have been categorical.</p> | 16,639,537 | 1 | 0 | null | 2013-05-19 21:07:24.327 UTC | 7 | 2017-08-09 15:16:25.27 UTC | 2013-05-19 21:21:40.167 UTC | null | 1,315,767 | null | 233,286 | null | 1 | 28 | r|type-conversion | 107,574 | <p>Have a look at <code>?as.factor</code>. In your case </p>
<pre><code>mydata$COR <- as.factor(mydata$COR)
</code></pre> |
17,035,609 | Most Efficient Multipage RequireJS and Almond setup | <p>I have multiple pages on a site using RequireJS, and most pages have unique functionality. All of them share a host of common modules (jQuery, Backbone, and more); all of them have their own unique modules, as well. I'm wondering what is the best way to optimize this code using <a href="https://github.com/jrburke/r.js/" rel="noreferrer">r.js</a>. I see a number of alternatives suggested by different parts of RequireJS's and Almond's documentation and examples -- so I came up with the following list of possibilities I see, and I'm asking which one is most recommended (or if there's another better way):</p>
<ol>
<li><strong>Optimize a single JS file for the whole site</strong>, using <a href="https://github.com/jrburke/almond" rel="noreferrer">Almond</a>, which would load once and then stay cached. The downside of this most simple approach is that I'd be loading onto each page code that the user doesn't need for that page (i.e. modules specific to other pages). For each page, the JS loaded would be bigger than it <em>needs</em> to be.</li>
<li><strong>Optimize a single JS file for each page</strong>, which would include both the common and the page-specific modules. That way I could include Almond in each page's file and would only load one JS file on each page -- which would be significantly smaller than a single JS file for the whole site would be. The downside I see, though, is that the common modules wouldn't be cached in the browser, right? For every page the user goes to she'd have to re-download the bulk of jQuery, Backbone, etc. (the common modules), as those libraries would constitute large parts of each unique single-page JS file. (This seems to be the approach of the <a href="https://github.com/requirejs/example-multipage/" rel="noreferrer">RequireJS multipage example</a>, except that the example doesn't use Almond.)</li>
<li><strong>Optimize one JS file for common modules, and then another for each specific page</strong>. That way the user would cache the common modules' file and, browsing between pages, would only have to load a small page-specific JS file. Within this option I see two ways to finish it off, to include the RequireJS functionality:
a. Load the file require.js before the common modules on all pages, using the <code>data-main</code> syntax or a normal <code><script></code> tag -- not using Almond at all. That means each page would have three JS files: require.js, common modules, and page-specific modules.
b. It seems that <a href="https://gist.github.com/jrburke/1509135" rel="noreferrer">this gist</a> is suggesting a method for plugging Almond into each optimized file ---- so I wouldn't have to load require.js, but would instead include Almond in both my common modules AND my page-specific modules. Is that right? Is that more efficient than loading require.js upfront?</li>
</ol>
<p>Thanks for any advice you can offer as to the best way to carry this out.</p> | 17,385,513 | 5 | 1 | null | 2013-06-11 02:22:57.593 UTC | 29 | 2015-06-01 02:54:07 UTC | 2013-06-29 00:13:56.147 UTC | null | 2,284,669 | null | 2,284,669 | null | 1 | 34 | optimization|compression|requirejs|r.js|almond | 10,003 | <p>I think you've answered your own question pretty clearly. </p>
<p>For production, we do - as well as most companies I've worked with <strong>option 3</strong>.</p>
<p>Here are advantages of solution 3, and why I think <strong>you should use it</strong>:</p>
<ul>
<li>It utilizes the <strong>most caching</strong>, all common functionality is loaded <em>once</em>. Taking the least traffic and generating the fastest loading times when surfing multiple pages. Loading times of multiple pages are important and while the traffic on your side might not be significant compared to other resources you're loading, the clients will really appreciate the faster load times.</li>
<li>It's the most logical, since commonly most files on the site share common functionality.</li>
</ul>
<p>Here is an interesting advantage for solution 2:</p>
<ul>
<li><p>You send the least data to each page. If a lot of your visitors are one time, for example in a landing page - this is your best bet. Loading times can not be overestimated in importance in conversion oriented scenarios.</p></li>
<li><p>Are your visitors repeat? <a href="http://yuiblog.com/blog/2007/01/04/performance-research-part-2/" rel="noreferrer">some studies</a> suggest that 40% of visitors come with an empty cache. </p></li>
</ul>
<p>Other considerations:</p>
<ul>
<li><p>If most of your visitors visit a single page - consider option 2. Option 3 is great for sites where the average users visit multiple pages, but if the user visits a single page and that's all he sees - that's your best bet. </p></li>
<li><p>If you have <em>a lot</em> of JavaScript. Consider loading some of it to give the user visual indication, and then loading the rest in a deferred way asynchronously (with script tag injection, or directly with require if you're already using it). The threshold for people noticing something is 'clunky' in the UI is normally about 100ms. An example of this is GMail's 'loading...' .</p></li>
<li><p>Given that HTTP connections are <a href="http://en.wikipedia.org/wiki/HTTP_persistent_connection" rel="noreferrer">Keep-Alive</a> by default in HTTP/1.1 or with an additional header in HTTP/1.0 , sending multiple files is less of a problem than it was 5-10 years ago. Make sure you're sending the <code>Keep-Alive</code> header from your server for HTTP/1.0 clients.</p></li>
</ul>
<p>Some general advice and reading material:</p>
<ul>
<li><a href="https://developers.google.com/speed/pagespeed/module/filter-js-minify" rel="noreferrer">JavaScript minification</a> is a must, r.js for example does this nicely and your thought process in using it was correct. r.js also <a href="https://developers.google.com/speed/pagespeed/module/filter-js-combine" rel="noreferrer">combines</a> JavaScript which is a step in the right direction.</li>
<li>As I suggested, <a href="https://developers.google.com/speed/pagespeed/module/filter-js-defer" rel="noreferrer">defering</a> JavaScript is really important too, and can drastically improve loading times. Defering execution will help your loading time <em>look</em> fast which is <em>very</em> important, a lot more important in some scenarios than actually loading fast.</li>
<li>Anything you <em>can</em> load from a CDN like external resources you <em>should</em> load from a CDN. Some libraries people use today like jQuery are pretty bid (80kb), fetching them from a cache could really benefit you. In your example, I would <em>not</em> load Backbone, underscore and jQuery from your site, rather, I'd load them from a CDN.</li>
</ul> |
16,788,068 | Hibernate: make database only if not exists | <p>I want Hibernate make database file (SQLite), but only if not exists.</p>
<p>Now in hibernate.cfg.xml I have this line:</p>
<pre><code><property name="hibernate.hbm2ddl.auto">create</property>
</code></pre>
<p>The problem is that database file is been creating in all the time, even the file exists.</p> | 16,788,284 | 2 | 4 | null | 2013-05-28 09:06:48.337 UTC | 4 | 2013-05-28 09:17:38.013 UTC | null | null | null | null | 1,819,402 | null | 1 | 34 | java|hibernate | 45,964 | <p>Try switching the value to <code>update</code></p>
<pre><code><property name="hibernate.hbm2ddl.auto">update</property>
</code></pre> |
17,091,300 | Linux: Set permission only to directories | <p>I have to change the permissions of the <code>htdocs</code> directory in apache to a certain group and with certain read/write/execute.</p>
<p>The directories need to have 775 permissions and the files need to have 664.</p>
<p>If I do a recursive 664 to the <code>htdocs</code>, then all files and directories will change to 664.</p>
<p>I don't want to change the directories manually.</p>
<p>Is there any way to change only files or directories?</p> | 17,091,359 | 7 | 0 | null | 2013-06-13 15:40:41.6 UTC | 21 | 2021-09-06 00:12:52.923 UTC | 2013-07-26 14:49:25.267 UTC | null | 445,131 | null | 995,655 | null | 1 | 37 | linux|bash|directory|chmod | 37,898 | <p>Use find's <code>-type</code> option to limit actions to files and directories. Use the <code>-o</code> option to specify alternate actions for different types, so you only have to run <code>find</code> once, rather than separately for each type.</p>
<pre><code>find htdocs -type f -exec chmod 664 {} + -o -type d -exec chmod 775 {} +
</code></pre> |
25,569,865 | How to escape curly braces in a format string in Rust | <p>I want to write this</p>
<pre><code>write!(f, "{ hash:{}, subject: {} }", self.hash, self.subject)
</code></pre>
<p>But since curly braces have special meaning for formatting it's clear that I can't place the outer curly braces like that without escaping. So I tried to escape them.</p>
<pre><code>write!(f, "\{ hash:{}, subject: {} \}", self.hash, self.subject)
</code></pre>
<p>Rust doesn't like that either. Then I read this:</p>
<blockquote>
<p>The literal characters {, }, or # may be included in a string by preceding them with the \ character. Since \ is already an escape character in Rust strings, a string literal using this escape will look like "\{".</p>
</blockquote>
<p>So I tried</p>
<pre><code>write!(f, "\\{ hash:{}, subject: {} \\}", self.hash, self.subject)
</code></pre>
<p>But that's also not working. :-(</p> | 25,570,140 | 1 | 4 | null | 2014-08-29 13:59:02.72 UTC | 4 | 2018-10-08 12:41:34.967 UTC | null | null | null | null | 288,703 | null | 1 | 103 | string-formatting|rust | 28,569 | <p>You might be reading some out of date docs (e.g. for Rust 0.9)</p>
<p>As of Rust 1.0, <a href="https://doc.rust-lang.org/std/fmt/index.html#escaping" rel="noreferrer">the way to escape <code>{</code> and <code>}</code> is with another <code>{</code> or <code>}</code></a></p>
<pre><code>write!(f, "{{ hash:{}, subject: {} }}", self.hash, self.subject)
</code></pre>
<blockquote>
<p>The literal characters <code>{</code> and <code>}</code> may be included in a string by
preceding them with the same character. For example, the <code>{</code> character
is escaped with <code>{{</code> and the <code>}</code> character is escaped with <code>}}</code>.</p>
</blockquote> |
25,827,160 | Importing correctly with pytest | <p>I just got set up to use pytest with Python 2.6. It has worked well so far with the exception of handling "import" statements: I can't seem to get pytest to respond to imports in the same way that my program does.</p>
<p>My directory structure is as follows:</p>
<pre><code>src/
main.py
util.py
test/
test_util.py
geom/
vector.py
region.py
test/
test_vector.py
test_region.py
</code></pre>
<p>To run, I call <code>python main.py</code> from src/.</p>
<p>In main.py, I import both vector and region with</p>
<pre><code>from geom.region import Region
from geom.vector import Vector
</code></pre>
<p>In vector.py, I import region with</p>
<pre><code>from geom.region import Region
</code></pre>
<p>These all work fine when I run the code in a standard run. However, when I call "py.test" from src/, it consistently exits with import errors.</p>
<hr>
<h2>Some Problems and My Solution Attempts</h2>
<p>My first problem was that, when running "test/test_foo.py", py.test could not "import foo.py" directly. I solved this by using the "imp" tool. In "test_util.py":</p>
<pre><code>import imp
util = imp.load_source("util", "util.py")
</code></pre>
<p>This works great for many files. It also seems to imply that when pytest is running "path/test/test_foo.py" to test "path/foo.py", it is based in the directory "path".</p>
<p>However, this fails for "test_vector.py". Pytest can find and import the <code>vector</code> module, but it <strong>cannot</strong> locate any of <code>vector</code>'s imports. The following imports (from "vector.py") both fail when using pytest:</p>
<pre><code>from geom.region import *
from region import *
</code></pre>
<p>These both give errors of the form</p>
<pre><code>ImportError: No module named [geom.region / region]
</code></pre>
<p>I don't know what to do next to solve this problem; my understanding of imports in Python is limited.</p>
<p><strong>What is the proper way to handle imports when using pytest?</strong></p>
<hr>
<h2>Edit: Extremely Hacky Solution</h2>
<p>In <code>vector.py</code>, I changed the import statement from</p>
<pre><code>from geom.region import Region
</code></pre>
<p>to simply</p>
<pre><code>from region import Region
</code></pre>
<p>This makes the import relative to the directory of "vector.py".</p>
<p>Next, in "test/test_vector.py", I add the directory of "vector.py" to the path as follows:</p>
<pre><code>import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
</code></pre>
<p>This enables Python to find "../region.py" from "geom/test/test_vector.py".</p>
<p>This works, but it seems extremely problematic because I am adding a ton of new directories to the path. What I'm looking for is either</p>
<p>1) An import strategy that is compatible with pytest, or</p>
<p>2) An option in pytest that makes it compatible with my import strategy</p>
<p>So I am leaving this question open for answers of these kinds.</p> | 25,828,036 | 6 | 5 | null | 2014-09-13 20:02:50.083 UTC | 10 | 2022-08-07 02:23:07.843 UTC | 2014-09-15 03:52:48.877 UTC | null | 988,441 | null | 988,441 | null | 1 | 88 | python|import|pytest | 69,169 | <p><strong><em>import</em></strong> looks in the following directories to find a module:</p>
<ol>
<li>The <strong>home directory</strong> of the program. This is the directory of your root script. When you are running pytest your home directory is where it is installed (/usr/local/bin probably). No matter that you are running it from your src directory because the location of your pytest determines your home directory. That is the reason why it doesn't find the modules. </li>
<li><strong>PYTHONPATH</strong>. This is an environment variable. You can set it from the command line of your operating system. In Linux/Unix systems you can do this by executing: '<em>export PYTHONPATH=/your/custom/path</em>' If you wanted Python to find your modules from the test directory you should include the src path in this variable.</li>
<li>The <strong>standard libraries</strong> directory. This is the directory where all your libraries are installed. </li>
<li>There is a less common option using a <strong>pth</strong> file.</li>
</ol>
<p><strong><em>sys.path</em></strong> is the result of combining the <strong>home directory</strong>, <strong>PYTHONPATH</strong> and the <strong>standard libraries</strong> directory. What you are doing, modifying <strong><em>sys.path</em></strong> is correct. It is something I do regularly. You could try using <strong>PYTHONPATH</strong> if you don't like messing with <strong><em>sys.path</em></strong> </p> |
26,476,391 | How to auto-load MySQL on startup on OS X Yosemite / El Capitan | <p>After upgrading OS X my install of MySQL stopped loading on startup.</p>
<p>This <a href="http://dev.mysql.com/doc/mysql-macosx-excerpt/5.5/en/macosx-installation-startupitem.html" rel="noreferrer">walk-through on MySQL</a> says: </p>
<blockquote>
<p>"The Startup Item installation adds a variable MYSQLCOM=-YES- to the
system configuration file /etc/hostconfig. If you want to disable the
automatic startup of MySQL, change this variable to MYSQLCOM=-NO-."</p>
</blockquote>
<p>So, I opened that file and it says:</p>
<pre><code># This file is going away
AFPSERVER=-NO-
AUTHSERVER=-NO-
TIMESYNC=-NO-
QTSSERVER=-NO-
MYSQLCOM=-YES-
</code></pre>
<p>I assume OSX dev's added the <code># This file is going away</code> but I'm not certain.</p>
<p>If that is the case, what is the proper way to start MySQL on startup on OSX Yosemite?</p> | 26,492,593 | 5 | 7 | null | 2014-10-20 23:06:38.39 UTC | 37 | 2017-10-30 07:44:29.107 UTC | 2016-02-17 22:46:24.257 UTC | null | 922,522 | null | 922,522 | null | 1 | 77 | mysql|macos|osx-yosemite|startup|osx-elcapitan | 60,862 | <p><strong>This is what fixed it:</strong></p>
<p>First, create a new file: /Library/LaunchDaemons/com.mysql.mysql.plist</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true />
<key>Label</key>
<string>com.mysql.mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld_safe</string>
<string>--user=mysql</string>
</array>
</dict>
</plist>
</code></pre>
<p>Then update permissions and add it to <code>launchctl</code>:</p>
<pre><code>sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
</code></pre> |
9,660,445 | Detect iPhone Volume Button Up Press? | <p>Is there a notification that I can listen to that will tell me when an iPhone's volume is turned <strong>up</strong>? </p>
<p>I know about the <code>AVSystemController_SystemVolumeDidChangeNotification</code>, but it is essential that the notification only be triggered when the volume has been turned up, not up or down.</p>
<p>Secondly, how can I hide the translucent view that appears when the volume up button is pressed, showing the system's volume? <strong>Camera+</strong> has implemented this.</p> | 10,155,141 | 4 | 0 | null | 2012-03-12 00:48:33.667 UTC | 9 | 2017-10-06 23:34:48.697 UTC | 2012-10-30 14:37:02.117 UTC | null | 299,797 | null | 817,946 | null | 1 | 13 | iphone|objective-c|ios|volume|avsystemcontroller | 15,538 | <p>There is no documented way to to this, but you can use this workaround. Register for <code>AVSystemController_SystemVolumeDidChangeNotification</code> notification and add an <code>MPVolumeView</code> which will prevent the system volume view from showing up.</p>
<pre><code>MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(-100, 0, 10, 0)];
[volumeView sizeToFit];
[self.view addSubview:volumeView];
</code></pre>
<p>And don't forget to start an Audio Session</p>
<pre><code>AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
</code></pre>
<p>In This case, the <code>MPVolumeView</code> is hidden from the user.</p>
<p>As for checking if volume up or down was pressed, just grab the current application's volume </p>
<pre><code>float volumeLevel = [[MPMusicPlayerController applicationMusicPlayer] volume];
</code></pre>
<p>and compare it with new volume after the button was pressed in notification callback </p>
<p>If you don't want to do it by yourself, there's a drop-in class available in github</p>
<p><a href="https://github.com/blladnar/RBVolumeButtons" rel="noreferrer">https://github.com/blladnar/RBVolumeButtons</a></p> |
10,085,951 | Scala ~> (tilde greater than) operator | <p>I have the following scala class definition (found in a paper), modeling categories:</p>
<pre><code>trait Category[~>[_, _]] {
def compose[A, B, C]
(f: B ~> C)
(g: A ~> B)
: A ~> C
def id[A]: A ~> A
}
</code></pre>
<p>can someone explain me what the '~>' means in the Category type parameter, and in the methods return type?
Or direct me to a resource that explains it...
I'm new to Scala (coming from Java), so forgive me if that's something a scala user should have known...
Thank you in advance</p> | 10,086,051 | 2 | 0 | null | 2012-04-10 09:11:39.757 UTC | 8 | 2019-05-06 19:59:00.36 UTC | null | null | null | null | 601,960 | null | 1 | 28 | scala|operators | 8,947 | <p><code>~></code> is just the placeholder-name for the type-parameter of <code>Category</code>. Like the <code>T</code> in <code>class Option[T]</code>.</p>
<p>Additionally, Scala syntax allows you to write <code>B ~> C</code> as a shorthand for <code>~>[B, C]</code>.</p>
<p>Maybe things get clearer, if you rename it:</p>
<pre><code>trait Category[Mapping[_, _]] {
def compose[A, B, C](f: Mapping[B, C])(g: Mapping[A, B]): Mapping[A, C]
def id[A]: Mapping[A, A]
}
</code></pre> |
9,657,691 | Xcode: Dragging a Project to a Workspace shows tiny .xcodeproj file in Project Navigator. What's wrong? | <p><strong>Setup</strong>:</p>
<p>Xcode 4.3.1 (or 5.x)<br>
OS X 10.7.3</p>
<p>I have reproduced this issue on two separate late-model Macs with this setup.</p>
<p><strong>Steps</strong>:</p>
<ol>
<li>Create a new Mac "Cocoa Application" Xcode Project. <code>File > New > Project…</code> Name it "MyApp".</li>
<li>Create a new Workspace: <code>File > New > Workspace…</code> Name it "MySuite".</li>
<li>Drag <code>MyApp.xcodeproj</code> file from the Finder into the Project Navigator of "MySuite" Workspace.</li>
</ol>
<p><strong>Expected</strong>:<br>
The Project Navigator of the "MySuite" Workspace should now show a <strong>full sub-Project</strong> for "MyApp" with Source, Targets, etc.</p>
<p><strong>Actual</strong>:<br>
"MySuite" Workspace Project Navigator shows a tiny <code>MyApp.xcodeproj</code> item in the Project Navigator. (see screenshots)</p>
<hr>
<p><strong>Dragging:</strong></p>
<p><img src="https://i.stack.imgur.com/8nPlQ.png" alt="Dragging MyApp.xcodeproj to the Workspace"></p>
<p><strong>Result:</strong></p>
<p><img src="https://i.stack.imgur.com/FqKlK.png" alt="Result"></p>
<p>What am I doing wrong in trying to add a Project to a Workspace?</p> | 9,657,780 | 1 | 6 | null | 2012-03-11 18:31:58.967 UTC | 8 | 2013-11-21 00:07:37.05 UTC | 2013-11-21 00:07:37.05 UTC | null | 34,934 | null | 34,934 | null | 1 | 39 | xcode|macos | 12,965 | <p>Be sure you don't have the project already open in another window. Xcode only lets you open a project one time. I've made this mistake a lot when working on a framework then trying to add it to an application.</p>
<p>Simply close the project you're trying to drag in's window and everything will be happy.</p> |
9,899,113 | Get request.session from a class-based generic view | <p>Is there a way to get <code>request.session</code> from inside a class-based view? </p>
<p>For instance, I have </p>
<pre><code>from django.views.generic.edit import FormView
class CreateProfileView(FormView):
def form_valid(self, form):
# --> would like to save form contents to session here
return redirect(self.get_success_url())
</code></pre>
<p>The only thing I can think of would be override <code>as_view</code> by adding </p>
<pre><code>def as_view(self, request, *args, **kwargs):
self.session = request.session
super(CreateProfileView, self).as_view(request, *args, **kwargs)
</code></pre>
<p>to the class. But that seems ugly. Is there another way?</p> | 9,899,170 | 1 | 0 | null | 2012-03-27 23:22:44.96 UTC | 8 | 2013-03-12 19:30:55.987 UTC | null | null | null | null | 1,161,906 | null | 1 | 39 | django|django-views | 29,399 | <p>You have access to <code>self.request</code> from anywhere within the class (and therefore <code>self.request.session</code>)</p>
<p><a href="https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#dynamic-filtering">https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#dynamic-filtering</a></p>
<blockquote>
<p>The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request) this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.</p>
</blockquote> |
10,242,501 | How to find a substring in a field in Mongodb | <p>How can I find all the objects in a database with where a field of a object contains a substring?</p>
<p>If the field is A in an object of a collection with a string value:</p>
<p>I want to find all the objects in the db "database" where A contains a substring say "abc def".</p>
<p>I tried: </p>
<pre><code>db.database.find({A: {$regex: '/^*(abc def)*$/''}})
</code></pre>
<p>but didn't work</p>
<p><strong>UPDATE</strong></p>
<p>A real string (in unicode):</p>
<pre><code>Sujet Commentaire sur Star Wars Episode III - La Revanche des Sith 1
</code></pre>
<p>Need to search for all entries with Star Wars</p>
<pre><code>db.test.find({A: {$regex: '^*(star wars)*$''}}) not wokring
</code></pre> | 10,244,062 | 6 | 1 | null | 2012-04-20 08:08:34.163 UTC | 10 | 2021-04-13 06:50:49.257 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 713,087 | null | 1 | 73 | mongodb|nosql | 98,992 | <p>Instead of this:</p>
<pre><code>db.database.find({A: {$regex: '/^*(abc def)*$/''}})
</code></pre>
<p>You should do this:</p>
<pre><code>db.database.find({A: /abc def/i })
</code></pre>
<p>^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the character following" and (abc def)* means "0 or more times "abc def", but it has to be at the end of the string, because of your $. The "i" at the end is to make it case insensitive.</p> |
8,087,736 | How do you make a dynamically-sized data table? | <p>I am using Excel 2010.</p>
<p>I have a "monthly" data table that looks similar to this:</p>
<pre><code>MonthBegin InventoryExpenses Overhead TotalSales TotalSalesIncome TotalProfit
July-11 $1,500 $4,952 89 $7,139 $687
August-11 $2,200 $4,236 105 $8,312 $1,876
September-11 $1,100 $4,429 74 $6,691 $1,162
</code></pre>
<p>The following formula is automatically propogated to every cell in the [MonthBegin] column:</p>
<pre><code>=DATE( 2011, 7 + ( ROW( ) - 2 ), 1 )
</code></pre>
<p>Every other colmun has a similar column-formula that automatically pulls the appropriate data from another source, <strong>based on the month listed in the [MonthBegin] column</strong>.</p>
<p>With this configuration, I can just insert a new row anywhere into the table and the next month will automatically appear at the bottom in the correct order (which I find nifty).</p>
<p>But I need to take this to the next level of automation, to please management.<br>
How can I make it so that the spreadsheet automatically adds a row for October once the month is over?</p>
<p>I've been considering using a dynamic range for the table:</p>
<pre><code>=OFFSET(A1,0,0,( ( YEAR( TODAY( ) ) - 2011 ) * 12 ) + ( MONTH( TODAY( ) ) - 7 ),6)
</code></pre>
<p>... but Excel won't accept such a formula for the table area, I assume because it is not static.<br>
Can anyone explain to me how to gain this functionality with my data table?</p> | 8,149,620 | 3 | 2 | null | 2011-11-10 23:14:20.547 UTC | null | 2016-11-09 13:58:35.893 UTC | 2016-11-09 13:58:35.893 UTC | null | 4,370,109 | null | 120,888 | null | 1 | 5 | excel|datatable|excel-formula | 56,778 | <p>You can't <strong>dynamically</strong> add a new row with formula only.</p>
<p>Here is a VBA event procedure that will do the trick. You need to put in the <code>Workbook module</code></p>
<pre><code>Option Explicit
Private Sub Workbook_Open()
Dim lo As ListObject
Dim iTot As Long
Set lo = ListObjects("MyTable")
iTot = lo.Range.Rows.Count
'Add this statements before the Range with your worksheet name
'ThisWorkbook.Worksheets("Sheet1")
If Now() > Range("A" & iTot).Value Then
Range("A" & lo.Range.Rows.Count + 1).Formula = "=DATE( 2011, 7 + ( ROW( ) - 2 ), 1 )"
End If
End Sub
</code></pre>
<p>Don't forget to change the name of your table and to add the name of your Worksheet (see the comment inside the code)</p> |
7,912,180 | Plotting multiple lines from a data frame in R | <p>I am building an R function to plot a few lines from a data table, I don't understand why this is not working?</p>
<pre><code>data = read.table(path, header=TRUE);
plot(data$noop);
lines(data$noop, col="blue");
lines(data$plus, col="green");
</code></pre>
<p>I am reading the data from a file I has which is formatted like this:</p>
<pre><code> noop plus mins
33.3 33.3 33.3
30.0 40.0 30.0
25.0 50.0 25.0
</code></pre>
<p>This is the minimal representation of the dataset, which contains more headers and more data points. So each of the rows of this data set reflects a sample taken at a given time. So my objective is to read this data in from the file, and then plot each column as a series of points connected by lines of different color. </p>
<p>The approach I am using currently is only plotting 1 line, and not multiple lines.</p> | 7,913,639 | 3 | 2 | null | 2011-10-27 05:57:20.773 UTC | 3 | 2013-03-29 18:31:32.023 UTC | 2013-03-29 18:31:32.023 UTC | null | 697,568 | null | 546,427 | null | 1 | 6 | r|graph|plot | 70,336 | <p>Have a look at the ggplot2 package</p>
<pre><code>library(ggplot2)
library(reshape)
data <- data.frame(time = seq(0, 23), noob = rnorm(24), plus = runif(24), extra = rpois(24, lambda = 1))
Molten <- melt(data, id.vars = "time")
ggplot(Molten, aes(x = time, y = value, colour = variable)) + geom_line()
</code></pre>
<p><img src="https://i.stack.imgur.com/4dBQN.png" alt="enter image description here"></p> |
11,808,432 | C++- error C2144 syntax error : 'int' should be preceded by ';' | <p>I'm trying to compile this C++ code:</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "general_configuration.h"
#include "helper_functions.h"
#define LINE_LEN 80
// file_with_as_ext returns 1 if the input has .as extension
int file_with_as_ext(char* input)
{
char* dot_value = strchr(input, '.');
if (dot_value == NULL)
return 0;
else
{
if (strcmp(dot_value,".as") == 0)
return 1;
}
}
</code></pre>
<p>But I'm getting the error <code>"C2144: syntax error : 'int' should be preceded by ';'"</code></p>
<p>And I can't understand why, because <code>#define</code> doesn't need <code>';'</code> at the end.</p> | 11,808,543 | 3 | 5 | null | 2012-08-04 11:51:29.157 UTC | 2 | 2019-04-08 08:59:04.857 UTC | 2019-04-08 08:59:04.857 UTC | null | 2,527,795 | null | 1,363,226 | null | 1 | 6 | c++ | 39,723 | <p>First, the code you have posted begins with a stray backtick. If that's really in your code, you should remove it.</p>
<p>Second, the compiler would be happier, and emit fewer warnings, if you ended your function with the line</p>
<pre><code>return 0; // unreachable
</code></pre>
<p>This is good C++ style and is recommended. (In your case, the line may actually be <em>reachable,</em> in which case the line is not only good style but necessary for correct operation. Check this.)</p>
<p>Otherwise, your code looks all right except for some small objections one could raise regarding the outdated, C-style use of <code>#define</code> and regarding one or two other minor points of style. Regarding the <code>#define</code>, it is not C++ source code as such but is a <em>preprocessor directive.</em> It is actually handled by a different program than the compiler, and is removed and replaced by proper C++ code before the compiler sees it. The preprocessor is not interested in semicolons. This is why the <code>#define</code> line does not end in a semicolon. Neither do other lines that begin <code>#</code> usually end in semicolons.</p>
<p>As @JoachimIsaksson has noted, a needed semicolon may be missing from the end of the file <code>general_configuration.h</code> or the file <code>helper_function.h</code>. You should check the last line in each file.</p> |
11,498,366 | How to create an UI or a widget that sits on top of all applications in Android? | <p>Can I create an UI or a widget in Android that will sit on top of all applications? There are applications that have widgets like this. One example has a camera icon on top of all the applications that, when clicked, will capture the screen. </p> | 11,498,612 | 2 | 0 | null | 2012-07-16 05:03:36.6 UTC | 11 | 2017-05-15 21:58:56.853 UTC | 2017-05-15 21:58:56.853 UTC | null | 5,992,240 | null | 450,431 | null | 1 | 8 | android|android-windowmanager | 5,232 | <p>If you want to just display something, you can display it on top of everything even the lockscreen.</p>
<p>If you want something to be clickable, you can display it on top of anything except the lockscreen.</p>
<p>Here's a sample, modify to your needs:</p>
<p>Create a service and do the following:</p>
<pre><code>//These three are our main components.
WindowManager wm;
LinearLayout ll;
WindowManager.LayoutParams ll_lp;
//Just a sample layout parameters.
ll_lp = new WindowManager.LayoutParams();
ll_lp.format = PixelFormat.TRANSLUCENT;
ll_lp.height = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.width = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.gravity = Gravity.CLIP_HORIZONTAL | Gravity.TOP;
//This one is necessary.
ll_lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//Play around with these two.
ll_lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
ll_lp.flags = ll_lp.flags | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//This is our main layout.
ll = new LinearLayout(this);
ll.setBackgroundColor(android.graphics.Color.argb(0, 0, 0, 0));
ll.setHapticFeedbackEnabled(true);
//And finally we add what we created to the screen.
wm.addView(ll, ll_lp);
</code></pre> |
11,551,079 | Programmatically adding Label to Windows Form (Length of label?) | <p>In my code, i create a label with the following:</p>
<pre><code>Label namelabel = new Label();
namelabel.Location = new Point(13, 13);
namelabel.Text = name;
this.Controls.Add(namelabel);
</code></pre>
<p>The string called name is defined before this, and has a length of around 50 characters. However, only the first 15 are displayed in the label on my form. I tried messing with the MaximumSize of the label but to no avail.</p> | 11,551,100 | 4 | 1 | null | 2012-07-18 22:07:36.167 UTC | 2 | 2021-08-29 10:28:40.083 UTC | null | null | null | null | 1,116,831 | null | 1 | 12 | c#|.net|label|windows-forms-designer | 52,466 | <p>Try adding the AutoSize property:</p>
<pre><code>namelabel.AutoSize = true;
</code></pre>
<p>When you place a label on a form with the design editor, this property defaults to true, but if you create the label in code like you did, the default is false.</p> |
11,924,452 | Iterating over basic “for” loop using Handlebars.js | <p>I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.</p>
<p>Example.</p>
<pre><code>for(i=0 ; i<100 ; i++) {
create li's with i as the value
}
</code></pre>
<p>How can this be achieved?</p> | 11,924,998 | 5 | 0 | null | 2012-08-12 17:59:11.607 UTC | 25 | 2020-11-24 14:25:24.773 UTC | 2016-06-14 10:20:41.087 UTC | null | 313,106 | null | 1,184,100 | null | 1 | 82 | handlebars.js | 100,317 | <p>There's nothing in Handlebars for this but you can add your own helpers easily enough.</p>
<p>If you just wanted to do something <code>n</code> times then:</p>
<pre><code>Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i)
accum += block.fn(i);
return accum;
});
</code></pre>
<p>and</p>
<pre><code>{{#times 10}}
<span>{{this}}</span>
{{/times}}
</code></pre>
<p>If you wanted a whole <code>for(;;)</code> loop, then something like this:</p>
<pre><code>Handlebars.registerHelper('for', function(from, to, incr, block) {
var accum = '';
for(var i = from; i < to; i += incr)
accum += block.fn(i);
return accum;
});
</code></pre>
<p>and</p>
<pre><code>{{#for 0 10 2}}
<span>{{this}}</span>
{{/for}}
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/ambiguous/WNbrL/" rel="noreferrer">http://jsfiddle.net/ambiguous/WNbrL/</a></p> |
11,799,159 | trying to align html button at the center of the my page | <p>I'm trying to align an HTML button exactly at the centre of the page irrespective of the browser used. It is either floating to the left while still being at the vertical centre or being somewhere on the page like at the top of the page etc.. </p>
<p>I want it to be both vertically and horizontally be centered. Here is what I have written right now:</p>
<pre><code><button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname
</button>
</code></pre> | 11,799,200 | 9 | 1 | null | 2012-08-03 15:53:37.3 UTC | 21 | 2021-07-15 19:12:34.083 UTC | 2019-10-07 19:44:10.133 UTC | null | 2,756,409 | null | 1,455,116 | null | 1 | 118 | html|css|button|alignment|vertical-alignment | 1,006,015 | <p>Here's your solution: <a href="http://jsfiddle.net/7Laf8/" rel="noreferrer">JsFiddle</a></p>
<p>Basically, place your button into a div with centred text:</p>
<pre><code><div class="wrapper">
<button class="button">Button</button>
</div>
</code></pre>
<p>With the following styles:</p>
<pre><code>.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 50%;
}
</code></pre>
<p>There are many ways to skin a cat, and this is just one.</p> |
11,997,032 | How to get box-shadow on left & right sides only | <p>Any way to get box-shadow on left & right (horizontal?) sides only with no hacks or images. I am using:</p>
<pre><code>box-shadow: 0 0 15px 5px rgba(31, 73, 125, 0.8);
</code></pre>
<p>But it gives shadow all around.</p>
<p>I have no borders around the elements.</p> | 11,997,074 | 16 | 0 | null | 2012-08-16 23:49:59.47 UTC | 81 | 2021-11-10 13:22:56.23 UTC | null | null | null | null | 731,043 | null | 1 | 242 | html|css | 338,952 | <blockquote>
<p><strong>NOTE:</strong> I suggest checking out <a href="https://stackoverflow.com/a/17323375/605707">@Hamish's answer</a> below; it doesn't involve the imperfect "masking" in the solution described here.</p>
</blockquote>
<hr>
<p>You can get close with multiple box-shadows; one for each side</p>
<pre><code>box-shadow: 12px 0 15px -4px rgba(31, 73, 125, 0.8), -12px 0 8px -4px rgba(31, 73, 125, 0.8);
</code></pre>
<p><a href="http://jsfiddle.net/YJDdp/" rel="noreferrer">http://jsfiddle.net/YJDdp/</a></p>
<p><strong>Edit</strong></p>
<p>Add 2 more box-shadows for the top and bottom up front to mask out the that bleeds through.</p>
<pre><code>box-shadow: 0 9px 0px 0px white, 0 -9px 0px 0px white, 12px 0 15px -4px rgba(31, 73, 125, 0.8), -12px 0 15px -4px rgba(31, 73, 125, 0.8);
</code></pre>
<p><a href="http://jsfiddle.net/LE6Lz/" rel="noreferrer">http://jsfiddle.net/LE6Lz/</a></p> |
3,638,887 | What's the difference between self and window? | <p>I have a JavaScript that deals with with detection whether the page is in frames or not. I used top.frames[] etc. and everything works fine. </p>
<p>In this script I noticed that I can use "window" or "self" interchangeably and everything still works. Is "window" same as "self" when used in HTML page?</p> | 3,638,982 | 4 | 1 | null | 2010-09-03 19:21:13.883 UTC | 4 | 2019-08-20 04:52:09.077 UTC | null | null | null | null | 14,690 | null | 1 | 51 | javascript|window | 19,800 | <p>From <em>Javascript: The Definitive Guide</em>:</p>
<blockquote>
<p>The Window object defines a number of
properties and methods that allow you
to manipulate the web browser window.
It also defines properties that refer
to other important objects, such as
the <code>document</code> property for the
Document object. Finally, the Window
object has two self-referential
properties, <code>window</code> and <code>self</code>. You
can use either global variable to
refer directly to the Window object.</p>
</blockquote>
<p>In short, both <code>window</code> and <code>self</code> are references to the Window object, which is the global object of client-side javascript.</p> |
3,801,431 | Python: any way to perform this "hybrid" split() on multi-lingual (e.g. Chinese & English) strings? | <p>I have strings that are multi-lingual consist of both languages that use whitespace as word separator (English, French, etc) and languages that don't (Chinese, Japanese, Korean).</p>
<p>Given such a string, I want to separate the English/French/etc part into words using whitespace as separator, and to separate the Chinese/Japanese/Korean part into individual characters.</p>
<p>And I want to put of all those separated components into a list.</p>
<p>Some examples would probably make this clear:</p>
<p><strong>Case 1</strong>: English-only string. This case is easy:</p>
<pre><code>>>> "I love Python".split()
['I', 'love', 'Python']
</code></pre>
<p><strong>Case 2</strong>: Chinese-only string:</p>
<pre><code>>>> list(u"我爱蟒蛇")
[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']
</code></pre>
<p>In this case I can turn the string into a list of Chinese characters. But within the list I'm getting unicode representations:</p>
<pre><code>[u'\u6211', u'\u7231', u'\u87d2', u'\u86c7']
</code></pre>
<p>How do I get it to display the actual characters instead of the unicode? Something like:</p>
<pre><code>['我', '爱', '蟒', '蛇']
</code></pre>
<p>??</p>
<p><strong>Case 3</strong>: A mix of English & Chinese:</p>
<p>I want to turn an input string such as</p>
<pre><code>"我爱Python"
</code></pre>
<p>and turns it into a list like this:</p>
<pre><code>['我', '爱', 'Python']
</code></pre>
<p>Is it possible to do something like that?</p> | 3,801,846 | 5 | 2 | null | 2010-09-27 06:02:58.47 UTC | 12 | 2018-08-01 01:52:52.303 UTC | 2012-05-05 16:37:35.367 UTC | null | 1,079,354 | null | 86,073 | null | 1 | 12 | python|string|unicode|multilingual|cjk | 5,800 | <p>I thought I'd show the regex approach, too. It doesn't feel right to me, but that's mostly because all of the language-specific i18n oddnesses I've seen makes me worried that a regular expression might not be flexible enough for all of them--but you may well not need any of that. (In other words--overdesign.)</p>
<pre><code># -*- coding: utf-8 -*-
import re
def group_words(s):
regex = []
# Match a whole word:
regex += [ur'\w+']
# Match a single CJK character:
regex += [ur'[\u4e00-\ufaff]']
# Match one of anything else, except for spaces:
regex += [ur'[^\s]']
regex = "|".join(regex)
r = re.compile(regex)
return r.findall(s)
if __name__ == "__main__":
print group_words(u"Testing English text")
print group_words(u"我爱蟒蛇")
print group_words(u"Testing English text我爱蟒蛇")
</code></pre>
<p>In practice, you'd probably want to only compile the regex once, not on each call. Again, filling in the particulars of character grouping is up to you.</p> |
3,223,899 | PHP eval and capturing errors (as much as possible) | <p><strong><em>Disclaimer</strong>; I'm fully aware of the pitfalls and "evils" of eval, including but not limited to: performance issues, security, portability etc.</em></p>
<p><strong>The problem</strong></p>
<p>Reading the PHP manual on eval...</p>
<blockquote>
<p>eval() returns NULL unless return is
called in the evaluated code, in which
case the value passed to return is
returned. If there is a parse error in
the evaluated code, eval() returns
FALSE and execution of the following
code continues normally. It is not
possible to catch a parse error in
eval() using set_error_handler().</p>
</blockquote>
<p>In short, no error capture except returning false which is very helpful, but I'm sur eI could do way better!</p>
<p><strong>The reason</strong></p>
<p>A part of the site's functionality I'm working on relies on executing expressions. I'd like not to pass through the path of sandbox or execution modules, so I've ended using eval. Before you shout "what if the client turned bad?!" know that the client is pretty much trusted; he wouldn't want to break his own site, and anyone getting access to this functionality pretty much owns the server, regardless of eval.</p>
<p>The client knows about expressions like in Excel, and it isn't a problem explaining the little differences, however, having some form of warning is pretty much standard functionality.</p>
<p>This is what I have so far:</p>
<pre><code>define('CR',chr(13));
define('LF',chr(10));
function test($cond=''){
$cond=trim($cond);
if($cond=='')return 'Success (condition was empty).'; $result=false;
$cond='$result = '.str_replace(array(CR,LF),' ',$cond).';';
try {
$success=eval($cond);
if($success===false)return 'Error: could not run expression.';
return 'Success (condition return '.($result?'true':'false').').';
}catch(Exception $e){
return 'Error: exception '.get_class($e).', '.$e->getMessage().'.';
}
}
</code></pre>
<p><strong>Notes</strong></p>
<ul>
<li>The function returns a message string in any event</li>
<li>The code expression should be a single-line piece of PHP, without PHP tags and without an ending semicolon</li>
<li>New lines are converted to spaces</li>
<li>A variable is added to contain the result (expression should return either true or false, and in order not to conflict with eval's return, a temp variable is used.)</li>
</ul>
<p>So, what would you add to further aide the user? Is there any further parsing functions which might better pinpoint possible errors/issues?</p>
<p>Chris.</p> | 3,224,985 | 6 | 3 | null | 2010-07-11 17:01:42.46 UTC | 10 | 2021-08-18 11:07:32.42 UTC | 2010-07-11 17:36:21.907 UTC | null | 314,056 | null | 314,056 | null | 1 | 33 | php|exception|parsing|eval | 28,793 | <p>I've found a good alternative/answer to my question.</p>
<p>First of, let me start by saying that nikic's suggestion works when I set error_reporting(E_ALL); notices are shown in PHP output, and thanks to OB, they can be captured.</p>
<p>Next, I've found this very useful code:</p>
<pre><code>/**
* Check the syntax of some PHP code.
* @param string $code PHP code to check.
* @return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned.
*/
function php_syntax_error($code){
if(!defined("CR"))
define("CR","\r");
if(!defined("LF"))
define("LF","\n") ;
if(!defined("CRLF"))
define("CRLF","\r\n") ;
$braces=0;
$inString=0;
foreach (token_get_all('<?php ' . $code) as $token) {
if (is_array($token)) {
switch ($token[0]) {
case T_CURLY_OPEN:
case T_DOLLAR_OPEN_CURLY_BRACES:
case T_START_HEREDOC: ++$inString; break;
case T_END_HEREDOC: --$inString; break;
}
} else if ($inString & 1) {
switch ($token) {
case '`': case '\'':
case '"': --$inString; break;
}
} else {
switch ($token) {
case '`': case '\'':
case '"': ++$inString; break;
case '{': ++$braces; break;
case '}':
if ($inString) {
--$inString;
} else {
--$braces;
if ($braces < 0) break 2;
}
break;
}
}
}
$inString = @ini_set('log_errors', false);
$token = @ini_set('display_errors', true);
ob_start();
$code = substr($code, strlen('<?php '));
$braces || $code = "if(0){{$code}\n}";
if (eval($code) === false) {
if ($braces) {
$braces = PHP_INT_MAX;
} else {
false !== strpos($code,CR) && $code = strtr(str_replace(CRLF,LF,$code),CR,LF);
$braces = substr_count($code,LF);
}
$code = ob_get_clean();
$code = strip_tags($code);
if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
$code[2] = (int) $code[2];
$code = $code[2] <= $braces
? array($code[1], $code[2])
: array('unexpected $end' . substr($code[1], 14), $braces);
} else $code = array('syntax error', 0);
} else {
ob_end_clean();
$code = false;
}
@ini_set('display_errors', $token);
@ini_set('log_errors', $inString);
return $code;
}
</code></pre>
<p>Seems it easily does exactly what I need (yay)!</p> |
3,550,337 | WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED | <p>Could someone give me some guidance on when I should use <code>WITH (NOLOCK)</code> as opposed to <code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED</code></p>
<p>What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?</p> | 3,550,398 | 6 | 0 | null | 2010-08-23 18:05:07.963 UTC | 43 | 2015-07-09 17:44:44.117 UTC | 2014-07-18 09:22:52.307 UTC | null | 27,825 | null | 195,583 | null | 1 | 131 | sql|sql-server|sql-server-2005 | 148,617 | <p>They are the same thing. If you use the <code>set transaction isolation level</code> statement, it will apply to all the tables in the connection, so if you only want a <code>nolock</code> on one or two tables use that; otherwise use the other. </p>
<p>Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider <code>snapshot</code> or <code>serializable</code> hints instead.</p> |
3,592,079 | Minimum window width in string x that contains all characters of string y | <p>Find minimum window width in string <code>x</code> that contains all characters of another string <code>y</code>. For example:</p>
<pre><code>String x = "coobdafceeaxab"
String y = "abc"
</code></pre>
<p>The answer should be 5, because the shortest substring in <code>x</code> that contains all three letters of <code>y</code> is "bdafc".</p>
<p>I can think of a naive solution with complexity <code>O(n^2 * log(m))</code>, where <code>n = len(x)</code> and <code>m = len(y)</code>. Can anyone suggest a better solution? Thanks.</p>
<p><strong>Update</strong>: now think of it, if I change my set to <code>tr1::unordered_map</code>, then I can cut the complexity down to <code>O(n^2)</code>, because insertion and deletion should both be <code>O(1)</code>.</p> | 3,592,224 | 7 | 3 | null | 2010-08-28 19:10:41.047 UTC | 18 | 2017-08-31 14:33:14.503 UTC | 2017-08-31 14:33:14.503 UTC | null | 10,265,365 | null | 203,091 | null | 1 | 20 | algorithm | 7,602 | <p><strong>time: O(n) (One pass)<br>
space: O(k)</strong></p>
<p>This is how I would do it:<br>
Create a hash table for all the characters from string Y. (I assume all characters are different in Y). </p>
<p>First pass:<br>
Start from first character of string X.<br>
update hash table, for exa: for key 'a' enter location (say 1).<br>
Keep on doing it until you get all characters from Y (until all key in hash table has value).<br>
If you get some character again, update its newer value and erase older one.</p>
<p>Once you have first pass, take smallest value from hash table and biggest value.<br>
Thats the minimum window observed so far.</p>
<p>Now, go to next character in string X, update hash table and see if you get smaller window.</p>
<p><hr>
<strong>Edit:</strong> </p>
<p>Lets take an example here:<br>
String x = "coobdafceeaxab"<br>
String y = "abc"</p>
<p>First initialize a hash table from characters of Y.<br>
h[a] = -1<br>
h[b] = -1<br>
h[c] = -1</p>
<p>Now, Start from first character of X.<br>
First character is c, h[c] = 0<br>
Second character (o) is not part of hash, skip it.<br>
..<br>
Fourth character (b), h[b] = 3<br>
..<br>
Sixth character(a), enter hash table h[a] = 5.<br>
Now, all keys from hash table has some value.<br>
Smallest value is 0 (of c) and highest value is 5 (of a), minimum window so far is 6 (0 to 5).<br>
First pass is done. </p>
<p>Take next character. f is not part of hash table, skip it.<br>
Next character (c), update hash table h[c] = 7.<br>
Find new window, smallest value is 3 (of b) and highest value is 7 (of c).<br>
New window is 3 to 7 => 5.</p>
<p>Keep on doing it till last character of string X.</p>
<p>I hope its clear now.
<hr>
<strong>Edit</strong></p>
<p>There are some concerns about finding max and min value from hash.<br>
We can maintain sorted Link-list and map it with hash table.<br>
Whenever any element from Link list changes, it should be re-mapped to hash table.<br>
Both these operation are O(1) </p>
<p>Total space would be m+m</p>
<p><hr>
<strong>Edit</strong></p>
<p>Here is small visualisation of above problem:
For "coobdafceeaxab" and "abc" </p>
<p>step-0:<br>
Initial doubly linked-list = NULL<br>
Initial hash-table = NULL </p>
<p>step-1:<br>
Head<->[c,0]<->tail<br>
h[c] = [0, 'pointer to c node in LL'] </p>
<p>step-2:<br>
Head<->[c,0]<->[b,3]<->tail<br>
h[c] = [0, 'pointer to c node in LL'], h[b] = [3, 'pointer to b node in LL'], </p>
<p>Step-3:<br>
Head<->[c,0]<->[b,3]<->[a,5]<->tail<br>
h[c] = [0, 'pointer to c node in LL'], h[b] = [3, 'pointer to b node in LL'], h[a] = [5, 'pointer to a node in LL']<br>
Minimum Window => difference from tail and head => (5-0)+1 => Length: 6 </p>
<p>Step-4:<br>
Update entry of C to index 7 here. (Remove 'c' node from linked-list and append at the tail)<br>
Head<->[b,3]<->[a,5]<->[c,7]<->tail<br>
h[c] = [7, 'new pointer to c node in LL'], h[b] = [3, 'pointer to b node in LL'], h[a] = [5, 'pointer to a node in LL'],<br>
Minimum Window => difference from tail and head => (7-3)+1 => Length: 5 </p>
<p>And so on.. </p>
<p>Note that above Linked-list update and hash table update are both O(1).<br>
Please correct me if I am wrong.. </p>
<p><hr>
<strong>Summary:</strong></p>
<p>TIme complexity: O(n) with one pass<br>
Space Complexity: O(k) where k is length of string Y</p> |
3,502,530 | Using Visual Studio project properties effectively for multiple projects and configurations | <p>I have always used Visual Studios built in GUI support for configuring my projects, often using property sheets so that several projects will use a common set.</p>
<p>One of my main gripes with this is managing multiple projects, configurations and platforms. If you just do everything with the main GUI (right click the project -> properties) it quickly becomes a mess, difficult to maintain and prone to bugs (like failing to correctly define some macro, or using the wrong runtime library, etc). Dealing with the fact that different people put there dependency libraries in different places (eg mine all live in "C:\Libs\[C,C++]\[lib-name]\") and then often manage the different versions of those libraries differently as well (release, debug, x86, x64, etc) is also a large problem since it vastly complicates the time to set it up on a new system, and then there is issues with version-control and keeping everyone's paths separate...</p>
<p>Property sheets make this a bit better, but I cant have one sheet have separate settings for different configurations and platforms (the drop down boxes a greyed out), resulting in me having many sheets which if inherited in the correct order do what I want ("x86", "x64", "debug", "release", "common", "directories" (deals with the previously mentioned dependency issue by defining user macros like BoostX86LibDir), etc) and if inherited in the wrong order (eg "common" before "x64" and "debug") lead to issues like trying to link an incorrect library version, or incorrectly naming the output...</p>
<p>What I want is a way of dealing with all these scattered dependencies and setting up a set of "rules" which are used by all my projects in the solution, like naming an output library as "mylib-[vc90,vc100]-[x86,x64][-d].lib", without having to do all this for each individual project, configuration and platform combination, and then keep them all correctly in sync.</p>
<p>I am aware of moving to entirely different systems like CMake that create the needed files, however this then complicates things elsewhere by making it so even simple tasks like adding a new file to the project then requires additional changes elsewhere, which is not something I am entirely happy with either, unless there is some with VS2010 integration which can keep track of these sorts of changes.</p> | 3,503,738 | 7 | 1 | null | 2010-08-17 12:48:44.89 UTC | 59 | 2021-12-21 15:48:37.14 UTC | 2015-01-12 16:01:52.947 UTC | null | 11,343 | null | 6,266 | null | 1 | 70 | c++|visual-studio-2010|visual-studio|build|projects-and-solutions | 37,251 | <p>I just found out somthing I didnt think was possible (it is not exposed by the GUI) that helps make property sheet far more useful. The "Condition" attribute of many of the tags in the project property files and it can be used in the .props files as well!</p>
<p>I just put together the following as a test and it worked great and did the task of 5 (common,x64,x86,debug,release) separate property sheets!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="UserMacros">
<!--debug suffix-->
<DebugSuffix Condition="'$(Configuration)'=='Debug'">-d</DebugSuffix>
<DebugSuffix Condition="'$(Configuration)'!='Debug'"></DebugSuffix>
<!--platform-->
<ShortPlatform Condition="'$(Platform)' == 'Win32'">x86</ShortPlatform>
<ShortPlatform Condition="'$(Platform)' == 'x64'">x64</ShortPlatform>
<!--toolset-->
<Toolset Condition="'$(PlatformToolset)' == 'v90'">vc90</Toolset>
<Toolset Condition="'$(PlatformToolset)' == 'v100'">vc100</Toolset>
</PropertyGroup>
<!--target-->
<PropertyGroup>
<TargetName>$(ProjectName)-$(Toolset)-$(ShortPlatform)$(DebugSuffix)</TargetName>
</PropertyGroup>
</Project>
</code></pre>
<p>Only issue is the properties GUI cant handle it, a project that uses the above property sheet just reports default inherited values like "$(ProjectName)" for the target.</p> |
3,567,835 | $(this).val() not working to get text from span using jquery | <p>Giving this html, i want to grab "August" from it when i click on it:</p>
<pre><code><span class="ui-datepicker-month">August</span>
</code></pre>
<p>i tried </p>
<pre><code>$(".ui-datepicker-month").live("click", function () {
var monthname = $(this).val();
alert(monthname);
});
</code></pre>
<p>but doesn't seem to be working</p> | 3,567,845 | 7 | 0 | null | 2010-08-25 15:55:01.683 UTC | 18 | 2019-10-10 02:32:48.953 UTC | 2019-10-10 02:32:48.953 UTC | null | 85,950 | null | 4,653 | null | 1 | 110 | jquery|html | 270,499 | <p>Instead of <a href="http://api.jquery.com/val/" rel="noreferrer"><code>.val()</code></a> use <a href="http://api.jquery.com/text/" rel="noreferrer"><code>.text()</code></a>, like this:</p>
<pre><code>$(".ui-datepicker-month").live("click", function () {
var monthname = $(this).text();
alert(monthname);
});
</code></pre>
<p>Or in jQuery 1.7+ use <code>on()</code> as <code>live</code> is deprecated:</p>
<pre><code>$(document).on('click', '.ui-datepicker-month', function () {
var monthname = $(this).text();
alert(monthname);
});
</code></pre>
<p><a href="http://api.jquery.com/val/" rel="noreferrer"><code>.val()</code></a> is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use <a href="http://api.jquery.com/text/" rel="noreferrer"><code>.text()</code></a> here.</p> |
3,626,752 | Key existence check in HashMap | <p>Is checking for key existence in HashMap always necessary?</p>
<p>I have a HashMap with say a 1000 entries and I am looking at improving the efficiency.
If the HashMap is being accessed very frequently, then checking for the key existence at every access will lead to a large overhead. Instead if the key is not present and hence an exception occurs, I can catch the exception. (when I know that this will happen rarely). This will reduce accesses to the HashMap by half.</p>
<p>This might not be a good programming practice, but it will help me reduce the number of accesses. Or am I missing something here?</p>
<p>[<strong>Update</strong>] I do not have null values in the HashMap.</p> | 3,626,779 | 11 | 1 | null | 2010-09-02 11:45:16.013 UTC | 68 | 2022-06-14 07:58:22.5 UTC | 2010-09-02 11:53:09.52 UTC | null | 150,505 | null | 150,505 | null | 1 | 355 | java|hashmap | 577,870 | <p>Do you ever store a null value? If not, you can just do:</p>
<pre><code>Foo value = map.get(key);
if (value != null) {
...
} else {
// No such key
}
</code></pre>
<p>Otherwise, you <em>could</em> just check for existence if you get a null value returned:</p>
<pre><code>Foo value = map.get(key);
if (value != null) {
...
} else {
// Key might be present...
if (map.containsKey(key)) {
// Okay, there's a key but the value is null
} else {
// Definitely no such key
}
}
</code></pre> |
4,116,001 | Android Lock Screen Widget | <p>A few users have been asking me Android lock screen widgets for my app - I believe they want a widget that stays on their lock screens and allows them to interact with the app.</p>
<p>I haven't been able to find any official documentation for this - the only thing I found was apps that will take home screen widgets and put them on the lock screen for you.</p>
<p>Any clues on where I learn more about building true lock-screen widgets?</p> | 4,666,109 | 3 | 7 | null | 2010-11-07 00:57:40.653 UTC | 68 | 2016-09-07 15:09:40.547 UTC | 2012-10-16 01:57:08.17 UTC | null | 1,665,345 | null | 106,095 | null | 1 | 79 | android|android-widget|lockscreen | 78,671 | <p>Lock screen interaction is difficult. Android allows basic operations with two window flags (FLAG_SHOW_WHEN_LOCKED and FLAG_DISMISS_KEYGUARD). FLAG_SHOW_WHEN_LOCKED works pretty consistently in that it will show on top of the lock screen even when security is enabled (the security isn't bypassed, you can't switch to another non-FLAG_SHOW_WHEN_LOCKED window).</p>
<p>If you're just doing something temporary, like while music is playing or similar, you'll probably mostly be okay. If you're trying to create a custom lock screen then there's a lot of unusual interactions on all the different android platforms. ("Help! I can't turn off my alarm without rebooting my HTC phone"). </p>
<pre><code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
</code></pre>
<p><a href="http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html" rel="noreferrer">http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html</a></p>
<pre><code>FLAG_SHOW_WHEN_LOCKED
</code></pre>
<blockquote>
<p>Window flag: special flag to let windows be shown when the screen is
locked.</p>
</blockquote>
<pre><code>FLAG_DISMISS_KEYGUARD
</code></pre>
<blockquote>
<p>Window flag:
when set the window will cause the keyguard to be
dismissed, only if it is not a secure
lock keyguard. Because such a keyguard
is not needed for security, it will
never re-appear if the user navigates
to another window (in contrast to
FLAG_SHOW_WHEN_LOCKED, which will only
temporarily hide both secure and
non-secure keyguards but ensure they
reappear when the user moves to
another UI that doesn't hide them). If
the keyguard is currently active and
is secure (requires an unlock pattern)
than the user will still need to
confirm it before seeing this window,
unless FLAG_SHOW_WHEN_LOCKED has also
been set.
Constant Value: 4194304 (0x00400000)</p>
</blockquote> |
4,228,739 | VS2010 + Oracle driver: ORA-12154: TSN:could not resolve the connect identifier specified | <p>I am using:</p>
<ul>
<li>Visual Studio 2010</li>
<li>.Net Framework Data Provider for Oracle</li>
<li>Oracle Developer Tools for Visual Studio (from Oracle's website)</li>
</ul>
<p>I tried installing 'Oracle Developer Tools for Visual Studio' and created tnsnames.ora and sqlnet.ora files in my C:\app\ [my username]\product\11.2.0\client_1\Network\Admin directory. </p>
<p>They look like this:</p>
<pre><code># tnsnames.ora
ORATEST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = dbs-oratest)(PORT = 1521))
)
(CONNECT_DATA =
(SID = [ORATEST])
)
)
</code></pre>
<p>and</p>
<pre><code># sqlnet.ora
SQLNET.AUTHENTICATION_SERVICES= (ALL)
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
</code></pre>
<p>When I try using the .Net Framework Data Provider for Oracle driver to set up a new connection (or any other driver for that matter: OLE, ODBC, etc) it gives the error:</p>
<p><em>ORA-12154: TSN:could not resolve the connect identifier specified</em></p>
<p>Using the OLE driver on a machine <em>without</em> the Oracle client installed DOES work though:</p>
<pre><code>OleDbConnection conn = new OleDbConnection(
"Provider=MSDAORA;Data Source=ORATEST;" +
"Persist Security Info=True;Password=readonly;User ID=readonlyuser");
</code></pre>
<p>What am I doing wrong? Are there any simple instructions online about how to install a basic Oracle driver?</p>
<p>Thank you in advance!</p> | 7,919,008 | 4 | 0 | null | 2010-11-19 19:40:21.553 UTC | null | 2015-06-19 20:28:12.293 UTC | null | null | null | null | 386,806 | null | 1 | 3 | .net|visual-studio|oracle|driver | 40,497 | <p>The best solution I found was to use the Oracle Data Access Client library, and include the entire TNS names entry in the connection string. This allows the project to be easily published to a web server, ClickOnce, etc. </p>
<p>Here are the steps necessary to set up the Oracle driver working in your project:</p>
<p><strong>1) Get DLLs from 'Oracle Data Provider for .NET' package</strong></p>
<p>Download installer file from this location: <a href="http://www.oracle.com/technetwork/topics/dotnet/index-085163.html" rel="nofollow">http://www.oracle.com/technetwork/topics/dotnet/index-085163.html</a></p>
<p>I went ahead and installed the full 200 MB ODAC with Oracle Developer Tools for Visual Studio, but you only really need four DLLs from this download. (You may be able to extract them directly from the installer package, instead of going through the entire install process, or perhaps one of the smaller download includes all of them.)</p>
<p><strong>2) Reference DLLs in your project</strong></p>
<p>Search the installation directory of the Oracle Data Access Client and drag the following four DLLs into the root of your project:</p>
<ul>
<li>Oracle.DataAccess.dll </li>
<li>oci.dll</li>
<li>oraciicus11.dll</li>
<li>OraOps11w.dll</li>
</ul>
<p>Set the <strong>Copy to Output Directory</strong> property all of the files except Oracle.DataAccess.dll to <strong>Copy always</strong>.</p>
<p>Under <strong>Project</strong> --> <strong>Add Reference...</strong>, click on the <strong>Browse</strong> tab and select the Oracle.DataAccess.dll file.</p>
<p><strong>3) Use the driver with full connection string (optional)</strong></p>
<p>So as not to have to worry about TNS names files being set up on the machines the application was deployed to, I put the entire definition in the file as shown by <a href="http://www.connectionstrings.com/oracle" rel="nofollow">connectionstrings.com</a>. It makes the connection string a little bulky, but removed a lot of the TNS Names file headaches I was experiencing before:</p>
<pre><code>Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=servername)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=servicename)));User Id=username;Password=********;
</code></pre>
<p>Here's the full class I used to test the driver:</p>
<pre><code>using System;
using System.Data;
using Oracle.DataAccess.Client;
static class Program
{
[STAThread]
static void Main()
{
TestOracle();
}
private static void TestOracle()
{
string connString =
"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" +
"(HOST=servername)(PORT=1521)))" +
"(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=servicename)));"+
"User Id=username;Password=********;";
using (OracleConnection conn = new OracleConnection(connString))
{
string sqlSelect = "SELECT * FROM TEST_TABLE";
using (OracleDataAdapter da = new OracleDataAdapter(sqlSelect, conn))
{
var table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 1)
Console.WriteLine("Successfully read oracle.");
}
}
}
}
</code></pre> |
4,255,308 | Building a multidimensional array in vb.net | <p>I'm trying to build up a multidimensional array which will hold two bits of info for each record in a database e.g. id, description.</p>
<p>This is what I am currently doing.</p>
<pre><code>Dim mArray(,) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
End While
</code></pre>
<p>The problem I have here is that it doesn't like the <code>i</code> in <code>mArray(i,0)</code>. Anyone have any ideas about this? This is the error that is given <code>Object reference not set to an instance of an object.</code></p>
<p>Thanks for any and all help.</p>
<p>Nalum</p> | 4,255,327 | 5 | 0 | null | 2010-11-23 10:58:47.49 UTC | 3 | 2018-11-21 11:14:43.993 UTC | null | null | null | null | 189,154 | null | 1 | 10 | vb.net|multidimensional-array|while-loop | 89,763 | <p>Why not rather make use of <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer">List Class</a> and <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer">Dictionary Class</a></p>
<p>You can rather then create a List of Dictionaries, with the key and value both strings. The key can then represent your key (id and description in your example, and the value can be what ever was stored).</p>
<p>Something like </p>
<pre><code>Dim values As New List(Of Dictionary(Of String, String))()
</code></pre>
<p>and then in the while loop something like</p>
<pre><code>values.Add(New Dictionary(Of String, String)() From { _
{"id", cmdReader.Item("id")} _
})
values.Add(New Dictionary(Of String, String)() From { _
{"description", cmdReader.Item("description")} _
})
</code></pre>
<p>You could then use foreach</p>
<pre><code>For Each value As Dictionary(Of String, String) In values
Dim id As String = value("id")
Dim description As String = value("description")
Next
</code></pre>
<p>Or a for</p>
<pre><code>For i As Integer = 0 To values.Count - 1
Dim value As Dictionary(Of String, String) = values(i)
Dim id As String = value("id")
Dim description As String = value("description")
Next
</code></pre> |
4,200,172 | C, socket programming: Connecting multiple clients to server using select() | <p>I'm trying to make a server that can be connected to by multiple clients. Here's my code so far:</p>
<p>Client:</p>
<pre><code>int main(int argc, char **argv) {
struct sockaddr_in servaddr;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) perror("Socket");
bzero((void *) &servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6782);
servaddr.sin_addr.s_addr = inet_addr(<server_ip_address>);
if (-1 == connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)))
perror("Connect");
while(1) {
char message[6];
fgets(message, 6, stdin);
message[5] = '\0';
send(sock, message, 6, 0);
}
close(sock);
}
</code></pre>
<p>Server:</p>
<pre><code>int main(int argc, char **argv) {
fd_set fds, readfds;
int i, clientaddrlen;
int clientsock[2], rc, numsocks = 0, maxsocks = 2;
int serversock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serversock == -1) perror("Socket");
struct sockaddr_in serveraddr, clientaddr;
bzero(&serveraddr, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(6782);
if (-1 == bind(serversock, (struct sockaddr *)&serveraddr,
sizeof(struct sockaddr_in)))
perror("Bind");
if (-1 == listen(serversock, SOMAXCONN))
perror("Listen");
FD_ZERO(&fds);
FD_SET(serversock, &fds);
while(1) {
readfds = fds;
rc = select(FD_SETSIZE, &readfds, NULL, NULL, NULL);
if (rc == -1) {
perror("Select");
break;
}
for (i = 0; i < FD_SETSIZE; i++) {
if (FD_ISSET(i, &readfds)) {
if (i == serversock) {
if (numsocks < maxsocks) {
clientsock[numsocks] = accept(serversock,
(struct sockaddr *) &clientaddr,
(socklen_t *)&clientaddrlen);
if (clientsock[numsocks] == -1) perror("Accept");
FD_SET(clientsock[numsocks], &fds);
numsocks++;
} else {
printf("Ran out of socket space.\n");
}
} else {
int messageLength = 5;
char message[messageLength+1];
int in, index = 0, limit = messageLength+1;
while ((in = recv(clientsock[i], &message[index], limit, 0)) > 0) {
index += in;
limit -= in;
}
printf("%d\n", index);
printf("%s\n", message);
}
}
}
}
close(serversock);
return 0;
}
</code></pre>
<p>As soon as a client connects and sends its first message, the server just runs in an infinite loop, and spits out garbage from the message array. recv doesn't seem to receive anything. Can anyone see where i go wrong?</p> | 4,200,467 | 5 | 0 | null | 2010-11-16 23:41:04.82 UTC | 9 | 2018-02-11 19:42:16.033 UTC | 2015-01-01 01:03:20.923 UTC | null | 4,186,297 | null | 506,678 | null | 1 | 13 | c|sockets|network-programming|client|select-function | 39,734 | <p>Two issues in your code:</p>
<ul>
<li><p>You should do <code>recv(i, ...)</code> instead of <code>recv(clientsock[i], ...)</code></p></li>
<li><p>After that you do not check if <code>recv()</code> failed, and therefore <code>printf()</code> prints out the uninitialised buffer <code>message</code>, hence the garbage in the output</p></li>
</ul> |
4,614,331 | Using volatile keyword with mutable object | <p>In Java, I understand that <code>volatile</code> keyword provides visibility to variables. The question is, if a variable is a reference to a mutable object, does <code>volatile</code> also provide visibility to the members inside that object?</p>
<p>In the example below, does it work correctly if multiple threads are accessing <code>volatile Mutable m</code> and changing the <code>value</code>?</p>
<p>example</p>
<pre><code>class Mutable {
private int value;
public int get()
{
return a;
}
public int set(int value)
{
this.value = value;
}
}
class Test {
public volatile Mutable m;
}
</code></pre> | 4,629,148 | 5 | 2 | null | 2011-01-06 11:19:52.74 UTC | 8 | 2022-06-23 07:19:18.92 UTC | 2022-06-23 07:19:18.92 UTC | null | 168,986 | null | 277,422 | null | 1 | 32 | java|concurrency|volatile|mutable | 11,049 | <p>This is sort of a side note explanation on some of the details of volatile. Writing this here because it is too much for an comment. I want to give some examples which show how volatile affects visibility, and how that changed in jdk 1.5.</p>
<p>Given the following example code:</p>
<pre><code>public class MyClass
{
private int _n;
private volatile int _volN;
public void setN(int i) {
_n = i;
}
public void setVolN(int i) {
_volN = i;
}
public int getN() {
return _n;
}
public int getVolN() {
return _volN;
}
public static void main() {
final MyClass mc = new MyClass();
Thread t1 = new Thread() {
public void run() {
mc.setN(5);
mc.setVolN(5);
}
};
Thread t2 = new Thread() {
public void run() {
int volN = mc.getVolN();
int n = mc.getN();
System.out.println("Read: " + volN + ", " + n);
}
};
t1.start();
t2.start();
}
}
</code></pre>
<p>The behavior of this test code is well defined in jdk1.5+, but is <strong>not</strong> well defined pre-jdk1.5.</p>
<p>In the pre-jdk1.5 world, there was no defined relationship between volatile accesses and non-volatile accesses. therefore, the output of this program could be:</p>
<ol>
<li>Read: 0, 0</li>
<li>Read: 0, 5</li>
<li>Read: 5, 0</li>
<li>Read: 5, 5</li>
</ol>
<p>In the jdk1.5+ world, the semantics of volatile were changed so that volatile accesses affect non-volatile accesses in exactly the same way as synchronization. therefore, only certain outputs are possible in the jdk1.5+ world:</p>
<ol>
<li>Read: 0, 0</li>
<li>Read: 0, 5</li>
<li>Read: 5, 0 <strong><- not possible</strong></li>
<li>Read: 5, 5</li>
</ol>
<p>Output 3. is not possible because the reading of "5" from the volatile _volN establishes a synchronization point between the 2 threads, which means all actions from t1 taken before the assignment to _volN <em>must</em> be visible to t2.</p>
<p>Further reading:</p>
<ul>
<li><a href="http://www.ibm.com/developerworks/library/j-jtp02244.html" rel="noreferrer">Fixing the java memory model, part 1</a></li>
<li><a href="http://www.ibm.com/developerworks/library/j-jtp03304/" rel="noreferrer">Fixing the java memory model, part 2</a></li>
</ul> |
4,664,229 | Here document as an argument to bash function | <p>Is it possible to pass a here document as a bash function argument, and in the function have the parameter preserved as a multi-lined variable?</p>
<p>Something along the following lines:</p>
<pre><code>function printArgs {
echo arg1="$1"
echo -n arg2=
cat <<EOF
$2
EOF
}
printArgs 17 <<EOF
18
19
EOF
</code></pre>
<p>or maybe:</p>
<pre><code>printArgs 17 $(cat <<EOF
18
19
EOF)
</code></pre>
<p>I have a here document that I want to feed to ssh as the commands to execute, and the ssh session is called from a bash function.</p> | 4,665,893 | 5 | 0 | null | 2011-01-12 00:26:12.907 UTC | 7 | 2018-01-31 07:08:27.357 UTC | null | null | null | null | 572,058 | null | 1 | 48 | bash|function|shell|arguments|heredoc | 17,721 | <p>If you're not using something that will absorb standard input, then you will have to supply something that does it:</p>
<pre><code>$ foo () { while read -r line; do var+=$line; done; }
$ foo <<EOF
a
b
c
EOF
</code></pre> |
4,743,115 | How do I use bitwise operators on a "double" on C++? | <p>I was asked to get the internal binary representation of different types in C. My program currently works fine with 'int' but I would like to use it with "double" and "float". My code looks like this:</p>
<pre><code>template <typename T>
string findBin(T x) {
string binary;
for(int i = 4096 ; i >= 1; i/=2) {
if((x & i) != 0) binary += "1";
else binary += "0";
}
return binary;
}
</code></pre>
<p>The program fails when I try to instantiate the template using a "double" or a "float".</p> | 4,743,141 | 6 | 3 | null | 2011-01-20 03:16:51.53 UTC | 2 | 2019-08-20 01:55:27.143 UTC | 2011-01-20 03:28:09.89 UTC | null | 501,557 | null | 521,806 | null | 1 | 9 | c++|bitwise-operators | 40,893 | <p>Succinctly, you don't.</p>
<p>The bitwise operators do not make sense when applied to <code>double</code> or <code>float</code>, and the standard says that the bitwise operators (<code>~</code>, <code>&</code>, <code>|</code>, <code>^</code>, <code>>></code>, <code><<</code>, and the assignment variants) do not accept <code>double</code> or <code>float</code> operands.</p>
<p>Both <code>double</code> and <code>float</code> have 3 sections - a sign bit, an exponent, and the mantissa. Suppose for a moment that you could shift a <code>double</code> right. The exponent, in particular, means that there is no simple translation to shifting a bit pattern right - the sign bit would move into the exponent, and the least significant bit of the exponent would shift into the mantissa, with completely non-obvious sets of meanings. In IEEE 754, there's an implied 1 bit in front of the actual mantissa bits, which also complicates the interpretation.</p>
<p>Similar comments apply to any of the other bit operators.</p>
<p>So, because there is no sane or useful interpretation of the bit operators to <code>double</code> values, they are not allowed by the standard.</p>
<hr>
<p>From the comments:</p>
<blockquote>
<p>I'm only interested in the binary representation. I just want to print it, not do anything useful with it.</p>
</blockquote>
<p>This code was written several years ago for SPARC (big-endian) architecture.</p>
<pre><code>#include <stdio.h>
union u_double
{
double dbl;
char data[sizeof(double)];
};
union u_float
{
float flt;
char data[sizeof(float)];
};
static void dump_float(union u_float f)
{
int exp;
long mant;
printf("32-bit float: sign: %d, ", (f.data[0] & 0x80) >> 7);
exp = ((f.data[0] & 0x7F) << 1) | ((f.data[1] & 0x80) >> 7);
printf("expt: %4d (unbiassed %5d), ", exp, exp - 127);
mant = ((((f.data[1] & 0x7F) << 8) | (f.data[2] & 0xFF)) << 8) | (f.data[3] & 0xFF);
printf("mant: %16ld (0x%06lX)\n", mant, mant);
}
static void dump_double(union u_double d)
{
int exp;
long long mant;
printf("64-bit float: sign: %d, ", (d.data[0] & 0x80) >> 7);
exp = ((d.data[0] & 0x7F) << 4) | ((d.data[1] & 0xF0) >> 4);
printf("expt: %4d (unbiassed %5d), ", exp, exp - 1023);
mant = ((((d.data[1] & 0x0F) << 8) | (d.data[2] & 0xFF)) << 8) | (d.data[3] & 0xFF);
mant = (mant << 32) | ((((((d.data[4] & 0xFF) << 8) | (d.data[5] & 0xFF)) << 8) | (d.data[6] & 0xFF)) << 8) | (d.data[7] & 0xFF);
printf("mant: %16lld (0x%013llX)\n", mant, mant);
}
static void print_value(double v)
{
union u_double d;
union u_float f;
f.flt = v;
d.dbl = v;
printf("SPARC: float/double of %g\n", v);
// image_print(stdout, 0, f.data, sizeof(f.data));
// image_print(stdout, 0, d.data, sizeof(d.data));
dump_float(f);
dump_double(d);
}
int main(void)
{
print_value(+1.0);
print_value(+2.0);
print_value(+3.0);
print_value( 0.0);
print_value(-3.0);
print_value(+3.1415926535897932);
print_value(+1e126);
return(0);
}
</code></pre>
<p>The commented out 'image_print()` function prints an arbitrary set of bytes in hex, with various minor tweaks. Contact me if you want the code (see my profile).</p>
<p>If you're using Intel (little-endian), you'll probably need to tweak the code to deal with the reverse bit order. But it shows how you can do it - using a <code>union</code>.</p> |
4,087,839 | OnEditorActionListener called twice with same eventTime on SenseUI keyboard | <p>On just one phone I am testing on (HTC Incredible, Android 2.2, Software 3.21.605.1), I am experiencing the following behavior.</p>
<p>The onEditorAction event handler is being called twice (immediately) when the Enter key on the Sense UI keyboard is pressed.</p>
<p>The KeyEvent.getEventTime() is the same for both times the event is called, leading me to this work-around:</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
[...]
EditText text = (EditText)findViewById(R.id.txtBox);
text.setOnEditorActionListener(new OnEditorActionListener() {
private long lastCalled = -1;
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ( event.getEventTime() == lastCalled ) {
return false;
} else {
lastCalled = event.getEventTime();
handleNextButton(v);
return true;
}
}
});
[...]
}
</code></pre>
<p>The EditText is defined as:</p>
<pre><code><EditText
android:layout_width="150sp"
android:layout_height="wrap_content"
android:id="@+id/txtBox"
android:imeOptions="actionNext"
android:capitalize="characters"
android:singleLine="true"
android:inputType="textVisiblePassword|textCapCharacters|textNoSuggestions"
android:autoText="false"
android:editable="true"
android:maxLength="6"
/>
</code></pre>
<p>On all other devices I've tested on, the action button is properly labeled "Next" and the event is only called a single time when that button is pressed.</p>
<p>Is this a bug in Sense UI's keyboard, or am I doing something incorrectly?</p>
<p>Thank you for any assistance.</p>
<hr>
<p>Updated - thanks to the answers given, I have settled on the following as my checks. This works fine on both of the phones I have available to test (Sense UI and Cyanogenmod CM7)</p>
<pre><code> if (event != null && event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
if ( actionId != EditorInfo.IME_ACTION_NEXT && actionId != EditorInfo.IME_NULL ) {
return false;
}
</code></pre> | 4,903,973 | 6 | 2 | null | 2010-11-03 14:06:23.23 UTC | 1 | 2019-07-16 08:58:28.983 UTC | 2011-02-16 16:53:00.68 UTC | null | 293,483 | null | 293,483 | null | 1 | 33 | android | 9,691 | <p>As mitch said, you have to check the event action:</p>
<pre><code>public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event == null || event.getAction() != KeyEvent.ACTION_DOWN)
return false;
// do your stuff
return true;
}
</code></pre>
<p>This snippet works on both the Sense UI and the emulator.</p> |
4,060,405 | Is it possible to reference one CSS rule within another? | <p>For example if I have the following HTML:</p>
<pre><code><div class="someDiv"></div>
</code></pre>
<p>and this CSS:</p>
<pre><code>.opacity {
filter:alpha(opacity=60);
-moz-opacity:0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
}
.radius {
border-top-left-radius: 15px;
border-top-right-radius: 5px;
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 10px;
}
.someDiv {
background: #000; height: 50px; width: 200px;
/*** How can I reference the opacity and radius classes here
so this div has those generic rules applied to it as well ***/
}
</code></pre>
<p>Like how in scripting languages you have generic functions that are used often written at the top of the script and every time you need to use that function you simply call the function instead of repeating all the code every time.</p> | 4,060,413 | 6 | 4 | null | 2010-10-30 19:53:52.303 UTC | 12 | 2020-04-10 17:41:02.61 UTC | 2014-05-19 18:06:28.213 UTC | null | 106,224 | null | 491,928 | null | 1 | 114 | css | 176,424 | <p>No, you cannot reference one rule-set from another.</p>
<p>You can, however, reuse selectors on multiple rule-sets within a stylesheet <em>and</em> use multiple selectors on a single rule-set (by <a href="http://www.w3.org/TR/CSS21/selector.html#grouping" rel="noreferrer">separating them with a comma</a>). </p>
<pre><code>.opacity, .someDiv {
filter:alpha(opacity=60);
-moz-opacity:0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
}
.radius, .someDiv {
border-top-left-radius: 15px;
border-top-right-radius: 5px;
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 10px;
}
</code></pre>
<p>You can also apply multiple classes to a single HTML element (the class attribute takes a space separated list).</p>
<pre><code><div class="opacity radius">
</code></pre>
<p>Either of those approaches should solve your problem.</p>
<p>It would probably help if you used class names that described <em>why</em> an element should be styled instead of <em>how</em> it should be styled. Leave the <em>how</em> in the stylesheet.</p> |
4,295,681 | Evil samples of subtly broken C++ code | <p>I need some samples of bad C++ code that will illustrate violation of good practices. I wanted to come up with my own examples, but I am having a hard time coming up with examples that are <em>not contrived, and where a trap is not immediately obvious</em> (it's harder than it seems).</p>
<p>Examples would be something like:</p>
<ol>
<li>Not defining copy constructor for classes with <code>std::auto_ptr</code> members, and using <code>std::auto_ptr</code> members with forward-declared classes.</li>
<li>Calling virtual functions from a constructor or a destructor (directly or indirectly).</li>
<li>Overloading a template function.</li>
<li>Circular references with <code>boost::shared_ptr</code>.</li>
<li>Slicing.</li>
<li>Throwing exceptions from C callbacks (directly or indirectly).</li>
<li>Floating point comparison for equality.</li>
<li>Exception safety of constructors with raw pointer members.</li>
<li>Throwing from destructors.</li>
<li>Integer overflow when compiled on different architectures (mismatch of <code>size_t</code> and <code>int</code>).</li>
<li>Invalidating a container iterator.</li>
</ol>
<p>...or any other evil thing you can think of.</p>
<p>I'd appreciate some pointers to existing resources, or a sample or two.</p> | 4,295,704 | 8 | 8 | null | 2010-11-28 06:23:40.463 UTC | 23 | 2010-11-28 18:57:23.13 UTC | null | null | null | null | 23,643 | null | 1 | 40 | c++ | 11,283 | <p><a href="http://en.wikipedia.org/wiki/Most_vexing_parse" rel="noreferrer">The most vexing parse</a> is an amazingly counterintuitive result of the way C++ parses things like this:</p>
<pre><code>// Declares a function called "myVector" that returns a std::vector<float>.
std::vector<float> myVector();
// Does NOT declare an instance of std::vector<float> called "myVector"
// Declares a function called "foo" that returns a Foo and accepts an unnamed
// parameter of type Bar.
Foo foo(Bar());
// Does NOT create an instance of Foo called "foo" nor creates a Bar temporary
// Declares a function called "myVector" that takes two parameters, the first named
// "str" and the second unnamed, both of type std::istream_iterator<int>.
std::vector<float> myVector(
std::istream_iterator<int>(str),
std::istream_iterator<int>()
);
// Does NOT create an instance of `std::vector<float>` named "myVector" while copying
// in elements from a range of iterators
</code></pre>
<p>This will surprise just about anybody who is not familiar with this particular quirk of the language (myself included when I started learning C++).</p> |
4,661,557 | PIL rotate image colors (BGR -> RGB) | <p>I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?</p> | 4,661,652 | 13 | 0 | null | 2011-01-11 19:06:16.837 UTC | 22 | 2022-03-08 21:22:01.993 UTC | null | null | null | null | 15,055 | null | 1 | 71 | python|colors|python-imaging-library | 122,235 | <p>Assuming no alpha band, isn't it as simple as this?</p>
<pre><code>b, g, r = im.split()
im = Image.merge("RGB", (r, g, b))
</code></pre>
<p>Edit:</p>
<p>Hmm... It seems PIL has a few bugs in this regard... <code>im.split()</code> doesn't seem to work with recent versions of PIL (1.1.7). It may (?) still work with 1.1.6, though...</p> |
4,653,236 | Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64 | <p>I am running Visual Studio 2010 (as Admin), IIS 7 on Windows 7 x64.
I am able to run the ASP.NET web site in IIS 7 without debugging just fine, but when I press F5 to debug it, I get:</p>
<blockquote>
<p>Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging.</p>
</blockquote>
<p>Unfortunately the help link is not helping me much and leads down a heck of a large tree of things.</p>
<p>I checked the following:</p>
<ul>
<li><p>Security requirements — I don't recall having to do anything special before. The worker process in IIS7 is w3wp.exe. It says that if it's running as ASPNET or NETWORK SERVICE I must have Administrator privileges to debug it. How do I find out if I need to change something here?</p></li>
<li><p>Web site Property Pages > Start Options > Debuggers > ASP.NET is checked.
Use custom server is set to the URL of the site (which works fine without debugging).</p></li>
<li><p>Debugging is enabled in <code>web.config</code>.</p></li>
<li><p>Application is using ASP.NET 3.5 (I want to move to 4.0 eventually but I have some migration to deal with).</p></li>
<li><p>Application pool: Classing .NET AppPool (also tried DefaultAppPool).</p></li>
</ul>
<p>Any ideas where I can check next?</p>
<p>Surely it shouldn't be that hard to install IIS, VS, create a web site, and start testing it?</p>
<p>Thanks in advance.</p> | 4,685,878 | 31 | 6 | null | 2011-01-11 01:07:10.657 UTC | 32 | 2015-09-17 18:30:47.013 UTC | 2012-05-30 08:09:29.88 UTC | null | 41,956 | null | 114,472 | null | 1 | 92 | asp.net|.net|visual-studio-2010|iis-7|visual-studio-debugging | 199,030 | <p>Turns out that the culprit was the IIS <strong>Url Rewrite</strong> module. I had defined a rule that redirected calls to <strong>Default.aspx</strong> (which was set as the <strong>start page of the web site</strong>) to the root of the site so that I could have a canonical home URL. However, apparently VS had a problem with this and got confused. This problem did not happen when I was using Helicon ISAPI_Rewrite so it didn't even occur to me to check.</p>
<p>I ended up creating a whole new web site from scratch and porting projects/files over little by little into my solution and rebuilding my web.config until I found this out!
Well, at least now I have a slightly cleaner site using .NET 4.0 (so far, hopefully I won't run into any walls)--but what a pain!</p> |
14,794,556 | Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells | <p>Using Excel (2010) VBA, I am trying to copy (pass) a constant range of cells (whose values recalculate) to an array. Then I am trying to pass that array to a new range of cells, directly below it. After I have done this, I want to again copy (pass) the constant range's new values to the array, and pass these new values to a range directly below the one I previously passed.</p>
<p>I know this code is atrocious (I am new to arrays in VBA).</p>
<pre><code>Sub ARRAYER()
Dim anARRAY(5) As Variant
Number_of_Sims = 10
For i = 1 To Number_of_Sims
anARRAY = Range("C4:G4")
Range("C4").Select
ActiveCell.Offset(Number_of_Sims, 0).Select
ActiveCell = anARRAY
Range("C4").Select
Next
End Sub
</code></pre>
<p>I sure do appreciate your help!</p>
<p>Thank you.</p>
<p>Respectfully,</p>
<p>Jonathan </p> | 14,794,645 | 4 | 2 | null | 2013-02-10 03:58:29.99 UTC | 3 | 2017-07-22 22:03:33.373 UTC | null | null | null | null | 1,352,561 | null | 1 | 10 | arrays|excel|vba | 107,080 | <p>You are off slightly on a few things here, so hopefully the following helps.</p>
<p>Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.</p>
<p>It's also good practice to use <code>Option Explicit</code> at the top of your modules to force variable declaration.</p>
<p>The following will do what you are after:</p>
<pre><code>Sub ARRAYER()
Dim Number_of_Sims As Integer, i As Integer
Number_of_Sims = 10
For i = 1 To Number_of_Sims
'Do your calculation here to update C4 to G4
Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
Next
End Sub
</code></pre>
<p>If you do want to manipulate the values within the array then do this:</p>
<pre><code>Sub ARRAYER()
Dim Number_of_Sims As Integer, i As Integer
Dim anARRAY as Variant
Number_of_Sims = 10
For i = 1 To Number_of_Sims
'Do your calculation here to update C4 to G4
anARRAY= Range("C4:G4").Value
'You can loop through the array and manipulate it here
Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
Next
End Sub
</code></pre> |
14,539,992 | Pandas Drop Rows Outside of Time Range | <p>I am trying to go through every row in a DataFrame index and remove all rows that are not between a certain time.</p>
<p>I have been looking for solutions but none of them separate the Date from the Time, and all I want to do is drop the rows that are outside of a Time range.</p> | 14,540,509 | 3 | 0 | null | 2013-01-26 18:15:35.187 UTC | 8 | 2021-03-11 13:19:31.977 UTC | null | null | null | null | 546,624 | null | 1 | 18 | python|pandas | 20,013 | <p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="noreferrer"><code>between_time</code></a> function directly:</p>
<pre><code>ts.between_time(datetime.time(18), datetime.time(9), include_start=False, include_end=False)
</code></pre>
<hr>
<p><em>Original answer:</em></p>
<p>You can use the <code>indexer_between_time</code> <code>Index</code> method.</p>
<p>For example, to <em>include</em> those times between 9am and 6pm (<em>inclusive</em>):</p>
<pre><code>ts.ix[ts.index.indexer_between_time(datetime.time(9), datetime.time(18))]
</code></pre>
<p>to do the opposite and <em>exclude</em> those times between 6pm and 9am (<em>exclusive</em>):</p>
<pre><code>ts.ix[ts.index.indexer_between_time(datetime.time(18), datetime.time(9),
include_start=False, include_end=False)]
</code></pre>
<p><em>Note: <code>indexer_between_time</code>'s arguments <code>include_start</code> and <code>include_end</code> are by default <code>True</code>, setting <code>include_start</code> to <code>False</code> means that datetimes whose time-part is precisely <code>start_time</code> (the first argument), in this case 6pm, will not be included.</em></p>
<p>Example:</p>
<pre><code>In [1]: rng = pd.date_range('1/1/2000', periods=24, freq='H')
In [2]: ts = pd.Series(pd.np.random.randn(len(rng)), index=rng)
In [3]: ts.ix[ts.index.indexer_between_time(datetime.time(10), datetime.time(14))]
Out[3]:
2000-01-01 10:00:00 1.312561
2000-01-01 11:00:00 -1.308502
2000-01-01 12:00:00 -0.515339
2000-01-01 13:00:00 1.536540
2000-01-01 14:00:00 0.108617
</code></pre>
<p>Note: the same syntax (using <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#advanced-indexing-with-labels" rel="noreferrer"><code>ix</code></a>) works for a DataFrame:</p>
<pre><code>In [4]: df = pd.DataFrame(ts)
In [5]: df.ix[df.index.indexer_between_time(datetime.time(10), datetime.time(14))]
Out[5]:
0
2000-01-03 10:00:00 1.312561
2000-01-03 11:00:00 -1.308502
2000-01-03 12:00:00 -0.515339
2000-01-03 13:00:00 1.536540
2000-01-03 14:00:00 0.108617
</code></pre> |
14,642,985 | Type safety: Unchecked cast from Object to List<MyObject> | <p>I have a ListView listing a custom object (let's say <code>MyObject</code>).</p>
<p>I want to filter it dynamically through an <code>EditText</code> so I had to implement a <code>getFilter()</code> with a publishResults method: </p>
<pre><code>@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
MyObjectAdapter.this.setItems((List<MyObject>) results.values);
MyObjectAdapter.this.notifyDataSetChanged();
}
</code></pre>
<p>At this point, Eclipse complains: <code>Type safety: Unchecked cast from Object to List<MyObject></code></p>
<p>I am sure this cast will always be true, but Eclipse only suggests to add <code>@SuppressWarnings("unchecked")</code> but I'm totally against <code>SuppressWarnings</code> because it's only hiding the problem, not a solution...</p>
<p>I tried adding:</p>
<pre><code>if(results.values instanceof List<MyObject>)
</code></pre>
<p>But Eclipse complains again, and this solves nothing...</p>
<p><code>Cannot perform instanceof check against parameterized type List<MyObject>. Use the form List<?></code></p>
<p>I know the casting will always be correct, but which is the proper way to make the code to be sure <code>results.values</code> is actually a <code>List<MyObject></code> ?</p>
<p>Thanks in advance!</p> | 14,645,590 | 4 | 1 | null | 2013-02-01 09:16:12 UTC | 4 | 2016-03-24 01:19:36.76 UTC | 2015-12-15 01:31:31.803 UTC | null | 51,683 | null | 1,178,445 | null | 1 | 26 | android|listview|casting|filter|custom-object | 55,175 | <p>Well, I finally managed to find a solution.</p>
<p>Just as @Medo42 said:</p>
<blockquote>
<p>Another option is to check for and cast to List as the instanceof
error suggests. Then you can iterate over the elements in the list and
check if they are actually all instances of MyObject, and copy them to
a new List.</p>
</blockquote>
<p>Even though I did not went through the process of creating a whole new object in order to make this particular case to work "warning-less" this was the right direction to go.</p>
<p>So I took @lokoko 's idea and use it in a new <code>setItems()</code> method, with an <code>Object</code> parameter instead of a <code>List<MyObject></code> in order to make sure</p>
<p>The result code is the following:</p>
<pre><code>public void setItems(List<MyObject> var){
this.list = var;
}
public void setItems(Object var){
List<MyObject> result = new ArrayList<MyObject>();
if (var instanceof List){
for(int i = 0; i < ((List<?>)var).size(); i++){
Object item = ((List<?>) var).get(i);
if(item instanceof MyObject){
result.add((MyObject) item);
}
}
}
setItems(result);
}
</code></pre>
<p>Thanks everyone for your help!</p> |
14,760,496 | UICollectionView automatically scroll to bottom when screen loads | <p>I'm trying to figure out how to scroll all the way to the bottom of a UICollectionView when the screen first loads. I'm able to scroll to the bottom when the status bar is touched, but I'd like to be able to do that automatically when the view loads as well. The below works fine if I want to scroll to the bottom when the status bar is touched.</p>
<pre><code>- (BOOL)scrollViewShouldScrollToTop:(UITableView *)tableView
{
NSLog(@"Detect status bar is touched.");
[self scrollToBottom];
return NO;
}
-(void)scrollToBottom
{//Scrolls to bottom of scroller
CGPoint bottomOffset = CGPointMake(0, collectionViewReload.contentSize.height - collectionViewReload.bounds.size.height);
[collectionViewReload setContentOffset:bottomOffset animated:NO];
}
</code></pre>
<p>I've tried calling [self scrollToBottom] in the viewDidLoad. This isn't working. Any ideas on how I can scroll to the bottom when the view loads?</p> | 14,763,881 | 9 | 2 | null | 2013-02-07 20:35:06.67 UTC | 5 | 2021-01-14 22:24:23.287 UTC | 2013-02-10 01:26:26.48 UTC | null | 1,429,262 | null | 1,253,907 | null | 1 | 34 | ios|objective-c|uiscrollview|uicollectionview | 39,287 | <p>Just to elaborate on my comment.</p>
<p>viewDidLoad is called before elements are visual so certain UI elements cannot be manipulated very well. Things like moving buttons around work but dealing with subviews often does not (like scrolling a CollectionView).</p>
<p>Most of these actions will work best when called in viewWillAppear or viewDidAppear. Here is an except from the Apple docs that points out an important thing to do when overriding either of these methods:</p>
<blockquote>
<p>You can override this method to perform additional tasks associated
with presenting the view. <strong>If you override this method, you must call
super at some point in your implementation.</strong></p>
</blockquote>
<p>The super call is generally called before custom implementations. (so the first line of code inside of the overridden methods).</p> |
14,386,994 | Chrome >=24 - how to dock devtools to the right? | <p>I like docking devtools to the right. I remember how happy I was when I first saw that option when I realized I no longer have to split screen and position windows manually.</p>
<p>Recent versions of chrome that option seems to be missing. Even on my installs where I already have devtools on the right the option is removed.</p>
<p>Where did it go?</p> | 14,387,041 | 1 | 3 | null | 2013-01-17 19:52:14.607 UTC | 15 | 2015-10-22 04:39:45.087 UTC | null | null | null | null | 5,056 | null | 1 | 112 | google-chrome-devtools | 22,502 | <p>If you click and hold on the icon in the top right next to the close icon (Undock into separate window button), you are given the option to dock it to the right. See screenshot:</p>
<p><img src="https://i.imgur.com/fM5wwzU.png" alt="Dock to right"></p>
<p>Starting in Chrome 41, you are able to use <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>D</kbd> (Windows/Linux) or <kbd>Command (⌘)</kbd> + <kbd>Shift</kbd> + <kbd>D</kbd> (Mac OS X) to be able to toggle between these views.</p>
<p>Starting in Chrome 46, they've finally changed the user interface for the docking location. There's a vertical ellipsis now and in there it has explicit buttons for each docking location. See screenshot:</p>
<p><img src="https://i.imgur.com/Q6rSGgD.png" alt="New Docking"></p> |
14,846,920 | Collections.emptyMap() vs new HashMap() | <p>What are some of the situations where I can use <code>Collections.emptyMap()</code> ? The Documentation says I can use this method if I want my collection to be immutable. </p>
<p><strong>Why would I want an immutable empty collection? What is the point?</strong></p> | 14,846,960 | 9 | 4 | null | 2013-02-13 05:23:59.663 UTC | 26 | 2015-06-15 10:49:43.813 UTC | 2013-02-14 04:43:05.33 UTC | null | 942,391 | null | 571,718 | null | 1 | 156 | java|collections | 59,421 | <p>From <strong>Effective Java</strong>, <strong>Item #43</strong> - <code>"Return empty arrays or collections, not null"</code> demonstrates returning an empty collection and perhaps even demonstrates using these <code>emptyList()</code>, <code>emptySet()</code>, and <code>emptyMap()</code> methods on the Collections class to get an empty collection that also has the additional benefit of being immutable. From <strong>Item #15</strong> <code>"Minimize Mutability"</code>.</p>
<p>From <a href="http://www.coderanch.com/t/536728/java/java/Collections-emptySet-Collections-emptyList-Collections" rel="noreferrer">Collections-emptySet-Collections-emptyList-Collections</a> </p>
<blockquote>
<p>Its a type of programming idiom. This is for people that do not want null variables. So before the set gets initialized, they can use the empty set. </p>
</blockquote>
<p><strong>Note:</strong> Below code is just an example (change it according to your use case): </p>
<pre><code>private Set myset = Collections.emptySet();
void initSet() {
myset = new HashSet();
}
void deleteSet() {
myset = Collections.emptySet();
}
</code></pre>
<p>These methods offer a couple of advantages:</p>
<ol>
<li><p>They're more concise because you don't need to explicitly type out the generic type of the collection - it's generally just inferred from the context of the method call. </p></li>
<li><p>They're more efficient because they don't bother creating new objects; they just re-use an existing empty and immutable object. This effect is generally very minor, but it's occasionally (well, rarely) important.</p></li>
</ol> |
45,615,621 | Spark column string replace when present in other column (row) | <p>I would like to remove strings from <code>col1</code> that are present in <code>col2</code>:</p>
<pre><code>val df = spark.createDataFrame(Seq(
("Hi I heard about Spark", "Spark"),
("I wish Java could use case classes", "Java"),
("Logistic regression models are neat", "models")
)).toDF("sentence", "label")
</code></pre>
<p>using <code>regexp_replace</code> or <code>translate</code> ref: <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$" rel="noreferrer">spark functions api</a></p>
<pre><code>val res = df.withColumn("sentence_without_label", regexp_replace
(col("sentence") , "(?????)", "" ))
</code></pre>
<p>so that <code>res</code> looks as below:</p>
<p><a href="https://i.stack.imgur.com/GDKET.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GDKET.png" alt="enter image description here"></a></p> | 45,615,779 | 2 | 0 | null | 2017-08-10 13:48:44.98 UTC | 2 | 2018-04-23 11:41:39.51 UTC | null | null | null | null | 4,666,785 | null | 1 | 13 | scala|apache-spark|user-defined-functions | 50,039 | <p>You could simply use <code>regexp_replace</code></p>
<pre><code>df5.withColumn("sentence_without_label", regexp_replace($"sentence" , lit($"label"), lit("" )))
</code></pre>
<p>or you can use simple udf function as below </p>
<pre><code>val df5 = spark.createDataFrame(Seq(
("Hi I heard about Spark", "Spark"),
("I wish Java could use case classes", "Java"),
("Logistic regression models are neat", "models")
)).toDF("sentence", "label")
val replace = udf((data: String , rep : String)=>data.replaceAll(rep, ""))
val res = df5.withColumn("sentence_without_label", replace($"sentence" , $"label"))
res.show()
</code></pre>
<p>Output: </p>
<pre><code>+-----------------------------------+------+------------------------------+
|sentence |label |sentence_without_label |
+-----------------------------------+------+------------------------------+
|Hi I heard about Spark |Spark |Hi I heard about |
|I wish Java could use case classes |Java |I wish could use case classes|
|Logistic regression models are neat|models|Logistic regression are neat |
+-----------------------------------+------+------------------------------+
</code></pre> |
2,743,866 | Scala return type for tuple-functions | <p>I want to make a scala function which returns a scala tuple.</p>
<p>I can do a function like this:</p>
<pre><code>def foo = (1,"hello","world")
</code></pre>
<p>and this will work fine, but now I want to tell the compiler what I expect to be returned from the function instead of using the built in type inference (after all, I have no idea what a <code>(1,"hello","world")</code> is).</p> | 2,744,040 | 2 | 2 | null | 2010-04-30 10:38:01.89 UTC | 6 | 2017-03-24 19:11:24.437 UTC | 2013-08-06 20:39:29.59 UTC | user212218 | null | null | 238,100 | null | 1 | 43 | function|scala|types|return|tuples | 45,925 | <pre><code>def foo : (Int, String, String) = (1, "Hello", "World")
</code></pre>
<p>The compiler will interpret the type <code>(Int, String, String)</code> as a <code>Tuple3[Int, String, String]</code></p> |
1,921,627 | Multiple insert/update statements inside trigger? | <p>Just a quick question that no doubt someone out there will know the answer to.</p>
<p>I need to be able to do multiple insert/updates within a trigger. Every attempt ends with failure :(</p>
<pre><code>DROP TRIGGER IF EXISTS `Insert_Article`//
CREATE TRIGGER `Insert_Article` AFTER INSERT ON `Article`
FOR EACH ROW insert into FullTextStore (`Table`, `PrimaryKey`, `ColumnName`, `Data`, `Created`) values ('Article', NEW.ArticleID, 'Description', NEW.Description, UNIX_TIMESTAMP())
//
</code></pre>
<p>At the moment, the above simply inserts a row into a table when the parent table inserts. This works fine.</p>
<p>To get this to work with mulitple values I need to do </p>
<pre><code>DROP TRIGGER IF EXISTS `Insert_Article`//
CREATE TRIGGER `Insert_Article` AFTER INSERT ON `Article`
FOR EACH ROW insert into FullTextStore (`Table`, `PrimaryKey`, `ColumnName`, `Data`, `Created`)
select 'Article', NEW.ArticleID, 'Description', NEW.Description, UNIX_TIMESTAMP()
union
select 'Article', NEW.ArticleID, 'Keywords', NEW.Keywords, UNIX_TIMESTAMP()
//
</code></pre>
<p>But... There must be an easier way? When I try using ; to terminate each statement, it fails with </p>
<pre><code>1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL version for the right syntax to use near 'select 'Article', NEW.ArticleID, 'Keywords', 'NEW.Keywords, UNIX_TIMESTAMP())' at line 1
</code></pre>
<p>I can't even get multiple update statements to work.</p>
<p>It'd be a great help if anyone could point out what i'm doing wrong?</p>
<p>Cheers</p>
<p>Gavin</p> | 1,921,657 | 1 | 0 | null | 2009-12-17 13:00:02.767 UTC | 8 | 2009-12-17 13:03:51.927 UTC | null | null | null | null | 55,859 | null | 1 | 24 | mysql|database|triggers | 41,381 | <p>From the docs: <a href="http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html" rel="noreferrer">Create Trigger Syntax</a></p>
<blockquote>
<p>trigger_stmt is the statement to
execute when the trigger activates. If
you want to execute multiple
statements, use the BEGIN ... END
compound statement construct. This
also enables you to use the same
statements that are allowable within
stored routines</p>
</blockquote>
<pre><code>CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
</code></pre> |
21,813,122 | Changing content of class using Javascript | <p>I started reading JavaScript in W3schools and testing out/changing few things in the examples they give so I can see what is doing what but didn't manage to identify the syntax, yet.</p>
<p>Below is the original code to change p tag content, <em>the <a href="http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html" rel="nofollow noreferrer">link</a> to it.</em></p>
<pre><code><p id="demo">
JavaScript can change the content of an HTML element.
</p>
<script>
function myFunction()
{
x = document.getElementById("demo"); // Find the element
x.innerHTML = "Hello JavaScript!"; // Change the content
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</code></pre>
<p>I want to know how to change contents with the same class, but failed as you can see that the example below doesn't work. <a href="http://jsfiddle.net/37jq9/" rel="nofollow noreferrer">Fiddle of code below</a>.</p>
<pre><code><p class="demo">
JavaScript can change the content of an HTML element.
</p>
<p class="demo">Yolo</p>
<script>
function myFunction()
{
x = document.getElementsByClassName("demo"); // Find the element
x.innerHTML = "Hello JavaScript!"; // Change the content
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</code></pre>
<p>If you could show me how ^^" and help me understand, is "getElementById" a variable that could be anything else or is it a command?</p> | 21,813,274 | 3 | 0 | null | 2014-02-16 15:23:12.22 UTC | 2 | 2019-01-31 07:16:13.947 UTC | 2019-01-31 07:16:13.947 UTC | null | 7,473,844 | null | 3,104,214 | null | 1 | 13 | javascript|html|onclick|tags | 54,626 | <p>Your x - is array of elements. try to use loop:</p>
<pre><code><body>
<p class="demo">JavaScript can change the content of an HTML element.</p>
<p class="demo">Yolo</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<script>
function myFunction()
{
x=document.getElementsByClassName("demo"); // Find the elements
for(var i = 0; i < x.length; i++){
x[i].innerText="Hello JavaScript!"; // Change the content
}
}
</script>
</body>
</code></pre>
<p>See <a href="http://jsfiddle.net/37jq9/7/" rel="noreferrer">FIDDLE</a></p> |
26,777,083 | How to implement REST token-based authentication with JAX-RS and Jersey | <p>I'm looking for a way to enable token-based authentication in Jersey. I am trying not to use any particular framework. Is that possible?</p>
<p>My plan is: A user signs up for my web service, my web service generates a token, sends it to the client, and the client will retain it. Then the client, for each request, will send the token instead of username and password.</p>
<p>I was thinking of using a custom filter for each request and <code>@PreAuthorize("hasRole('ROLE')")</code>, but I just thought that this causes a lot of requests to the database to check if the token is valid.</p>
<p>Or not create filter and in each request put a param token? So that each API first checks the token and after executes something to retrieve resource.</p> | 26,778,123 | 2 | 0 | null | 2014-11-06 10:26:27.133 UTC | 574 | 2021-09-22 20:57:49.053 UTC | 2021-09-22 20:57:49.053 UTC | null | 2,756,409 | null | 4,120,466 | null | 1 | 503 | java|rest|authentication|jax-rs|jersey-2.0 | 393,793 | <h2>How token-based authentication works</h2>
<p>In token-based authentication, the client exchanges <em>hard credentials</em> (such as username and password) for a piece of data called <em>token</em>. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.</p>
<p>In a few words, an authentication scheme based on tokens follow these steps:</p>
<ol>
<li>The client sends their credentials (username and password) to the server.</li>
<li>The server authenticates the credentials and, if they are valid, generate a token for the user.</li>
<li>The server stores the previously generated token in some storage along with the user identifier and an expiration date.</li>
<li>The server sends the generated token to the client.</li>
<li>The client sends the token to the server in each request.</li>
<li>The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
<ul>
<li>If the token is valid, the server accepts the request.</li>
<li>If the token is invalid, the server refuses the request.</li>
</ul>
</li>
<li>Once the authentication has been performed, the server performs authorization.</li>
<li>The server can provide an endpoint to refresh tokens.</li>
</ol>
<h2>What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)</h2>
<p>This solution uses only the JAX-RS 2.0 API, <em>avoiding any vendor specific solution</em>. So, it should work with JAX-RS 2.0 implementations, such as <a href="https://jersey.github.io/" rel="noreferrer">Jersey</a>, <a href="http://resteasy.jboss.org/" rel="noreferrer">RESTEasy</a> and <a href="https://cxf.apache.org/" rel="noreferrer">Apache CXF</a>.</p>
<p>It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's <code>web.xml</code> descriptor. It's a custom authentication.</p>
<h3>Authenticating a user with their username and password and issuing a token</h3>
<p>Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:</p>
<pre class="lang-java prettyprint-override"><code>@Path("/authentication")
public class AuthenticationEndpoint {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
authenticate(username, password);
// Issue a token for the user
String token = issueToken(username);
// Return the token on the response
return Response.ok(token).build();
} catch (Exception e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
private void authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
}
private String issueToken(String username) {
// Issue a token (can be a random String persisted to a database or a JWT token)
// The issued token must be associated to a user
// Return the issued token
}
}
</code></pre>
<p>If any exceptions are thrown when validating the credentials, a response with the status <code>403</code> (Forbidden) will be returned.</p>
<p>If the credentials are successfully validated, a response with the status <code>200</code> (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.</p>
<p>When consuming <code>application/x-www-form-urlencoded</code>, the client must send the credentials in the following format in the request payload:</p>
<pre class="lang-none prettyprint-override"><code>username=admin&password=123456
</code></pre>
<p>Instead of form params, it's possible to wrap the username and the password into a class:</p>
<pre class="lang-java prettyprint-override"><code>public class Credentials implements Serializable {
private String username;
private String password;
// Getters and setters omitted
}
</code></pre>
<p>And then consume it as JSON:</p>
<pre class="lang-java prettyprint-override"><code>@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {
String username = credentials.getUsername();
String password = credentials.getPassword();
// Authenticate the user, issue a token and return a response
}
</code></pre>
<p>Using this approach, the client must to send the credentials in the following format in the payload of the request:</p>
<pre class="lang-json prettyprint-override"><code>{
"username": "admin",
"password": "123456"
}
</code></pre>
<h3>Extracting the token from the request and validating it</h3>
<p>The client should send the token in the standard HTTP <code>Authorization</code> header of the request. For example:</p>
<pre class="lang-none prettyprint-override"><code>Authorization: Bearer <token-goes-here>
</code></pre>
<p>The name of the standard HTTP header is unfortunate because it carries <em>authentication</em> information, not <em>authorization</em>. However, it's the standard HTTP header for sending credentials to the server.</p>
<p>JAX-RS provides <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/NameBinding.html" rel="noreferrer"><code>@NameBinding</code></a>, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a <code>@Secured</code> annotation as following:</p>
<pre class="lang-java prettyprint-override"><code>@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }
</code></pre>
<p>The above defined name-binding annotation will be used to decorate a filter class, which implements <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/container/ContainerRequestFilter.html" rel="noreferrer"><code>ContainerRequestFilter</code></a>, allowing you to intercept the request before it be handled by a resource method. The <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/container/ContainerRequestContext.html" rel="noreferrer"><code>ContainerRequestContext</code></a> can be used to access the HTTP request headers and then extract the token:</p>
<pre class="lang-java prettyprint-override"><code>@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private static final String REALM = "example";
private static final String AUTHENTICATION_SCHEME = "Bearer";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
return;
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
validateToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
private boolean isTokenBasedAuthentication(String authorizationHeader) {
// Check if the Authorization header is valid
// It must not be null and must be prefixed with "Bearer" plus a whitespace
// The authentication scheme comparison must be case-insensitive
return authorizationHeader != null && authorizationHeader.toLowerCase()
.startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
}
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
// Abort the filter chain with a 401 status code response
// The WWW-Authenticate header is sent along with the response
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
.build());
}
private void validateToken(String token) throws Exception {
// Check if the token was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}
}
</code></pre>
<p>If any problems happen during the token validation, a response with the status <code>401</code> (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.</p>
<h3>Securing your REST endpoints</h3>
<p>To bind the authentication filter to resource methods or resource classes, annotate them with the <code>@Secured</code> annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will <em>only</em> be reached if the request is performed with a valid token.</p>
<p>If some methods or classes do not need authentication, simply do not annotate them:</p>
<pre class="lang-java prettyprint-override"><code>@Path("/example")
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myUnsecuredMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// The authentication filter won't be executed before invoking this method
...
}
@DELETE
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response mySecuredMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured
// The authentication filter will be executed before invoking this method
// The HTTP request must be performed with a valid token
...
}
}
</code></pre>
<p>In the example shown above, the filter will be executed <em>only</em> for the <code>mySecuredMethod(Long)</code> method because it's annotated with <code>@Secured</code>.</p>
<h2>Identifying the current user</h2>
<p>It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:</p>
<h3>Overriding the security context of the current request</h3>
<p>Within your <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/container/ContainerRequestFilter.html#filter-javax.ws.rs.container.ContainerRequestContext-" rel="noreferrer"><code>ContainerRequestFilter.filter(ContainerRequestContext)</code></a> method, a new <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/SecurityContext.html" rel="noreferrer"><code>SecurityContext</code></a> instance can be set for the current request. Then override the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/SecurityContext.html#getUserPrincipal--" rel="noreferrer"><code>SecurityContext.getUserPrincipal()</code></a>, returning a <a href="http://docs.oracle.com/javase/10/docs/api/java/security/Principal.html" rel="noreferrer"><code>Principal</code></a> instance:</p>
<pre class="lang-java prettyprint-override"><code>final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return () -> username;
}
@Override
public boolean isUserInRole(String role) {
return true;
}
@Override
public boolean isSecure() {
return currentSecurityContext.isSecure();
}
@Override
public String getAuthenticationScheme() {
return AUTHENTICATION_SCHEME;
}
});
</code></pre>
<p>Use the token to look up the user identifier (username), which will be the <a href="http://docs.oracle.com/javase/10/docs/api/java/security/Principal.html" rel="noreferrer"><code>Principal</code></a>'s name.</p>
<p>Inject the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/SecurityContext.html" rel="noreferrer"><code>SecurityContext</code></a> in any JAX-RS resource class:</p>
<pre class="lang-java prettyprint-override"><code>@Context
SecurityContext securityContext;
</code></pre>
<p>The same can be done in a JAX-RS resource method:</p>
<pre class="lang-java prettyprint-override"><code>@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id,
@Context SecurityContext securityContext) {
...
}
</code></pre>
<p>And then get the <a href="http://docs.oracle.com/javase/10/docs/api/java/security/Principal.html" rel="noreferrer"><code>Principal</code></a>:</p>
<pre class="lang-java prettyprint-override"><code>Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();
</code></pre>
<h3>Using CDI (Context and Dependency Injection)</h3>
<p>If, for some reason, you don't want to override the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/SecurityContext.html" rel="noreferrer"><code>SecurityContext</code></a>, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.</p>
<p>Create a CDI qualifier:</p>
<pre class="lang-java prettyprint-override"><code>@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }
</code></pre>
<p>In your <code>AuthenticationFilter</code> created above, inject an <a href="https://docs.oracle.com/javaee/10/api/javax/enterprise/event/Event.html" rel="noreferrer"><code>Event</code></a> annotated with <code>@AuthenticatedUser</code>:</p>
<pre class="lang-java prettyprint-override"><code>@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;
</code></pre>
<p>If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):</p>
<pre class="lang-java prettyprint-override"><code>userAuthenticatedEvent.fire(username);
</code></pre>
<p>It's very likely that there's a class that represents a user in your application. Let's call this class <code>User</code>.</p>
<p>Create a CDI bean to handle the authentication event, find a <code>User</code> instance with the correspondent username and assign it to the <code>authenticatedUser</code> producer field:</p>
<pre class="lang-java prettyprint-override"><code>@RequestScoped
public class AuthenticatedUserProducer {
@Produces
@RequestScoped
@AuthenticatedUser
private User authenticatedUser;
public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
this.authenticatedUser = findUser(username);
}
private User findUser(String username) {
// Hit the the database or a service to find a user by its username and return it
// Return the User instance
}
}
</code></pre>
<p>The <code>authenticatedUser</code> field produces a <code>User</code> instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a <code>User</code> instance (in fact, it's a CDI proxy):</p>
<pre class="lang-java prettyprint-override"><code>@Inject
@AuthenticatedUser
User authenticatedUser;
</code></pre>
<p>Note that the CDI <a href="https://javaee.github.io/javaee-spec/javadocs/javax/enterprise/inject/Produces.html" rel="noreferrer"><code>@Produces</code></a> annotation is <em>different</em> from the JAX-RS <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/Produces.html" rel="noreferrer"><code>@Produces</code></a> annotation:</p>
<ul>
<li>CDI: <a href="https://javaee.github.io/javaee-spec/javadocs/javax/enterprise/inject/Produces.html" rel="noreferrer"><code>javax.enterprise.inject.Produces</code></a></li>
<li>JAX-RS: <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/Produces.html" rel="noreferrer"><code>javax.ws.rs.Produces</code></a></li>
</ul>
<p>Be sure you use the CDI <a href="https://javaee.github.io/javaee-spec/javadocs/javax/enterprise/inject/Produces.html" rel="noreferrer"><code>@Produces</code></a> annotation in your <code>AuthenticatedUserProducer</code> bean.</p>
<p>The key here is the bean annotated with <a href="https://javaee.github.io/javaee-spec/javadocs/javax/enterprise/context/RequestScoped.html" rel="noreferrer"><code>@RequestScoped</code></a>, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.</p>
<p>Compared to the approach that overrides the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/SecurityContext.html" rel="noreferrer"><code>SecurityContext</code></a>, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.</p>
<h2>Supporting role-based authorization</h2>
<p>Please refer to my other <a href="https://stackoverflow.com/a/45814178/1426227">answer</a> for details on how to support role-based authorization.</p>
<h2>Issuing tokens</h2>
<p>A token can be:</p>
<ul>
<li><strong>Opaque:</strong> Reveals no details other than the value itself (like a random string)</li>
<li><strong>Self-contained:</strong> Contains details about the token itself (like JWT).</li>
</ul>
<p>See details below:</p>
<h3>Random string as token</h3>
<p>A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen <a href="https://stackoverflow.com/a/41156/1426227">here</a>. You also could use:</p>
<pre class="lang-java prettyprint-override"><code>Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
</code></pre>
<h3>JWT (JSON Web Token)</h3>
<p>JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the <a href="https://www.rfc-editor.org/rfc/rfc7519" rel="noreferrer">RFC 7519</a>.</p>
<p>It's a self-contained token and it enables you to store details in <em>claims</em>. These claims are stored in the token payload which is a JSON encoded as <a href="https://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a>. Here are some claims registered in the <a href="https://www.rfc-editor.org/rfc/rfc7519" rel="noreferrer">RFC 7519</a> and what they mean (read the full RFC for further details):</p>
<ul>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1" rel="noreferrer"><code>iss</code></a>: Principal that issued the token.</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2" rel="noreferrer"><code>sub</code></a>: Principal that is the subject of the JWT.</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4" rel="noreferrer"><code>exp</code></a>: Expiration date for the token.</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5" rel="noreferrer"><code>nbf</code></a>: Time on which the token will start to be accepted for processing.</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6" rel="noreferrer"><code>iat</code></a>: Time on which the token was issued.</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7" rel="noreferrer"><code>jti</code></a>: Unique identifier for the token.</li>
</ul>
<p>Be aware that you must not store sensitive data, such as passwords, in the token.</p>
<p>The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.</p>
<p>You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (<a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7" rel="noreferrer"><code>jti</code></a> claim) along with some other details such as the user you issued the token for, the expiration date, etc.</p>
<p>When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.</p>
<h2>Using JWT</h2>
<p>There are a few Java libraries to issue and validate JWT tokens such as:</p>
<ul>
<li><a href="https://github.com/jwtk/jjwt" rel="noreferrer">jjwt</a></li>
<li><a href="https://github.com/auth0/java-jwt" rel="noreferrer">java-jwt</a></li>
<li><a href="https://bitbucket.org/b_c/jose4j/wiki/Home" rel="noreferrer">jose4j</a></li>
</ul>
<p>To find some other great resources to work with JWT, have a look at <a href="http://jwt.io/" rel="noreferrer">http://jwt.io</a>.</p>
<h3>Handling token revocation with JWT</h3>
<p>If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use <a href="https://www.rfc-editor.org/rfc/rfc4122" rel="noreferrer">UUID</a>.</p>
<p>The <a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7" rel="noreferrer"><code>jti</code></a> claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the <a href="https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7" rel="noreferrer"><code>jti</code></a> claim against the token identifiers you have on server side.</p>
<p>For security purposes, revoke all the tokens for a user when they change their password.</p>
<h2>Additional information</h2>
<ul>
<li>It doesn't matter which type of authentication you decide to use. <strong>Always</strong> do it on the top of a HTTPS connection to prevent the <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack" rel="noreferrer">man-in-the-middle attack</a>.</li>
<li>Take a look at <a href="https://security.stackexchange.com/q/19676">this question</a> from Information Security for more information about tokens.</li>
<li><a href="https://stormpath.com/blog/token-auth-spa/" rel="noreferrer">In this article</a> you will find some useful information about token-based authentication.</li>
</ul> |
38,610,723 | How to insert a pandas dataframe to an already existing table in a database? | <p>I'm using <code>sqlalchemy</code> in pandas to query postgres database and then insert results of a transformation to another table on the same database. But when I do
<code>df.to_sql('db_table2', engine)</code> I get this error message:
<code>ValueError: Table 'db_table2' already exists.</code> I noticed it want to create a new table. How to insert pandas dataframe to an already existing table ? </p>
<pre><code>df = pd.read_sql_query('select * from "db_table1"',con=engine)
#do transformation then save df to db_table2
df.to_sql('db_table2', engine)
ValueError: Table 'db_table2' already exists
</code></pre> | 38,610,751 | 2 | 0 | null | 2016-07-27 10:43:23.417 UTC | 17 | 2019-12-24 08:33:28.193 UTC | 2018-01-22 21:51:18.19 UTC | null | 395,857 | null | 1,102,806 | null | 1 | 52 | python|database|pandas|dataframe | 115,030 | <p>make use of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="noreferrer">if_exists</a> parameter:</p>
<pre><code>df.to_sql('db_table2', engine, if_exists='replace')
</code></pre>
<p>or</p>
<pre><code>df.to_sql('db_table2', engine, if_exists='append')
</code></pre>
<p>from docstring:</p>
<pre><code>"""
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
"""
</code></pre> |
40,391,717 | react-native-keyboard-aware-scroll-view not working properly | <p>I am trying to use the react-native-keyboard-aware-scroll-view so the keyboard doesn't cover my inputs. </p>
<p>For some reason it always thinks there is a keyboard active I guess because it always compresses everything.</p>
<p>Attached is a picture of what is happening as well as the code. Any chance anyone has any idea whats happening here? I've been playing around with it for awhile and have had no luck. I'm running react-native v 0.33 and react-native-keyboard-aware-scroll-view v 0.2.1. </p>
<p><a href="https://www.npmjs.com/package/react-native-keyboard-aware-scroll-view" rel="noreferrer">https://www.npmjs.com/package/react-native-keyboard-aware-scroll-view</a></p>
<p><a href="https://i.stack.imgur.com/EdTel.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EdTel.png" alt="enter image description here"></a></p>
<pre><code>import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
class LoginIOS extends Component{
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.renderScene = this.renderScene.bind(this);
this.state={
username: '',
password: ''
};
}
render() {
return (
<Navigator
renderScene={this.renderScene}
navigator={this.props.navigator}
navigationBar={
<Navigator.NavigationBar style={{backgroundColor: 'transparent'}}
routeMapper={NavigationBarRouteMapper} />
} />
);
}
renderScene() {
return (
<KeyboardAwareScrollView>
<View style={styles.container}>
<Spinner visible={this.state.visible} />
<StatusBar barStyle="light-content" hidden={true}/>
<View style={styles.topContainer}>
<View style={styles.bannerContainer}>
<View style={{flexDirection: 'column', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Image style={styles.mark} source={require('***')} />
</View>
</View>
<View style={styles.credentialContainer}>
<View style={styles.inputContainer}>
<Icon style={styles.inputPassword} name="person" size={28} color="#FFCD00" />
<View style={{flexDirection: 'row', flex: 1, marginLeft: 2, marginRight: 2, borderBottomColor: '#e0e0e0', borderBottomWidth: 2}}>
<TextInput
style={styles.input}
placeholder="Username"
autoCorrect={false}
autoCapitalize="none"
returnKeyType="next"
placeholderTextColor="#e0e0e0"
onChangeText={(text) => this.setState({username: text})}
value={this.state.username}
>
</TextInput>
</View>
</View>
<View style={styles.inputContainer}>
<Icon style={styles.inputPassword} name="lock" size={28} color="#FFCD00" />
<View style={{flexDirection: 'row', flex: 1, marginLeft: 2, marginRight: 2, borderBottomColor: '#e0e0e0', borderBottomWidth: 2}}>
<TextInput
style={styles.input}
placeholder="Password"
returnKeyType="done"
autoCorrect={false}
secureTextEntry={true}
placeholderTextColor="#e0e0e0"
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
onSubmitEditing={(event)=> {
this.login();
}}
>
</TextInput>
</View>
</View>
<TouchableOpacity style={styles.forgotContainer}>
</TouchableOpacity>
</View>
</View>
<TouchableHighlight
underlayColor="#D6AB00"
onPress={this.login}
style={styles.signInButtonContainer}>
<Text style={styles.signInText}>Sign In</Text>
</TouchableHighlight>
</View>
</KeyboardAwareScrollView>
);
}
</code></pre> | 40,410,908 | 11 | 0 | null | 2016-11-02 23:52:25.333 UTC | 2 | 2022-09-11 22:10:31.46 UTC | 2016-11-03 00:04:19.96 UTC | null | 6,726,798 | null | 6,726,798 | null | 1 | 12 | android|ios|user-interface|reactjs|react-native | 43,578 | <p>I solved this problem by using another lib. Not sure why the react-native-keyboard-aware-scroll-view doesn't work but if you implement the react-native-keyboard-aware-view you shouldn't have any problems. </p>
<p><a href="https://www.npmjs.com/package/react-native-keyboard-aware-view" rel="noreferrer">https://www.npmjs.com/package/react-native-keyboard-aware-view</a></p> |
65,985,507 | Why shouldn't I use catch() to handle errors in React useEffect API calls? | <p>On this page of the React docs:</p>
<p><a href="https://reactjs.org/docs/faq-ajax.html" rel="noreferrer">https://reactjs.org/docs/faq-ajax.html</a></p>
<p>A code comment says...</p>
<blockquote>
<p>Note: it's important to handle errors here instead of a catch() block so that we don't swallow exceptions from actual bugs in components.</p>
</blockquote>
<p>...about handling errors in the second argument to the second <code>.then</code> after <code>fetch</code>. The complete snippet from the docs is:</p>
<pre class="lang-js prettyprint-override"><code> useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
</code></pre>
<p>It doesn't elaborate on this advice, and I've seen many examples of working React code using <code>catch</code> to handle errors from API calls. I've tried Googling but can't find any clarification.</p>
<p>Could someone please give me a more detailed explanation as to why I shouldn't use <code>catch</code> to deal with errors that arise when making a <code>fetch</code> API call in a <code>useEffect</code> hook?</p>
<p>Or are there some situations when it's ok to do so, but others when it's not?</p>
<p>What is meant by "swallow exceptions [...] in components" ?</p>
<p>Does this rule/guideline apply to all of React, or just to API calls?</p>
<p>Or just to the <code>useEffect</code> hook or <code>componentDidMount</code> lifecycle method?</p> | 65,989,940 | 2 | 0 | null | 2021-01-31 23:54:51.563 UTC | 5 | 2021-02-01 13:12:21.697 UTC | 2021-02-01 00:06:20.463 UTC | null | 6,243,352 | null | 9,274,894 | null | 1 | 33 | reactjs|react-hooks|use-effect | 8,540 | <p>It is a copy-and-paste error of the example's author.
The first example uses the component state of a class based component: <code>this.setState()</code> causes a synchronous re-render (or at least this was the case with react v15.0 in 2016, not sure if it holds true today). Therefore the warning comment and the use of the second arg to <code>.then(onResolve, onReject)</code> is justified.
The second example uses the <code>useState</code> hook of a function component: <code>setState</code> causes no <em>synchronous</em> re-render only an asynchronous re-render. Therefore the warning comment and the use of the second arg to <code>.then(onResolve, onReject)</code> is <strong>not</strong> justified.</p>
<p>To illustrate this: with <code>useState</code> hooks you can call multiple updaters and they all will only take effect in one re-render.</p>
<pre><code>const [a, setA] = useState();
const [b, setB] = useState();
const [c, setC] = useState();
const updateState = () => {
setA('foo');
setB('bar');
setC('buz');
// will only cause one single re-render
}
</code></pre>
<p>and therefore its perfectly fine to use catch</p>
<pre><code>useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
}
)
.catch(
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
</code></pre> |
36,095,496 | Angular 2: How to write a for loop, not a foreach loop | <p>Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, <code>*ngFor="let object of objects"</code>. However, I want to run a simple <code>for</code> loop, not a <code>foreach</code> loop. Something like (pseudo-code):</p>
<pre><code>{for i = 0; i < 5; i++}
<li>Something</li>
{endfor}
</code></pre>
<p>How would I do this?</p> | 38,249,801 | 11 | 0 | null | 2016-03-18 22:47:19.253 UTC | 9 | 2022-08-01 14:50:33.42 UTC | 2020-10-03 03:58:59.297 UTC | null | 3,357,958 | null | 3,357,958 | null | 1 | 83 | angular|angular2-template | 269,612 | <p>You can instantiate an empty array with a given number of entries if you pass an <code>int</code> to the <code>Array</code> constructor and then iterate over it via <code>ngFor</code>.</p>
<p><strong>In your component code :</strong></p>
<pre><code>export class ForLoop {
fakeArray = new Array(12);
}
</code></pre>
<p><strong>In your template :</strong></p>
<pre><code><ul>
<li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>
</code></pre>
<p>The index properties give you the iteration number.</p>
<p><a href="https://embed.plnkr.co/2tpFX9Y26FZ33AmTzJyd/" rel="noreferrer">Live version</a></p> |
45,842,167 | How to use DatePickerDialog in Kotlin? | <p>In Java an DatePickerDialog can be use such as:</p>
<pre><code>final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(getActivity(),new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
// Display Selected date in textbox
lblDate.setText(""+ dayOfMonth+" "+MONTHS[monthOfYear] + ", " + year);
}
}, year, month,day);
dpd.show();
</code></pre>
<p>How does Kotlin's DatePickerDialog use look like?</p> | 45,844,018 | 7 | 0 | null | 2017-08-23 14:11:32 UTC | 6 | 2020-06-07 22:05:57.147 UTC | null | null | null | null | 8,006,185 | null | 1 | 46 | kotlin|datepickerdialog | 62,209 | <p>It would look something like this:</p>
<pre><code>val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in textbox
lblDate.setText("" + dayOfMonth + " " + MONTHS[monthOfYear] + ", " + year)
}, year, month, day)
dpd.show()
</code></pre>
<p>this was done by simply copying and pasting the code into a kotlin file in android studio. I would strongly recommend using it.</p> |