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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
51,863,881 | Is there a way to create/modify connections through Airflow API | <p>Going through <code>Admin -> Connections</code>, we have the ability to create/modify a connection's params, but I'm wondering if I can do the same through API so I can programmatically set the connections</p>
<p><code>airflow.models.Connection</code> seems like it only deals with actually connecting to the instance instead of saving it to the list. It seems like a function that should have been implemented, but I'm not sure where I can find the docs for this specific function.</p> | 51,863,960 | 5 | 0 | null | 2018-08-15 17:49:10.613 UTC | 12 | 2022-02-16 22:11:14.013 UTC | null | null | null | null | 3,450,594 | null | 1 | 33 | python|airflow | 20,316 | <p>Connection is actually a model which you can use to query and insert a new connection </p>
<pre><code>from airflow import settings
from airflow.models import Connection
conn = Connection(
conn_id=conn_id,
conn_type=conn_type,
host=host,
login=login,
password=password,
port=port
) #create a connection object
session = settings.Session() # get the session
session.add(conn)
session.commit() # it will insert the connection object programmatically.
</code></pre> |
2,819,367 | Execute a stored procedure as another user permission | <p>I faced the following problem: there's a user who has to execute a stored procedure (spTest). In spTest's body sp_trace_generateevent is called. sp_trace_generateevent requires alter trace permissions, and I don't want user to have it. So I would like user to be able to execute spTest. How can I do that? </p> | 2,819,415 | 4 | 0 | null | 2010-05-12 13:47:52.463 UTC | null | 2020-02-12 08:35:46.29 UTC | 2018-02-20 22:34:14.397 UTC | null | 63,550 | null | 219,976 | null | 1 | 22 | sql-server|sql-server-2005|permissions | 87,105 | <p>Try this:</p>
<pre><code>EXECUTE AS user = 'special_user'
EXECUTE YourProcerdure
REVERT
</code></pre>
<p>see these:<br>
<a href="http://msdn.microsoft.com/en-us/library/ms191296.aspx" rel="noreferrer">Understanding Context Switching</a> <code><<<has examples of things like you are trying to do</code><br>
<a href="http://msdn.microsoft.com/en-us/library/ms187096.aspx" rel="noreferrer">Understanding Execution Context</a><br>
<a href="http://msdn.microsoft.com/en-us/library/ms188354.aspx" rel="noreferrer">EXECUTE AS Clause (Transact-SQL)</a><br>
<a href="http://msdn.microsoft.com/en-us/library/ms181362.aspx" rel="noreferrer">EXECUTE AS (Transact-SQL)</a></p> |
2,638,654 | Redirect C++ std::clog to syslog on Unix | <p>I work on Unix on a C++ program that send messages to syslog.</p>
<p>The current code uses the <strong>syslog</strong> system call that works like printf.</p>
<p>Now I would prefer to use a stream for that purpose instead, typically the built-in <strong>std::clog</strong>. But clog merely redirect output to stderr, not to syslog and that is useless for me as I also use stderr and stdout for other purposes.</p>
<p>I've seen in <a href="https://stackoverflow.com/questions/665509/redirecting-standard-output-to-syslog">another answer</a> that it's quite easy to redirect it to a file using rdbuf() but I see no way to apply that method to call syslog as openlog does not return a file handler I could use to tie a stream on it.</p>
<p>Is there another method to do that ? (looks pretty basic for unix programming) ? </p>
<p><strong>Edit:</strong> I'm looking for a solution that does not use external library. What @Chris is proposing could be a good start but is still a bit vague to become the accepted answer.</p>
<p><strong>Edit</strong>: using Boost.IOStreams is OK as my project already use Boost anyway.</p>
<p>Linking with external library is possible but is also a concern as it's GPL code. Dependencies are also a burden as they may conflict with other components, not be available on my Linux distribution, introduce third-party bugs, etc. If this is the only solution I may consider completely avoiding streams... (a pity).</p> | 4,457,138 | 4 | 10 | null | 2010-04-14 15:22:05.56 UTC | 19 | 2019-01-08 17:54:45.413 UTC | 2017-05-23 11:47:11.987 UTC | null | -1 | null | 168,465 | null | 1 | 27 | c++|stream|syslog|clog | 22,073 | <p>I needed something simple like this too, so I just put this together:</p>
<p>log.h:</p>
<pre><code>#include <streambuf>
#include <syslog.h>
enum LogPriority {
kLogEmerg = LOG_EMERG, // system is unusable
kLogAlert = LOG_ALERT, // action must be taken immediately
kLogCrit = LOG_CRIT, // critical conditions
kLogErr = LOG_ERR, // error conditions
kLogWarning = LOG_WARNING, // warning conditions
kLogNotice = LOG_NOTICE, // normal, but significant, condition
kLogInfo = LOG_INFO, // informational message
kLogDebug = LOG_DEBUG // debug-level message
};
std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
class Log : public std::basic_streambuf<char, std::char_traits<char> > {
public:
explicit Log(std::string ident, int facility);
protected:
int sync();
int overflow(int c);
private:
friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
std::string buffer_;
int facility_;
int priority_;
char ident_[50];
};
</code></pre>
<p>log.cc:</p>
<pre><code>#include <cstring>
#include <ostream>
#include "log.h"
Log::Log(std::string ident, int facility) {
facility_ = facility;
priority_ = LOG_DEBUG;
strncpy(ident_, ident.c_str(), sizeof(ident_));
ident_[sizeof(ident_)-1] = '\0';
openlog(ident_, LOG_PID, facility_);
}
int Log::sync() {
if (buffer_.length()) {
syslog(priority_, "%s", buffer_.c_str());
buffer_.erase();
priority_ = LOG_DEBUG; // default to debug for each message
}
return 0;
}
int Log::overflow(int c) {
if (c != EOF) {
buffer_ += static_cast<char>(c);
} else {
sync();
}
return c;
}
std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority) {
static_cast<Log *>(os.rdbuf())->priority_ = (int)log_priority;
return os;
}
</code></pre>
<p>In <code>main()</code> I initialize clog:</p>
<pre><code>std::clog.rdbuf(new Log("foo", LOG_LOCAL0));
</code></pre>
<p>Then whenever I want to log, it's easy:</p>
<pre><code>std::clog << kLogNotice << "test log message" << std::endl;
std::clog << "the default is debug level" << std::endl;
</code></pre> |
1,283,049 | How to set WPF string format as percent wihout multiplying by 100? | <p>I have a textbox bound to a property in an object.
I have setup the string format to be p0.</p>
<p>However, when I enter 12 for example it is formatted as 1200% (multiplies by 100 and add % sign)</p>
<p>How can i set the stringformat so that for exampe 20 is formatted as 20% ?</p>
<p>My current control is :</p>
<pre><code><TextBox Text="{Binding Path=MyCase, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, StringFormat=p0}"/>
</code></pre>
<p>how t change the string format so that the format for 7 is 7% not 700% ?</p> | 1,283,211 | 2 | 0 | null | 2009-08-15 22:42:39.457 UTC | 4 | 2019-05-24 09:20:01.277 UTC | 2010-07-01 11:59:37.637 UTC | null | 98,713 | null | 120,885 | null | 1 | 45 | wpf|data-binding | 47,114 | <pre><code>"{Binding Path=Percentage, StringFormat={}{0}%}"
</code></pre> |
2,931,704 | How to compare string with const char*? | <pre><code>#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string cmd;
while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0)
{
cin>>cmd;
cout<<cmd;
}
return 0;
}
</code></pre>
<p>I am stuck.</p> | 2,931,750 | 6 | 4 | null | 2010-05-28 18:52:46.007 UTC | 2 | 2014-12-20 07:40:11.653 UTC | 2010-05-28 18:55:28.92 UTC | null | 140,719 | null | 332,012 | null | 1 | 16 | c++ | 52,642 | <p>After fixing a couple of small bugs, this works on my machine: </p>
<pre><code>#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
int main()
{
std::string cmd;
while( std::strcmp(cmd.c_str(),"exit")!=0
&& std::strcmp(cmd.c_str(),"\\exit")!=0)
{
std::cin>>cmd;
std::cout<<cmd << '\n';
}
return 0;
}
</code></pre>
<p>However, I wonder why you want to use <code>std::strcmp()</code> at all. As you have just found out, it's not as easy to use as the <code>std::string</code> class. This</p>
<pre><code>while(cmd!="exit" && cmd!="\\exit")
</code></pre>
<p>works just as well, is easier to understand, and thus easier to get right. </p> |
2,531,372 | How to stop emacs from replacing underbar with <- in ess-mode | <p><code>ess-mode</code> is "Emacs speaks statistics." This mode is useful for editing programs for R or Splus (two separate statistics packages).</p>
<p>In my buffer, when ever I type <code>_</code> the character is replaced with <code><-</code>, which is very frustrating. Is there an emacs lisp statement to turn off this behavior?</p>
<p>emacs: 22.1.1
ess-mode release (unknown)</p> | 2,531,417 | 6 | 2 | null | 2010-03-27 23:45:54.83 UTC | 9 | 2022-05-31 18:54:42.403 UTC | 2013-11-18 06:22:35.837 UTC | user1131435 | null | null | 30,636 | null | 1 | 56 | r|emacs|ess | 10,145 | <p>From <a href="http://ess.r-project.org/Manual/ess.html" rel="noreferrer">ESS's manual</a> (look under "Changes/New Features in 5.2.0"):</p>
<blockquote>
<p>ESS[S]: Pressing underscore ("_") once inserts " <- " (as before); pressing underscore twice inserts a literal underscore. To stop this smart behaviour, add "(ess-toggle-underscore nil)" to your .emacs after ess-site has been loaded</p>
</blockquote> |
2,340,610 | Difference between fflush and fsync | <p>I thought <code>fsync()</code> does <code>fflush()</code> internally, so using <code>fsync()</code> on a stream is OK. But I am getting an unexpected result when executed under network I/O.</p>
<p>My code snippet:</p>
<pre><code>FILE* fp = fopen(file, "wb");
/* multiple fputs() calls like: */
fputs(buf, fp);
...
...
fputs(buf.c_str(), fp);
/* get fd of the FILE pointer */
fd = fileno(fp);
#ifndef WIN32
ret = fsync(fd);
#else
ret = _commit(fd);
fclose(fp);
</code></pre>
<p>But it seems <code>_commit()</code> is not flushing the data (I tried on Windows and the data was written on a Linux exported filesystem).</p>
<p>When I changed the code to be:</p>
<pre><code>FILE* fp = fopen(file, "wb");
/* multiple fputs() calls like: */
fputs(buf, fp);
...
...
fputs(buf.c_str(), fp);
/* fflush the data */
fflush(fp);
fclose(fp);
</code></pre>
<p>it flushes the data.</p>
<p>I am wondering if <code>_commit()</code> does the same thing as <code>fflush()</code>. Any inputs?</p> | 2,340,641 | 6 | 4 | null | 2010-02-26 09:36:11.403 UTC | 36 | 2019-06-30 18:25:23.937 UTC | 2019-06-27 17:45:57.35 UTC | null | 10,795,151 | null | 258,479 | null | 1 | 70 | fflush|fsync|c|windows | 55,123 | <p><code>fflush()</code> works on <code>FILE*</code>, it just flushes the internal buffers in the <code>FILE*</code> of your application out to the OS.</p>
<p><code>fsync</code> works on a lower level, it tells the OS to flush its buffers to the physical media.</p>
<p>OSs heavily cache data you write to a file. If the OS enforced every write to hit the drive, things would be <em>very</em> slow. <code>fsync</code> (among other things) allows you to control when the data should hit the drive.</p>
<p>Furthermore, fsync/commit works on a file descriptor. It has no knowledge of a <code>FILE*</code> and can't flush its buffers. <code>FILE*</code> lives in your application, file descriptors live in the OS kernel, typically.</p> |
2,564,137 | How to terminate a thread when main program ends? | <p>If I have a thread in an infinite loop, is there a way to terminate it when the main program ends (for example, when I press <kbd><strong>Ctrl</strong></kbd>+<kbd><strong>C</strong></kbd>)?</p> | 2,564,161 | 6 | 0 | null | 2010-04-01 22:44:52.77 UTC | 18 | 2022-09-19 08:34:30.14 UTC | 2019-11-20 00:37:02.487 UTC | null | 355,230 | null | 282,307 | null | 1 | 93 | python|multithreading|python-multithreading | 190,062 | <p>Check this question. The correct answer has great explanation on how to terminate threads the right way:
<a href="https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">Is there any way to kill a Thread in Python?</a></p>
<p>To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:</p>
<pre><code>try:
start_thread()
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread()
sys.exit()
</code></pre>
<p>This way you can control what to do whenever the program is abruptly terminated.</p>
<p>You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): <a href="http://docs.python.org/library/signal.html" rel="noreferrer">http://docs.python.org/library/signal.html</a></p> |
2,862,071 | How large should my recv buffer be when calling recv in the socket library | <p>I have a few questions about the socket library in C. Here is a snippet of code I'll refer to in my questions.</p>
<pre><code>char recv_buffer[3000];
recv(socket, recv_buffer, 3000, 0);
</code></pre>
<ol>
<li>How do I decide how big to make recv_buffer? I'm using 3000, but it's arbitrary. </li>
<li>what happens if <code>recv()</code> receives a packet bigger than my buffer? </li>
<li>how can I know if I have received the entire message without calling recv again and have it wait forever when there is nothing to be received?</li>
<li>is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space? maybe using <code>strcat</code> to concatenate the latest <code>recv()</code> response to the buffer?</li>
</ol>
<p>I know it's a lot of questions in one, but I would greatly appreciate any responses.</p> | 2,862,176 | 6 | 0 | null | 2010-05-19 00:19:47.027 UTC | 106 | 2019-05-03 11:12:58.23 UTC | 2015-09-19 08:32:09.983 UTC | null | 2,335,648 | null | 191,474 | null | 1 | 154 | c|sockets|buffer|recv | 127,132 | <p>The answers to these questions vary depending on whether you are using a stream socket (<code>SOCK_STREAM</code>) or a datagram socket (<code>SOCK_DGRAM</code>) - within TCP/IP, the former corresponds to TCP and the latter to UDP.</p>
<p><em>How do you know how big to make the buffer passed to <code>recv()</code>?</em></p>
<ul>
<li><p><code>SOCK_STREAM</code>: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).</p></li>
<li><p><code>SOCK_DGRAM</code>: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.</p></li>
</ul>
<p><em>What happens if <code>recv</code> gets a packet larger than the buffer?</em></p>
<ul>
<li><p><code>SOCK_STREAM</code>: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to <code>recv</code>.</p></li>
<li><p><code>SOCK_DGRAM</code>: The excess bytes are discarded.</p></li>
</ul>
<p><em>How can I know if I have received the entire message?</em></p>
<ul>
<li><p><code>SOCK_STREAM</code>: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.</p></li>
<li><p><code>SOCK_DGRAM</code>: An single <code>recv</code> call always returns a single datagram.</p></li>
</ul>
<p><em>Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?</em></p>
<p>No. However, you can try to resize the buffer using <code>realloc()</code> (if it was originally allocated with <code>malloc()</code> or <code>calloc()</code>, that is).</p> |
2,579,666 | getElementsByTagName() equivalent for textNodes | <p>Is there any way to get the collection of all <code>textNode</code> objects within a document? </p>
<p><code>getElementsByTagName()</code> works great for Elements, but <code>textNode</code>s are not Elements.</p>
<p><strong>Update:</strong> I realize this can be accomplished by walking the DOM - as many below suggest. I know how to write a DOM-walker function that looks at every node in the document. I was hoping there was some browser-native way to do it. After all it's a little strange that I can get all the <code><input></code>s with a single built-in call, but not all <code>textNode</code>s.</p> | 2,579,869 | 7 | 0 | null | 2010-04-05 16:58:36.92 UTC | 47 | 2020-08-07 07:38:51.65 UTC | 2010-04-05 21:57:13.26 UTC | null | 4,465 | null | 4,465 | null | 1 | 89 | javascript|dom|dhtml|textnode | 18,875 | <p><strong>Update</strong>:</p>
<p>I have outlined some basic performance tests for each of these 6 methods over 1000 runs. <code>getElementsByTagName</code> is the fastest but it does a half-assed job, as it does not select all elements, but only one particular type of tag ( i think <code>p</code>) and blindly assumes that its firstChild is a text element. It might be little flawed but its there for demonstration purpose and comparing its performance to <code>TreeWalker</code>. <a href="http://jsfiddle.net/zaqtg/10/" rel="noreferrer">Run the tests yourselves on jsfiddle</a> to see the results.</p>
<ol>
<li>Using a TreeWalker</li>
<li>Custom Iterative Traversal</li>
<li>Custom Recursive Traversal</li>
<li>Xpath query</li>
<li>querySelectorAll</li>
<li>getElementsByTagName</li>
</ol>
<p>Let's assume for a moment that there is a method that allows you to get all <code>Text</code> nodes natively. You would still have to traverse each resulting text node and call <code>node.nodeValue</code> to get the actual text as you would do with any DOM Node. So the issue of performance is not with iterating through text nodes, but iterating through all nodes that are not text and checking their type. I would argue (based on the results) that <code>TreeWalker</code> performs just as fast as <code>getElementsByTagName</code>, if not faster (even with getElementsByTagName playing handicapped).</p>
<pre>
Ran each test 1000 times.
Method Total ms Average ms
--------------------------------------------------
document.TreeWalker 301 0.301
Iterative Traverser 769 0.769
Recursive Traverser 7352 7.352
XPath query 1849 1.849
querySelectorAll 1725 1.725
getElementsByTagName 212 0.212
</pre>
<hr />
<p>Source for each method:</p>
<p><strong>TreeWalker</strong></p>
<pre><code>function nativeTreeWalker() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node.nodeValue);
}
}
</code></pre>
<p><strong>Recursive Tree Traversal</strong></p>
<pre><code>function customRecursiveTreeWalker() {
var result = [];
(function findTextNodes(current) {
for(var i = 0; i < current.childNodes.length; i++) {
var child = current.childNodes[i];
if(child.nodeType == 3) {
result.push(child.nodeValue);
}
else {
findTextNodes(child);
}
}
})(document.body);
}
</code></pre>
<p><strong>Iterative Tree Traversal</strong></p>
<pre><code>function customIterativeTreeWalker() {
var result = [];
var root = document.body;
var node = root.childNodes[0];
while(node != null) {
if(node.nodeType == 3) { /* Fixed a bug here. Thanks @theazureshadow */
result.push(node.nodeValue);
}
if(node.hasChildNodes()) {
node = node.firstChild;
}
else {
while(node.nextSibling == null && node != root) {
node = node.parentNode;
}
node = node.nextSibling;
}
}
}
</code></pre>
<p><strong>querySelectorAll</strong></p>
<pre><code>function nativeSelector() {
var elements = document.querySelectorAll("body, body *"); /* Fixed a bug here. Thanks @theazureshadow */
var results = [];
var child;
for(var i = 0; i < elements.length; i++) {
child = elements[i].childNodes[0];
if(elements[i].hasChildNodes() && child.nodeType == 3) {
results.push(child.nodeValue);
}
}
}
</code></pre>
<p><strong>getElementsByTagName</strong> (handicap)</p>
<pre><code>function getElementsByTagName() {
var elements = document.getElementsByTagName("p");
var results = [];
for(var i = 0; i < elements.length; i++) {
results.push(elements[i].childNodes[0].nodeValue);
}
}
</code></pre>
<p><strong>XPath</strong></p>
<pre><code>function xpathSelector() {
var xpathResult = document.evaluate(
"//*/text()",
document,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
var results = [], res;
while(res = xpathResult.iterateNext()) {
results.push(res.nodeValue); /* Fixed a bug here. Thanks @theazureshadow */
}
}
</code></pre>
<p>Also, you might find this discussion helpful - <a href="http://bytes.com/topic/javascript/answers/153239-how-do-i-get-elements-text-node" rel="noreferrer">http://bytes.com/topic/javascript/answers/153239-how-do-i-get-elements-text-node</a></p> |
2,911,714 | Creating a Month Dropdown in C# ASP.NET MVC | <p>This method seems stupid and a bit heavy; is there a more optimal way of creating the same thing (its for an MVC View Dropdown)</p>
<pre><code>private List<KeyValuePair<int, string>> getMonthListDD
{
get
{
var dDur = new List<KeyValuePair<int, string>>();
dDur.Add(new KeyValuePair<int, string>(1, "January"));
dDur.Add(new KeyValuePair<int, string>(2, "Febuary"));
dDur.Add(new KeyValuePair<int, string>(3, "March"));
dDur.Add(new KeyValuePair<int, string>(4, "April"));
dDur.Add(new KeyValuePair<int, string>(5, "May"));
dDur.Add(new KeyValuePair<int, string>(6, "June"));
dDur.Add(new KeyValuePair<int, string>(7, "July"));
dDur.Add(new KeyValuePair<int, string>(8, "August"));
dDur.Add(new KeyValuePair<int, string>(9, "September"));
dDur.Add(new KeyValuePair<int, string>(10, "October"));
dDur.Add(new KeyValuePair<int, string>(11, "November"));
dDur.Add(new KeyValuePair<int, string>(12, "December"));
return dDur;
}
}
</code></pre> | 2,911,776 | 8 | 0 | null | 2010-05-26 09:39:14.2 UTC | 7 | 2018-09-18 12:48:29.163 UTC | null | null | null | null | 52,912 | null | 1 | 34 | c#|asp.net-mvc|c#-3.0 | 33,305 | <p>In your view model you could have a <code>Months</code> property:</p>
<pre><code>public IEnumerable<SelectListItem> Months
{
get
{
return DateTimeFormatInfo
.InvariantInfo
.MonthNames
.Select((monthName, index) => new SelectListItem
{
Value = (index + 1).ToString(),
Text = monthName
});
}
}
</code></pre>
<p>which could be directly bound to a <code>DropDownListFor</code>:</p>
<pre><code><%= Html.DropDownListFor(x => x.SelectedMonth, Model.Months) %>
</code></pre> |
2,514,713 | What is an Ontology (Database?)? | <p>I was just reading <a href="http://architects.dzone.com/news/architecture-change-breaking" rel="noreferrer">this article</a> and it mentions that some organization had an Ontology as(?) their database(?) layer, and that the decision to do this was bad. Problem is I hadn't heard about this before, so I can't understand why it's bad.</p>
<p>So I tried googling about databases and ontology, and came about quite a few pdfs from 2006 that we're full of incomprehensible content (for my mind). I read a few of these and at this point still have absolutely no idea what they are talking about.</p>
<p>My current impression is that it was some crazy fad of 2006 that some academics were trying to sell us, but failed miserably due to the wording of their ideas. But I'm still curious if anyone actually knows what this is actually all about.</p> | 2,514,919 | 9 | 1 | null | 2010-03-25 10:32:07.263 UTC | 16 | 2021-02-10 23:19:04.97 UTC | null | null | null | null | 15,124 | null | 1 | 26 | database|ontology | 25,591 | <p>Karussell already provided the wikipedia definition: </p>
<blockquote>
<p>"a formal representation of the
knowledge by a set of concepts within
a domain and the relationships between
those concepts".</p>
</blockquote>
<p>In order to implement such a representation, several languages have been developed. The one that currently gets the most attention is probably the <a href="http://www.w3.org/TR/owl-features/" rel="noreferrer">Web Ontology Language (OWL)</a>. </p>
<p>In a traditional relational database, concepts can be stored using tables, but the system does not contain any information about what the concepts mean and how they relate to each other. Ontologies <em>do</em> provide the means to store such information, which allows for a much richer way to store information. This also means that one can construct fairly advanced and intelligent queries. Query languages such as <a href="http://www.w3.org/TR/rdf-sparql-query/" rel="noreferrer">SPARQL</a> have been developed specifically for this purpose.</p>
<p>For my masters thesis, I have worked with OWL ontologies, but this was as part of a fairly academic research. I don't know if any of this technology is currently used in practice very much, but I'm sure the potential is there.</p>
<h3>Update: example</h3>
<p>An example of 'meaning' and reasoning over the ontologies: say you define in your ontology a class <code>Pizza</code>, and a class <code>Vegetarian Pizza</code>, which is a <code>Pizza</code> that has no <code>Ingredients</code> that belong to the class <code>Meat</code>. If you now create some instance of a <code>Pizza</code> that just happens not to have any meat ingredients, the system can automatically infer that your pizza is also a <code>Vegetarian Pizza</code>, even if you did not explicitly specify it. </p> |
2,465,266 | safari and chrome javascript console multiline | <p>Firebug has a multiline feature in their console tool. Is there a way to get this functionality with the debugger tool in Safari/Chrome?</p> | 4,805,567 | 9 | 1 | null | 2010-03-17 19:33:33.11 UTC | 18 | 2019-11-19 12:06:05.077 UTC | null | null | null | null | 190,155 | null | 1 | 67 | javascript|browser|debugging | 36,793 | <p>Shift-Enter on Windows allows multi-line entry where Option-Enter works on Mac. </p>
<p>A more fully featured editor is in the works.</p> |
24,952,401 | How to convert List to JavaRDD | <p>We know that in spark there is a method rdd.collect which converts RDD to a list.</p>
<pre><code>List<String> f= rdd.collect();
String[] array = f.toArray(new String[f.size()]);
</code></pre>
<p>I am trying to do exactly opposite in my project. I have an ArrayList of String which I want to convert to JavaRDD. I am looking for this solution for quite some time but have not found the answer. Can anybody please help me out here?</p> | 24,953,895 | 4 | 0 | null | 2014-07-25 09:28:28.61 UTC | 3 | 2017-10-17 17:34:37.18 UTC | null | null | null | null | 2,488,981 | null | 1 | 35 | apache-spark | 57,079 | <p>You're looking for <a href="https://spark.apache.org/docs/latest/api/java/org/apache/spark/api/java/JavaSparkContext.html#parallelize(java.util.List)"><code>JavaSparkContext.parallelize(List)</code></a> and similar. This is just like in the Scala API.</p> |
10,659,860 | SQL - Remove the duplicate Results | <p>I have a table that looks like this:</p>
<pre><code>name | surname
------------------
John | John
Jessica | Madson
</code></pre>
<p>I have a query like this:</p>
<pre><code>SELECT *
FROM TABLE
WHERE name LIKE '%j%'
OR surname LIKE '%j%'
</code></pre>
<p>What I get:</p>
<pre><code>John John
John John
Jessica Madson
</code></pre>
<p>What I want:</p>
<pre><code>John John
Jessica Madson
</code></pre>
<p>How can I get rid of the duplicate results?</p> | 10,659,894 | 4 | 0 | null | 2012-05-18 21:16:07.313 UTC | 3 | 2020-02-03 12:16:11.547 UTC | 2020-02-03 11:39:47.537 UTC | null | 10,532,500 | null | 1,013,088 | null | 1 | 13 | sql|duplicates | 60,665 | <p>Use <code>DISTINCT</code>:</p>
<pre><code>SELECT DISTINCT name, surname
FROM yourtable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
</code></pre> |
10,535,950 | Forcing NVIDIA GPU programmatically in Optimus laptops | <p>I'm programming a DirectX game, and when I run it on an Optimus laptop the Intel GPU is used, resulting in horrible performance. If I force the NVIDIA GPU using the context menu or by renaming my executable to bf3.exe or some other famous game executable name, performance is as expected.<br/>
Obviously neither is an acceptable solution for when I have to redistribute my game, so is there a way to programmatically force the laptop to use the NVIDIA GPU?<br/><br/>
I've already tried using DirectX to enumerate adapters (IDirect3D9::GetAdapterCount, IDirect3D9::GetAdapterIdentifier) and it doesn't work: only 1 GPU is being reported (the one in use).</p> | 10,545,107 | 2 | 0 | null | 2012-05-10 14:16:52.113 UTC | 13 | 2012-12-26 13:10:37.813 UTC | 2012-05-10 14:59:53.417 UTC | null | 1,387,328 | null | 1,387,328 | null | 1 | 27 | c++|directx|nvidia|optimus | 13,201 | <p>The Optimus whitepaper at <a href="http://www.nvidia.com/object/LO_optimus_whitepapers.html" rel="noreferrer">http://www.nvidia.com/object/LO_optimus_whitepapers.html</a> is unclear on exactly what it takes before a switch to GPU is made. The whitepaper says that DX, DXVA, and CUDA calls are detected and will cause the GPU to be turned on. But in addition the decision is based on profiles maintained by NVIDIA and, of course, one does not yet exist for your game.</p>
<p>One thing to try would be make a CUDA call, for instance to <code>cuInit(0);</code>. As opposed to DX and DXVA, there is not way for the Intel integrated graphics to handle that, so it should force a switch to the GPU.</p> |
10,519,432 | How to do raw mongodb operations in mongoose? | <p>I'm asking this because when I write unit tests, I want to drop the test database and insert some initialize data, and also check the data in mongodb in testing. So I need raw operations to mongodb.</p>
<p>How to do this in mongoose? What I can do now is just create the connection, and not find any document in mongoose's official site.</p>
<pre><code> var mongoose = require('mongoose');
mongoose.connect('mongo://localhost/shuzu_test');
// get the connection
var conn = mongoose.connection;
</code></pre>
<p>But how to:</p>
<ol>
<li>drop the database</li>
<li>create a collection</li>
<li>write some data to a collection</li>
<li>query a collection</li>
<li>drop a collection</li>
</ol> | 10,519,504 | 6 | 0 | null | 2012-05-09 15:41:21.757 UTC | 22 | 2020-10-21 04:10:34.007 UTC | null | null | null | null | 342,235 | null | 1 | 75 | mongodb|mongoose | 55,631 | <p>See the section on "Driver Access" in the docs:
<a href="http://mongoosejs.com/" rel="nofollow noreferrer">http://mongoosejs.com/</a></p>
<p>Basically you can get access to the <a href="https://github.com/mongodb/node-mongodb-native" rel="nofollow noreferrer">node-mongodb-native</a> driver by doing <code>YourModel.collection</code> and then you can <code>insert</code> or <code>remove</code> or <code>drop</code> or whatever you need.</p>
<p>There's not a doc, but with this approach you'll get access to everything in here:
<a href="https://mongoosejs.com/docs/api.html#collection-js" rel="nofollow noreferrer">https://mongoosejs.com/docs/api.html#collection-js</a></p>
<p><strong>Edit:</strong></p>
<p>In your case you may want to skip using mongoose in your test suite and use the <a href="https://github.com/mongodb/node-mongodb-native" rel="nofollow noreferrer">node-mongodb-native</a> directly, or even write a simple <a href="http://www.mongodb.org/display/DOCS/Scripting+the+shell" rel="nofollow noreferrer">mongodb shell script</a> that can be run before your tests start.</p> |
10,363,933 | How to use transactions with dapper.net? | <p>I would like to run multiple insert statements on multiple tables. I am using dapper.net. I don't see any way to handle transactions with dapper.net.</p>
<p>Please share your ideas on how to use transactions with dapper.net.</p> | 10,363,978 | 6 | 0 | null | 2012-04-28 13:27:41.893 UTC | 24 | 2021-05-10 17:09:46.48 UTC | 2019-05-08 06:00:14.627 UTC | null | 5,779,732 | null | 147,613 | null | 1 | 140 | c#|transactions|dapper | 88,794 | <p>Here the code snippet:</p>
<pre><code>using System.Transactions;
....
using (var transactionScope = new TransactionScope())
{
DoYourDapperWork();
transactionScope.Complete();
}
</code></pre>
<p>Note that you need to add reference to <code>System.Transactions</code> assembly because it is not referenced by default. </p> |
5,893,183 | JSTL iterate over list of objects | <p>I am getting a list 'myList' of objects in jsp. Objects I am getting belongs to e.g 'MyClass'.
I want to iterate over this list through JSTL.</p>
<p>JSP code is below :</p>
<pre><code><c:forEach items="myList" var="element">
<tr>
<td>${element.getStatus()}</td>
<td>${element.getRequestType()}</td>
<td>${element.getRequestedFor()}</td>
<td>${element.getTimeSubmitted()}</td>
</tr>
</c:forEach>
</code></pre>
<p>I am getting exception :</p>
<pre><code> 00000024 WebApp E [Servlet Error]-[/requestHistory.jsp]: com.ibm.ws.jsp.translator.JspTranslationException: JSPG0227E: Exception caught while translating /requestHistory.jsp:
/requestHistory.jsp(31,6) --> JSPG0122E: Unable to parse EL function ${UserProcessRequests.getStatus()}.
</code></pre>
<p>Taglib I am using are :</p>
<pre><code> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false"%>
</code></pre> | 5,893,634 | 2 | 0 | null | 2011-05-05 05:47:22.757 UTC | 8 | 2013-05-15 05:44:25.457 UTC | 2011-05-05 13:38:26.687 UTC | null | 157,882 | null | 420,613 | null | 1 | 33 | java|jsp|jstl|iteration | 101,606 | <p>There is a mistake. See this line <code><c:forEach items="${myList}" var="element"></code>. ${} around 'myList' was missing.</p>
<pre><code><c:forEach items="${myList}" var="element">
<tr>
<td>${element.status}</td>
<td>${element.requestType}</td>
<td>${element.requestedFor}</td>
<td>${element.timeSubmitted}</td>
</tr>
</c:forEach>
</code></pre> |
31,054,453 | Ansible - actions BEFORE gathering facts | <p>Does anyone know how to do something (like wait for port / boot of the managed node) <em>BEFORE</em> gathering facts? I know I can turn gathering facts off</p>
<pre><code>gather_facts: no
</code></pre>
<p>and <em>THEN</em> wait for port but what if I need the facts while also still need to wait until the node boots up?</p> | 31,059,230 | 3 | 0 | null | 2015-06-25 15:21:28.02 UTC | 10 | 2022-06-20 08:27:56.02 UTC | 2017-01-19 05:46:33.8 UTC | null | 2,947,502 | null | 2,428,025 | null | 1 | 52 | ansible|ansible-facts | 22,659 | <p>Gathering facts is equivalent to running the <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/setup_module.html" rel="nofollow noreferrer"><code>setup</code> module</a>. You can manually gather facts by running it. It's not documented, but simply add a task like this:</p>
<pre><code>- name: Gathering facts
setup:
</code></pre>
<p>In combination with <code>gather_facts: no</code> on playbook level the facts will only be fetched when above task is executed.</p>
<p>Both in an example playbook:</p>
<pre><code>- hosts: all
gather_facts: no
tasks:
- name: Some task executed before gathering facts
# whatever task you want to run
- name: Gathering facts
setup:
</code></pre> |
31,239,831 | @function v/s @mixin in Sass-lang. Which one to use? | <p>After searching a lot in difference between @function and @mixin I ended up here. </p>
<p>Is there any advantage of using @mixin over @funcion or vice versa. In what context they'll be different, how to use them interchangeably, please come up with examples.</p> | 31,240,473 | 3 | 1 | null | 2015-07-06 07:18:30.073 UTC | 7 | 2022-07-19 10:46:27.897 UTC | null | null | null | null | 1,696,621 | null | 1 | 37 | sass | 14,076 | <p>Functions are useful specifically because they <em>return</em> values. Mixins are nothing like functions--they usually just provide valuable blocks of code.</p>
<p>Usually, there are cases where you might have to use both.</p>
<p>For example, if I wanted to create a <a href="http://codepen.io/danieltott/pen/AjKay" rel="noreferrer">long-shadow with SASS</a>, I would call a function like so:</p>
<pre><code>@function makelongshadow($color) {
$val: 0px 0px $color;
@for $i from 1 through 200 {
$val: #{$val}, #{$i}px #{$i}px #{$color};
}
@return $val;
}
</code></pre>
<p>Which would then be called with this mixin:</p>
<pre><code>@mixin longshadow($color) {
text-shadow: makelongshadow($color);
}
</code></pre>
<p>Which provides us with the actual code.</p>
<p>That gets included in the element:</p>
<pre><code>h1 {
@include longshadow(darken($color, 5% ));
}
</code></pre> |
40,976,536 | How to define Typescript Map of key value pair. where key is a number and value is an array of objects | <p>In my angular2 app i want to create a map which takes a number as key and returns an array of objects. I am currently implementing in following way but no luck. How should i implement it or should i use some other data structure for this purpose? I want to use map because maybe its fast?</p>
<p><strong>Declaration</strong></p>
<pre><code> private myarray : [{productId : number , price : number , discount : number}];
priceListMap : Map<number, [{productId : number , price : number , discount : number}]>
= new Map<number, [{productId : number , price : number , discount : number}]>();
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>this.myarray.push({productId : 1 , price : 100 , discount : 10});
this.myarray.push({productId : 2 , price : 200 , discount : 20});
this.myarray.push({productId : 3 , price : 300 , discount : 30});
this.priceListMap.set(1 , this.myarray);
this.myarray = null;
this.myarray.push({productId : 1 , price : 400 , discount : 10});
this.myarray.push({productId : 2 , price : 500 , discount : 20});
this.myarray.push({productId : 3 , price : 600 , discount : 30});
this.priceListMap.set(2 , this.myarray);
this.myarray = null;
this.myarray.push({productId : 1 , price : 700 , discount : 10});
this.myarray.push({productId : 2 , price : 800 , discount : 20});
this.myarray.push({productId : 3 , price : 900 , discount : 30});
this.priceListMap.set(3 , this.myarray);
this.myarray = null;
</code></pre>
<p>I want to get an array of 3 objects if i use <code>this.priceList.get(1);</code></p> | 40,976,654 | 3 | 0 | null | 2016-12-05 14:26:14.833 UTC | 20 | 2022-04-21 23:08:23.707 UTC | 2016-12-05 14:33:28.003 UTC | null | 942,852 | null | 3,926,831 | null | 1 | 60 | arrays|json|angular|typescript | 256,195 | <p>First thing, define a type or interface for your object, it will make things much more readable:</p>
<pre><code>type Product = { productId: number; price: number; discount: number };
</code></pre>
<p>You used <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html#tuple" rel="noreferrer">a tuple</a> of size one instead of array, it should look like this:</p>
<pre><code>let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
</code></pre>
<p>So now this works fine:</p>
<pre><code>myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
</code></pre>
<p>(<a href="https://www.typescriptlang.org/play/#src=type%20Product%20%3D%20%7B%20productId%3A%20number%2C%20price%3A%20number%2C%20discount%3A%20number%20%7D%3B%0A%0Alet%20myarray%3A%20Product%5B%5D%3B%0Alet%20priceListMap%20%3A%20Map%3Cnumber%2C%20Product%5B%5D%3E%20%3D%20new%20Map%3Cnumber%2C%20Product%5B%5D%3E()%3B%0A%0Amyarray.push(%7BproductId%20%3A%201%20%2C%20price%20%3A%20100%20%2C%20discount%20%3A%2010%7D)%3B%0Amyarray.push(%7BproductId%20%3A%202%20%2C%20price%20%3A%20200%20%2C%20discount%20%3A%2020%7D)%3B%0Amyarray.push(%7BproductId%20%3A%203%20%2C%20price%20%3A%20300%20%2C%20discount%20%3A%2030%7D)%3B%0ApriceListMap.set(1%20%2C%20this.myarray)%3B%0Amyarray%20%3D%20null%3B%0A%0Amyarray.push(%7BproductId%20%3A%201%20%2C%20price%20%3A%20400%20%2C%20discount%20%3A%2010%7D)%3B%0Amyarray.push(%7BproductId%20%3A%202%20%2C%20price%20%3A%20500%20%2C%20discount%20%3A%2020%7D)%3B%0Amyarray.push(%7BproductId%20%3A%203%20%2C%20price%20%3A%20600%20%2C%20discount%20%3A%2030%7D)%3B%0ApriceListMap.set(2%20%2C%20this.myarray)%3B%0Amyarray%20%3D%20null%3B%0A%0Amyarray.push(%7BproductId%20%3A%201%20%2C%20price%20%3A%20700%20%2C%20discount%20%3A%2010%7D)%3B%0Amyarray.push(%7BproductId%20%3A%202%20%2C%20price%20%3A%20800%20%2C%20discount%20%3A%2020%7D)%3B%0Amyarray.push(%7BproductId%20%3A%203%20%2C%20price%20%3A%20900%20%2C%20discount%20%3A%2030%7D)%3B%0ApriceListMap.set(3%20%2C%20this.myarray)%3B%0Amyarray%20%3D%20null%3B" rel="noreferrer">code in playground</a>)</p> |
32,502,207 | Random "An existing connection was forcibly closed by the remote host." after a TCP reset | <p>I have two parts, a client and a server. And I try to send data (size > 5840 Bytes) from the client to the server and then the server sends the data back. I loop this a number of times waiting a second between each time. Sometime the server application crash, the crash seems very random the error:</p>
<blockquote>
<p>Unhandled Exception: System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---></p>
</blockquote>
<blockquote>
<p>System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host</p>
</blockquote>
<blockquote>
<p>at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)</p>
</blockquote>
<blockquote>
<p>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)</p>
</blockquote>
<blockquote>
<p>--- End of inner exception stack trace ---</p>
</blockquote>
<blockquote>
<p>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)</p>
</blockquote>
<blockquote>
<p>at TCP_Server.Program.Main(String[] args)</p>
</blockquote>
<p>Client code (This is inside the loop):</p>
<pre><code> try
{
Int32 port = 13777;
using (TcpClient client = new TcpClient(ip, port))
using (NetworkStream stream = client.GetStream())
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
var data = GenerateData(size);
sw.Start();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Buffer to store the response bytes.
data = new Byte[size];
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
sw.Stop();
Console.WriteLine(i + ": Done transporting " + size + " bytes to and from " + ip + " time: " +
sw.ElapsedMilliseconds + " ms");
// Close everything.
stream.Close();
client.Close();
}
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
sw.Reset();
</code></pre>
<p>Server code:</p>
<pre><code> Byte[] bytes = new Byte[size];
// Enter the listening loop.
for (int i = 0; i < numberOfPackages; i++)
{
using (TcpClient client = server.AcceptTcpClient())
using (NetworkStream stream = client.GetStream())
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
// Loop to receive all the data sent by the client.
while ((stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Send back a response.
stream.Write(bytes, 0, size);
}
client.GetStream().Close();
client.Close();
}
Console.WriteLine("Receive data size " + size);
}
</code></pre>
<p>I have used wireshark to monitor the tcp packages sent and found that a TCP RST is sent from the client to the server before the program crashes. So I assume the problem is that the the RST is not handles correctly.
There is no firewall between the client and the host so that is not the problem.</p>
<p>The wireshark files for both the Client and Server is here: <a href="https://www.dropbox.com/sh/ctl2chq3y2c20n7/AACgIJ8IRiclqnyOyw8sqd9La?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/sh/ctl2chq3y2c20n7/AACgIJ8IRiclqnyOyw8sqd9La?dl=0</a></p>
<p>So either I need to get rid of the TCP RST or I need my server to handle it in some way and not crash.</p>
<p>I have tried to use longer waiting time but it does not help.
If the data is below 5840 Bytes I do not get any crashes, what I know of.</p>
<p>Any suggestions or ideas?</p> | 32,504,052 | 5 | 0 | null | 2015-09-10 12:41:15.723 UTC | 2 | 2022-08-02 21:00:46.3 UTC | 2022-08-02 20:59:49.657 UTC | null | 2,756,409 | null | 1,131,957 | null | 1 | 12 | c#|.net|sockets|tcp|wireshark | 55,762 | <p>Two problems that I see:</p>
<ol>
<li>You are assuming that a read for <code>size</code> bytes will actually read <code>size</code> bytes. It does not. TCP is a streaming protocol. A read reads at least one byte. That's the only guarantee given.</li>
<li>Your code will randomly deadlock. The client writes data to the server. The server echos it back. But the client will not read until it has written everything. If it writes more than the network buffers can take this will deadlock. The client must read and write concurrently. Probably, you need another thread/task for reading the data back. A good pattern to solve that issue would be to start one writer task, one reader task and to Task.WhenAll/WaitAll to join them back.</li>
</ol>
<p>I'm not sure under what exact circumstances a TCP stack would send a RST. Could be due to the deadlock causing a timeout.</p>
<p>You are not swallowing any exceptions, right?</p>
<p>Normally, closing a connection performs an orderly shutdown in the background. But I'm unsure about what happens when the other side is still writing at this point. Maybe the answer is that an RST is generated by the receiver of the writes. Surely, the TCP spec would answer this question. If <a href="https://stackoverflow.com/a/9828143/122718">this answer</a> is to be trusted then indeed a Shutdown(Read)/Close followed by an incoming write would RST the connection.</p>
<p>Fix both issues and report back with your findings.</p> |
34,261,928 | Can Server Sent Events (SSE) with EventSource pass parameter by POST | <p>I'm using Html5 Server Sent Events. The server side is Java Servlet.
I have a json array data wants to pass to server.</p>
<pre><code>var source = new EventSource("../GetPointVal?id=100&jsondata=" + JSON.stringify(data));
</code></pre>
<p>If the array size is small , the server side can get the querystring.
But if the array size is big. (maybe over thousands of characters), the server can't get the querystring.
Is it possible to use POST method in <code>new EventSource(...)</code> to to pass the json array to server that can avoid the querystring length limitation? </p> | 34,285,526 | 3 | 0 | null | 2015-12-14 07:43:29.477 UTC | 5 | 2020-12-17 20:36:36.643 UTC | 2020-12-17 20:36:36.643 UTC | null | 124,486 | null | 2,450,397 | null | 1 | 35 | json|post|server-sent-events|eventsource | 21,958 | <p>No, the SSE standard does not allow POST.</p>
<p>(For no technical reason, as far as I've been able to tell - I think it was just that the designers never saw the use cases: it is not just large data, but if you want to do a custom authentication scheme there are security reasons not to put the password in GET data.)</p>
<p><code>XMLHttpRequest</code> (i.e. AJAX) does allow POST, so one option is to go back to the older long-poll/comet methods. (My book, <a href="http://shop.oreilly.com/product/0636920030928.do" rel="noreferrer">Data Push Apps with HTML5 SSE</a> goes into quite some detail about how to do this.)</p>
<p>Another approach is to <code>POST</code> all the data in beforehand, and store it in an <code>HttpSession</code>, and then call the SSE process, which can make use of that session data. (SSE does support cookies, so the <code>JSESSIONID</code> cookie should work fine.)</p>
<p>P.S. The <a href="http://www.w3.org/TR/eventsource/" rel="noreferrer">standard</a> doesn't explicitly say POST cannot be used. But, unlike <code>XMLHttpRequest</code>, there is no parameter to specify the http method to use, and no way to specify the data you want to post.</p> |
52,081,768 | How I can make `ctrl + click` to go to definition in visual studio code editor for mac OS? | <p>How I can make <code>ctrl + click</code> to go to definition in visual studio code editor for mac OS? Now it is F12 which is using my mac for show desktop.</p> | 56,024,839 | 8 | 0 | null | 2018-08-29 16:02:03.597 UTC | 9 | 2022-09-22 09:33:03.33 UTC | 2019-03-11 14:48:15.497 UTC | null | 2,631,715 | null | 2,871,542 | null | 1 | 57 | visual-studio-code|vscode-settings | 77,293 | <p>First and foremost, please note that in VS Code for macOS, the familiar <strong><kbd>Ctrl</kbd> + click</strong> from Windows / Linux operating systems has been replaced with <strong><kbd>⌘</kbd> + click</strong> (i.e.: "command + click"). Try that first before proceeding any further as that shortcut <em>should</em> work out of the box without any special modifications.</p>
<p>However, if the above still doesn't work for you then try fixing the problem by editing your <code>settings.json</code> file. To do that, press <kbd>F1</kbd>, type <code>settings json</code>, then click <code>Open Settings (JSON)</code>, and then do one of the following:</p>
<p>To use <strong><kbd>⌘</kbd> + click</strong> as your "Go to definition" shortcut, ensure the following line exists in your JSON settings:</p>
<pre><code>"editor.multiCursorModifier": "alt",
</code></pre>
<p>What this does is it explicitly sets VS Code's "add another cursor" shortcut to <strong><kbd>option</kbd> + click</strong> (try it out for yourself!), thus freeing up <strong><kbd>⌘</kbd> + click</strong> to be used for the "Go to definition" operation.</p>
<p>Conversely, to use <strong><kbd>option</kbd> + click</strong> as your "Go to definition" shortcut instead, add:</p>
<pre><code>"editor.multiCursorModifier": "ctrlCmd",
</code></pre>
<p>Note: the above line will actually set the "add another cursor" shortcut to <strong><kbd>⌘</kbd> + click</strong> (not <em><strong><kbd>Ctrl</kbd> + <kbd>⌘</kbd> + click</strong></em>, as implied by the JSON value).</p> |
21,364,445 | Apply CSS style attribute dynamically in Angular JS | <p>This should be a simple problem, but I can't seem to find a solution.</p>
<p>I have the following markup:</p>
<pre><code><div style="width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;"></div>
</code></pre>
<p>I need the background color to be bound to the scope, so I tried this:</p>
<pre><code><div style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:{{data.backgroundCol}};}"></div>
</code></pre>
<p>That didn't work, so I did some research and found <code>ng-style</code>, but that didn't work, so I tried taking the dynamic part out and just hard-coding the style in <code>ng-style</code>, like this...</p>
<pre><code><div ng-style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;}"></div>
</code></pre>
<p>and that doesn't even work. Am I misunderstanding how <code>ng-style</code> works? Is there a way of putting <code>{{data.backgroundCol}}</code> into a plain style attribute and getting it to insert the value?</p> | 21,364,563 | 6 | 1 | null | 2014-01-26 14:15:55 UTC | 22 | 2019-09-30 06:24:07.05 UTC | 2014-01-26 18:08:22.307 UTC | null | 2,015,318 | null | 56,007 | null | 1 | 113 | javascript|angularjs|ng-style | 331,076 | <p><a href="https://docs.angularjs.org/api/ng/directive/ngStyle" rel="noreferrer"><strong>ngStyle</strong></a> directive allows you to set <strong>CSS</strong> style on an HTML element dynamically.</p>
<blockquote>
<p><a href="https://docs.angularjs.org/guide/expression" rel="noreferrer">Expression</a> which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted. </p>
</blockquote>
<p><code>ng-style="{color: myColor}"</code></p>
<p>Your code will be:</p>
<pre><code><div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>
</code></pre>
<p>If you want to use scope variables:</p>
<pre><code><div ng-style="{'background-color': data.backgroundCol}"></div>
</code></pre>
<p><a href="http://jsfiddle.net/mrajcok/eTTZj/" rel="noreferrer">Here</a> an example on fiddle that use <code>ngStyle</code>, and below the code with the running snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.items = [{
name: 'Misko',
title: 'Angular creator'
}, {
name: 'Igor',
title: 'Meetup master'
}, {
name: 'Vojta',
title: 'All-around superhero'
}
];
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pending-delete {
background-color: pink
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">
<input type="text" ng-model="myColor" placeholder="enter a color name">
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
name: {{item.name}}, {{item.title}}
<input type="checkbox" ng-model="item.checked" />
<span ng-show="item.checked"/><span>(will be deleted)</span>
</div>
<p>
<div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>
</div></code></pre>
</div>
</div>
</p> |
21,888,052 | What is the relation between APP_PLATFORM, android:minSdkVersion and android:targetSdkVersion? | <p>I'm developing an Android app that uses NDK features. My app defines <code>android:minSdkVersion</code> and <code>android:targetSdkVersion</code> in <code>AndroidManifest.xml</code> and <code>APP_PLATFORM</code> in jni/Application.mk.</p>
<p>My current understanding is that <code>android:minSdkVersion</code> decalres minimal supported OS version, <code>android:targetSdkVersion</code> declares Java library version to be linked against, and <code>APP_PLATFORM</code> declares C++ library to be linked against.</p>
<p>Two questions:</p>
<ol>
<li><p>Is my understanding correct?</p></li>
<li><p>Is it Ok for <code>APP_PLATFORM</code> to be greater that <code>android:minSdkVersion</code>? Or they must be equal each other?</p></li>
</ol>
<p>The reason for my question: I want my app to be available for devices with <strong>API >= 10</strong>, but I need to use NDK functions (like <code>AMotionEvent_getAxisValue</code>) that are defined in <code>platforms\android-13</code> folder in NDK. So I use <code>android:minSdkVersion=10</code> and <code>APP_PLATFORM=13</code>. Project compiles successfully, but would it be runnable on API 10-12 devices?</p> | 21,982,908 | 3 | 0 | null | 2014-02-19 17:34:59.967 UTC | 15 | 2018-11-29 01:18:57.037 UTC | 2018-11-29 01:18:57.037 UTC | null | 8,034,839 | null | 674,548 | null | 1 | 18 | android|android-ndk | 12,708 | <ol>
<li><p><code>android:minSdkVersion</code> is the minimum OS version that your app expects.</p></li>
<li><p><code>android:targetSdkVersion</code> is essentially the maximum OS version that you've designed your app to work with. Here's an example of how this works. Imagine that you tested your app fine with API 19 and you release your app with <code>android:targetSdkVersion</code>=19. Then Google decides to release API 20 with a change in behavior of some API, but they don't want to change the behavior for old apps (to prevent from breaking them). So when your app starts up, Android sees that your app has <code>targetSdkVersion</code>=19, so it gives you the old API behavior, but if some other app says <code>targetSdkVersion</code>=20, Android will give it the new API behavior.</p></li>
<li><p><code>APP_PLATFORM</code> is the version of the native headers and libraries that the NDK will compile your native code with. If you set <code>APP_PLATFORM</code> to a specific value and you use APIs that are only available in that platform version, then your app will not run properly on older platforms. So <code>APP_PLATFORM</code> is a minimum value. The solution is to use a lower value and not use those newer APIs, or to write code that decides at runtime whether to call the new APIs or not (and probably use <code>dlopen</code>/<code>dlsym</code>).</p></li>
</ol>
<p>It seems like in general it doesn't make sense to use an <code>APP_PLATFORM</code> value newer than <code>android:minSdkVersion</code>, unless you're doing some special (like being careful not to call new APIs by checking the version at runtime, plus making sure not to link to new APIs and instead using <code>dlopen</code>/<code>dlsym</code>).</p>
<p>So if you use <code>APP_PLATFORM=13</code> and you call <code>AMotionEvent_getAxisValue</code> (which is not in earlier platform headers, implying that it isn't available at runtime on earlier platforms), your app will not run on devices with API < 13. The one caveat would be if <code>AMotionEvent_getAxisValue</code> is actually available on older versions, but it just wasn't in the header/library files or it just wasn't documented. But I don't know if that's the case for this particular API (basically, that would require more research and risk analysis of whether you want to depend on something unsupported).</p> |
36,725,314 | Bitcode Compile During Archive Never Finishes | <p>I am preparing an app for ad hoc distribution via Test Flight. I have stepped through (successfully) all of the preparatory steps in this Ray Wenderlich article already (<a href="https://www.raywenderlich.com/48750/testflight-sdk-tutorial">https://www.raywenderlich.com/48750/testflight-sdk-tutorial</a>), and I feel confident that the certificate, App ID, and Provisioning Profile are all created correctly and in proper working order. I am on the step in which you archive the project in Xcode. I have selected these settings during the archive process:</p>
<p>I choose to Export :</p>
<p><a href="https://i.stack.imgur.com/X8z3F.png"><img src="https://i.stack.imgur.com/X8z3F.png" alt="enter image description here"></a></p>
<p>I choose "Save for Ad Hoc deployment" since our plan is to use Test Flight to distribute the app to our testers. I <em>do</em> believe this is the correct option for that (as opposed to "for enterprise deployment"):</p>
<p><a href="https://i.stack.imgur.com/tEdyG.png"><img src="https://i.stack.imgur.com/tEdyG.png" alt="enter image description here"></a></p>
<p>This is the default setting, and I do not have a specific reason to change it, although I'd appreciate any insight you may have:</p>
<p><a href="https://i.stack.imgur.com/3JaYq.png"><img src="https://i.stack.imgur.com/3JaYq.png" alt="enter image description here"></a></p>
<p>Again, default options for both of these. The first one is unchecked by default and the second one is checked by default:</p>
<p><a href="https://i.stack.imgur.com/sna57.png"><img src="https://i.stack.imgur.com/sna57.png" alt="enter image description here"></a></p>
<p>When I get to this screen, the spinner spins seemingly forever:</p>
<p><a href="https://i.stack.imgur.com/62ejr.png"><img src="https://i.stack.imgur.com/62ejr.png" alt="enter image description here"></a></p>
<p>The problem seems to be that once it gets to the part where it is compiling from bitcode it spins and spins and shows no signs of finishing. When I am building the app to run on a device connected to the MBP, it compiles quickly, usually within a few seconds. What could be causing this unresponsiveness?</p> | 36,773,445 | 5 | 0 | null | 2016-04-19 17:23:04.317 UTC | 5 | 2018-09-26 15:35:47.14 UTC | 2016-04-21 03:55:52.77 UTC | null | 1,639,164 | null | 1,639,164 | null | 1 | 36 | ios|archive|bitcode | 17,325 | <p>I let this run for a long time (basically while I went out shopping). When I came back it was done. So for whatever reason this just takes a really long time to do.</p>
<p>That said, it was also the incorrect action. The way you add testers to TestFlight since Apple bought it is different. Now, instead of exporting and uploading an IPA file, you have to submit it to the store and let it be reviewed by Apple before you can add testers.</p> |
37,073,705 | Property 'catch' does not exist on type 'Observable<any>' | <p>On the Angular 2 documentation page for using the Http service, there is an example.</p>
<pre><code>getHeroes (): Observable<Stuff[]> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
}
</code></pre>
<p>I cloned the <a href="https://github.com/AngularClass/angular2-webpack-starter" rel="noreferrer">angular2-webpack-starter</a> project and added the above code myself. </p>
<p>I imported <code>Observable</code> using </p>
<pre><code>import {Observable} from 'rxjs/Observable';
</code></pre>
<p>I'm assuming the properties <code>Observable</code> are imported as well (<code>.map</code> works). Looked at the changelog for rxjs.beta-6 and nothing is mentioned about <code>catch</code>. </p> | 37,073,721 | 3 | 0 | null | 2016-05-06 13:30:18.177 UTC | 28 | 2020-12-17 18:00:42.523 UTC | 2018-08-15 19:29:45.33 UTC | null | 1,000,551 | null | 3,688,686 | null | 1 | 143 | javascript|angular|typescript|rxjs | 116,182 | <p><strong>Warning</strong>: This solution is deprecated since Angular 5.5, please refer to Trent's answer below</p>
<p>=====================</p>
<p>Yes, you need to import the operator:</p>
<pre><code>import 'rxjs/add/operator/catch';
</code></pre>
<p>Or import <code>Observable</code> this way:</p>
<pre><code>import {Observable} from 'rxjs/Rx';
</code></pre>
<p>But in this case, you import all operators.</p>
<p>See this question for more details:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276">Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]</a></li>
</ul> |
48,451,764 | How to set base size for rem | <p>I have a simple question, where do you declare the base size that <code>rem</code> is calculated from?</p>
<pre><code><body>
<h1>Something</h1>
</body>
</code></pre>
<p>I can see that the <code>font-size</code> is <code><body></code> is set to 16px and the <code><h1></code> is set to <code>3rem</code>, yet the font is rendering at 30px when I'd expect 48px. Can any parent redefine the base?</p> | 48,451,793 | 3 | 1 | null | 2018-01-25 20:54:46 UTC | 5 | 2022-07-22 07:21:06.797 UTC | null | null | null | null | 3,914,509 | null | 1 | 61 | css | 60,923 | <blockquote>
<p><strong>rem</strong></p>
<p>Represents the font-size of the root element (typically <code><html></code>).
When used within the root element font-size, it represents its initial
value (a common browser default is 16px, but user-defined preferences
may modify this).</p>
</blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/length" rel="noreferrer">Source</a></p>
<hr />
<p>In other words, change the <strong>font size of your <code>html</code> element</strong>, and the calculation base for <code>rem</code> will change.</p>
<p>Example:</p>
<pre class="lang-html prettyprint-override"><code><html style="font-size: 10px">
...
</html>
</code></pre> |
26,814,456 | How to get all the values that contains part of a string using mongoose find? | <p>I have the following problem retrieving data from MongoDB using mongoose.</p>
<p>Here is my Schema:</p>
<pre><code>const BookSchema = new Schema(
{
_id:Number,
title:String,
authors:[String],
subjects:[String]
}
);
</code></pre>
<p>as you can see i have 2 arrays embedded in the object, let's say the content of the authors can be something like this: authors:["Alex Ferguson", "Didier Drogba", "Cristiano Ronaldo", "Alex"]<br>
what I'm trying to achieve is get all the Alex in the array.</p>
<p>So far, I've been able to get the values if they match the value completely. However if I try to get the ones containing Alex the answer is always [].</p>
<p>What I want to know is how I can do this using find() without performing a map-reduce to create a view or a collection and then applying find() over that.</p>
<p>The code here works for exact matches</p>
<pre><code>Book.find( {authors:req.query.q} , function(errs, books){
if(errs){
res.send(errs);
}
res.json(books);
});
</code></pre>
<p>I tried some things but no luck
{authors:{$elemMatch:req.query.q}}
{authors:{$in:[req.query.q]}}</p>
<p>This one gives me an error and on top of that says is very inefficient in another post I found here.
{$where:this.authors.indexOf(req.query.q) != -1}</p>
<p>and I also tried {authors:{$regex:"./<em>value</em>/i"}}</p>
<p>The map-reduce works fine, I need to make it work using the other approach to see which one is better? </p>
<p>Any help is greatly appreciated. I'm sure this is easy, but I'm new with NodeJS and Mongo and I haven't been able to figure it out on my own.</p> | 26,814,550 | 3 | 0 | null | 2014-11-08 06:24:47.217 UTC | 26 | 2021-07-21 17:02:25.997 UTC | 2019-03-14 01:50:08.23 UTC | null | 2,313,887 | null | 4,229,458 | null | 1 | 72 | regex|node.js|mongodb|mongodb-query|aggregation-framework | 108,916 | <p>You almost answered this yourself in your tags. MongoDB has a <a href="http://docs.mongodb.org/manual/reference/operator/query/regex/"><strong><code>$regex</code></strong></a> operator which allows a regular expression to be submitted as a query. So you query for strings containing "Alex" you do this:</p>
<pre><code>Books.find(
{ "authors": { "$regex": "Alex", "$options": "i" } },
function(err,docs) {
}
);
</code></pre>
<p>You can also do this:</p>
<pre><code>Books.find(
{ "authors": /Alex/i },
function(err,docs) {
}
);
</code></pre>
<p>Both are valid and different to how you tried in the correct supported syntax as shown in the documentation.</p>
<p>But of course if you are actually asking "how to get the 'array' results only for those that match 'Alex' somewhere in the string?" then this is a bit different.</p>
<p>Complex matching for more than <strong>one</strong> array element is the domain of the <a href="http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/">aggregation framework</a> ( or possibly mapReduce, but that is much slower ), where you need to "filter" the array content.</p>
<p>You start of much the same. The key here is to <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/"><strong><code>$unwind</code></strong></a> to "de-normalize" the array content in order to be alble to "filter" properly as individual documents. Then re-construct the array with the "matching" documents.</p>
<pre><code>Books.aggregate(
[
// Match first to reduce documents to those where the array contains the match
{ "$match": {
"authors": { "$regex": "Alex", "$options": i }
}},
// Unwind to "de-normalize" the document per array element
{ "$unwind": "$authors" },
// Now filter those document for the elements that match
{ "$match": {
"authors": { "$regex": "Alex", "$options": i }
}},
// Group back as an array with only the matching elements
{ "$group": {
"_id": "$_id",
"title": { "$first": "$title" },
"authors": { "$push": "$authors" },
"subjects": { "$first": "$subjects" }
}}
],
function(err,results) {
}
)
</code></pre> |
742,564 | Using mmap over a file | <p>I'm trying to allow two different processes to communicate by using memory mapping the same file. However, I'm having some problems with this. I have a feeling this has to do with the way I'm using the open() call and passing my file descriptor to mmap. </p>
<p>Here is my code, can you see anything wrong with it?</p>
<p>Object 1's code:</p>
<pre><code> 16 FILE* temp = fopen(theSharedFileName, "w");
17 fseek(temp, fileSize-1, SEEK_SET);
18 fprintf(temp, "0"); // make the file a certain size
19 fseek(temp, 0, SEEK_CUR);
20
21 int sharedFileName = fileno(temp);
...
31 sharedArea = (MyStruct*)mmap(0, fileSize,
32 PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED, sharedFileName, 0);
</code></pre>
<p>I use the "w" file mode since Object 1 will only ever be made once and I want it to reset any previously existing data.</p>
<p>Object 2's Code:</p>
<pre><code> 130 FILE* tempFile = fopen(sharedFileName, "a");
131 int theFile = fileno(tempFile);
...
135 sharedArea = (MyStruct*)mmap(NULL, fileSize,
136 PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED, theFile, 0);
</code></pre> | 742,644 | 3 | 2 | null | 2009-04-12 22:49:08.263 UTC | 9 | 2009-04-13 01:31:01.62 UTC | null | null | null | null | 39,036 | null | 1 | 5 | c|file|mmap | 8,097 | <p>A few issues:</p>
<ol>
<li>Avoid mixing high-level I/O (fopen(), fseek()) and some low-level operation like mmap(). Although you can get the low-level file descriptor using fileno(), that is like taking the longest route to get to the same place. Also, just using mmap() breaks compatibility beyond BSD and POSIX, so you get nothing by using standard C I/O functions. Just use open() and lseek() directly.</li>
<li>It doesn't make sense to use stream formatted I/O (fprintf()) on the same file you are memory-mapping. When you memory-map a file, you are implicitly telling the system you are going to use it as random-access (direct indexing) data. fprintf() is for stream output, you usually use it for sequential access. In fact, although possible, it is unusual to see fprintf() and fseek() in the same descriptor (this is not even portable, but due to the previous item, I'm not considering portability).</li>
<li>The protection must match the open file protection. Since you are passing "w" to fopen(), and <code>PROT_READ | PROT_WRITE | PROT_EXEC</code> to mmap(), you are violating this restriction. This also highlights why you shouldn't mix high-level I/O with memory-mapping: how do you guarantee that <code>fopen(...,"w")</code> will open the file with the correct flags? This is supposed to be "implementation-detail" for the C library. If you want to memory-map a file with read and write permissions, you should use the low-level <code>open(theSharedFileName, O_RDWR)</code> to open the file.</li>
<li><strong>Do not</strong> use <code>PROT_WRITE</code> and <code>PROT_EXEC</code> together. It is not portable <strong>and</strong> it is a security risk. Read about <a href="http://en.wikipedia.org/wiki/W%5EX" rel="noreferrer">W^X</a> and <a href="http://en.wikipedia.org/wiki/Executable_space_protection" rel="noreferrer">executable space protection</a>.</li>
</ol> |
627,705 | .Net WebDAV Server | <p>I am looking to implement a WebDAV server in ASP.Net. the app will be deployed to IIS 6. I have seen a few frameworks that provide this functionality, but I can't seem to identify how they're able to accomplish it without (apparently) modifying IIS settings.</p>
<p>My specific question is how do I configure IIS and ASP.Net so that a IHttpModule/IHttpHandler might have an opportunity to handle any of the additional WebDAV verbs (i.e. LOCK, OPTIONS, PROFIND, etc.)</p> | 14,839,639 | 3 | 0 | null | 2009-03-09 19:42:24.083 UTC | 11 | 2013-02-12 18:50:36.373 UTC | null | null | null | Andrew Theken | 32,238 | null | 1 | 8 | c#|.net|webdav | 15,877 | <p>There is no way to configure WebDAV verbs in IIS 6 without modifying IIS settings. It is possible only with IIS 7 and later.</p>
<p>To handle all verbs required by WebDAV in IIS 6 you will need to create an application wildacrd map. Right click on your web application in IIS 6 MMC console and go to <em>Properties</em>-><em>Virtual Directory</em> Tab-><em>Configuration</em>. Click <em>Insert</em> to add new wildcard map.</p>
<ul>
<li>Executable - \Microsoft.NET\Framework\<.Net
Framework Version>\aspnet_isapi.dll</li>
<li><strong>Verify that file exists - Unchecked</strong></li>
</ul>
<p><img src="https://i.stack.imgur.com/ZB0Zp.gif" alt="enter image description here"></p>
<p>On <em>Home Directory</em> tab of your application properties set <em>Execute permissions</em> to <em>Scripts only</em> and allow reads.</p>
<p>Here is the web.config example: <a href="http://www.webdavsystem.com/server/prev/v2/documentation/hosting_iis_asp_net/webconfig_example" rel="noreferrer">http://www.webdavsystem.com/server/prev/v2/documentation/hosting_iis_asp_net/webconfig_example</a></p>
<p>Please note that this web.config example was specifically created and tested with ASP.NET 2.0 on IIS 6 on Server 2003 and IIS 5.1 on XP. It does not handle &, %, + and trailing dots (.). </p>
<p>ASP.NET 4.x provides means for handling any special characters in your WebDAV server, <a href="http://www.webdavsystem.com/server/documentation/special_characters_asp_net_iis" rel="noreferrer">configuring web.config</a>, including &, % and '.'. The web.config that supports IIS versions 6-8 is generated by <a href="http://www.webdavsystem.com/server" rel="noreferrer">IT Hit WebDAV Server Engine Wizard</a>.</p> |
857,198 | HtmlAgilityPack selecting childNodes not as expected | <p>I am attempting to use the HtmlAgilityPack library to parse some links in a page, but I am not seeing the results I would expect from the methods. In the following I have a <code>HtmlNodeCollection</code> of links. For each link I want to check if there is an image node and then parse its <code>attributes</code> but the <code>SelectNodes</code> and <code>SelectSingleNode</code> methods of <code>linkNode</code> seems to be searching the parent document not the <code>childNodes</code> of <code>linkNode</code>. What gives?</p>
<pre><code>HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(content);
HtmlNodeCollection linkNodes = htmldoc.DocumentNode.SelectNodes("//a[@href]");
foreach(HtmlNode linkNode in linkNodes)
{
string linkTitle = linkNode.GetAttributeValue("title", string.Empty);
if (linkTitle == string.Empty)
{
HtmlNode imageNode = linkNode.SelectSingleNode("/img[@alt]");
}
}
</code></pre>
<p>Is there any other way I could get the alt attribute of the image childnode of linkNode if it exists?</p> | 857,250 | 3 | 0 | null | 2009-05-13 10:29:06.453 UTC | 5 | 2022-09-09 19:22:29.437 UTC | 2022-09-09 19:22:29.437 UTC | null | 4,925,121 | null | 32,021 | null | 1 | 41 | c#|.net|asp.net|xpath|html-agility-pack | 24,901 | <p>You should remove the forwardslash prefix from "/img[@alt]" as it signifies that you want to start at the root of the document.</p>
<pre><code>HtmlNode imageNode = linkNode.SelectSingleNode("img[@alt]");
</code></pre> |
39,491,675 | Runtime issues with iOS 10/XCode 8 | <p>Since I built and started running app on iOS 10 simulator, I started getting logs such as :</p>
<pre><code>objc[6880]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x120275910) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x12009f210). One of the two will be used. Which one is undefined.
2016-09-14 17:18:55.812525 MyApp[6880:340725] bundleid: com.MyApps.MyApp, enable_level: 0, persist_level: 0, propagate_with_activity: 0
2016-09-14 17:18:55.813154 MyApp[6880:340725] subsystem: com.apple.siri, category: Intents, enable_level: 1, persist_level: 1, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
2016-09-14 17:18:55.842900 MyApp[6880:340837] subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-09-14 17:18:55.843428 MyApp[6880:340837] subsystem: com.apple.UIKit, category: HIDEventIncoming, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-09-14 17:18:55.855848 MyApp[6880:340836] subsystem: com.apple.BaseBoard, category: MachPort, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
2016-09-14 17:18:55.870530 MyApp[6880:340725] subsystem: com.apple.UIKit, category: StatusBar, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
</code></pre>
<p>Wonder how I fix them ? I never saw these on XCode 7.</p> | 39,493,523 | 2 | 0 | null | 2016-09-14 13:24:32.483 UTC | 5 | 2016-09-21 12:10:47.66 UTC | 2016-09-17 08:43:12.937 UTC | null | 1,391,249 | null | 917,521 | null | 1 | 34 | xcode|ios-simulator|ios10|xcode8 | 7,371 | <p>I have the same issue, but there is something you can do to,<br></p>
<p>1) Go in Product -> Scheme -> Edit Scheme<br>
2) Run Section on the left, select Argument Tab and in Environment Variable put this.</p>
<blockquote>
<p>OS_ACTIVITY_MODE to value : disable.</p>
</blockquote>
<p>For more information please find the below screenshot.</p>
<p><a href="https://i.stack.imgur.com/OToVc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OToVc.png" alt="enter image description here"></a></p>
<p>This will get rid of messages in the console. </p>
<p>But I still struggle with the <code>PLBuildVersion</code> is implemented in both....</p>
<p>I hope this helps you !</p>
<p>*** EDIT ****<br>
I found that the issue was caused by <code>Facebook SDK</code>. I removed the framework from <code>CocoaPods</code>, installed it manually by copying the SDK in my project folder and I have no errors now. </p> |
6,806,063 | Range based paging mongodb | <p>on the mongodb docs it says:
<a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D">(source)</a></p>
<blockquote>
<p>Unfortunately skip can be (very) costly and requires the server to
walk from the beginning of the collection, or index, to get to the
offset/skip position before it can start returning the page of data
(limit). As the page number increases skip will become slower and more
cpu intensive, and possibly IO bound, with larger collections. Range
based paging provides better use of indexes but does not allow you to
easily jump to a specific page.</p>
</blockquote>
<p>What is range based paging and where is the documentation for it?</p> | 6,806,285 | 1 | 0 | null | 2011-07-24 09:37:17.577 UTC | 10 | 2012-01-08 16:17:01.053 UTC | 2012-01-08 16:17:01.053 UTC | null | 282,773 | null | 663,447 | null | 1 | 11 | mongodb|pagination|paging | 6,526 | <p>The basic idea is to write the paging into the query predicate pattern.</p>
<p>For example if you list forum posts by date and you want to show the next page then use the date of the last post on the current page as a predicate. MongoDB can use the index built on the date field.</p>
<pre><code>//older posts
db.forum_posts.find({date: {$lt: ..last_post_date..} }).sort({date: -1}).limit(20);
</code></pre>
<p>Of course this gets a little more complicated if the field you are using for sorting is not unique.</p> |
55,054,337 | Cypress: run only one test | <p>I want to toggle only running one test, so I don't have to wait for my other tests to see the result of one test.</p>
<p>Currently, I comment out my other tests, but this is really annoying.</p>
<p>Is there a way to toggle only running one test in <code>Cypress</code>?</p> | 55,054,363 | 11 | 2 | null | 2019-03-07 23:14:51.13 UTC | 23 | 2022-01-15 20:52:01.637 UTC | 2022-01-15 20:52:01.637 UTC | user17870265 | null | null | 9,355,411 | null | 1 | 197 | javascript|automated-tests|cypress|e2e-testing | 125,151 | <h3>to run only one file</h3>
<pre class="lang-sh prettyprint-override"><code>cypress run --spec path/to/file.spec.js
</code></pre>
<p>or using glob patterns:</p>
<pre class="lang-sh prettyprint-override"><code>cypress run --spec 'path/to/files/*.spec.js'
</code></pre>
<blockquote>
<p>Note: you need to <strong>wrap your glob patterns in single quotes</strong> to avoid shell expansion!</p>
</blockquote>
<h3>to run only one test in a file</h3>
<p>You can use a <code>.only</code> as described in <a href="https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests.html#Excluding-and-Including-Tests" rel="noreferrer">the Cypress docs</a></p>
<pre class="lang-js prettyprint-override"><code>it.only('only run this one', () => {
// similarly use it.skip(...) to skip a test
})
it('not this one', () => {
})
</code></pre>
<p>Also, you can do the same with <code>describe</code> and <code>context</code> blocks</p>
<h3>edit:</h3>
<p>there's also a nice <code>VSCode</code> extension to make adding/removing <code>.only</code>'s easier with keyboard shortcuts. It's called Test Utils (install with <code>ext install chrisbreiding.test-utils</code>). It works with js, coffee, and typescript:</p>
<p><a href="https://i.stack.imgur.com/2cKuQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2cKuQ.png" alt="enter image description here" /></a></p> |
20,199,334 | How to go to previous commits in eclipse and egit | <p>I have a git android project managed in eclipse and some times i want to temporarily roll back my android project to a specific time and then build it and do stuff and then restore to the latest version.
How is this possible?</p> | 20,200,282 | 1 | 0 | null | 2013-11-25 17:25:51.157 UTC | 5 | 2018-09-13 06:10:03.497 UTC | null | null | null | null | 623,694 | null | 1 | 22 | eclipse|git|egit | 46,527 | <p>To check out an old state:</p>
<ol>
<li>Open the <em>History</em> view for the repository (Window > Show view > Other... > Team > History)</li>
<li>Select the commit at the time you want</li>
<li>Context menu > <em>Checkout</em></li>
</ol>
<p>When you want to go back, just select the commit where master is (or the branch you were working on before) and select <em>Checkout</em> again. Because there is a branch there, it will automatically check out the branch instead of the commit.</p>
<p>Note that you may also have to enable "Show All Branches and Tags" in the history to see master in the history view, see the <a href="https://wiki.eclipse.org/EGit/User_Guide#All_Branches" rel="noreferrer">section in the user guide about this</a>.</p> |
6,180,077 | jQuery save local variable for use later on in the code | <p>Is there anyway that I can save or access a local variable outside of it's function? Consider the code below:</p>
<pre><code>$( "#droppable2" ).droppable({
activeClass: "ui-state-hover",
hoverClass: "ui-state-active",
accept: "#draggable3",
drop: function( event, ui ) {
jdc = $(this).attr("id"); //I need to use this value later
$( this )
.addClass( "ui-state-highlight" );
var x = ui.helper.clone();
x.appendTo('body');
var jdi = $("img").attr("id");// I need to use this value later
$(this).droppable( 'disable' );
}
});
</code></pre>
<p>Is there anyway to get the values of the two variables (jdc and jdi above) for later use outside of the function?</p>
<p>The ultimate goal is to get id of droppable container and content of dropped element.</p> | 6,180,158 | 3 | 4 | null | 2011-05-30 19:30:58.967 UTC | 3 | 2017-12-12 15:41:46.233 UTC | 2017-12-12 15:41:46.233 UTC | null | 472,495 | null | 776,707 | null | 1 | 14 | javascript|jquery|variables|get|local | 54,089 | <p>try this:</p>
<pre><code>jQuery(element).data(key,value);
// Store arbitrary data associated with the matched elements.
</code></pre>
<p>or declare your variable outside the function.</p>
<pre><code>var example;
function abc(){
example = "12345";
}
abc();
console.log(example);
</code></pre> |
5,670,416 | Is there an online tool to build simple tables and test SQL statements? | <p>I want to be able to create simple tables and run SQL queries on them. I'm talking tables with fewer than 12 items. Is there an online tool to do this? This might seem crazy, but it'd really help as I go between 3-4 computers a day.</p>
<p>Example:</p>
<pre><code>Cats
Cat Names | Age
Marsha | 5
Melon | 3
Select * from Cats where Age > 3
Marsha | 5
</code></pre>
<p>Obviously that's a very, very simple example ... but I'm looking more towards testing some trickier SQL statements.</p>
<p>Edit: Not doing support. Right now I'm doing training and presentations. Screen sharing is not an option.</p> | 5,670,448 | 3 | 6 | null | 2011-04-14 22:24:05 UTC | 11 | 2018-11-03 20:35:38.26 UTC | 2011-04-14 22:53:31.327 UTC | null | 647,249 | null | 647,249 | null | 1 | 25 | sql | 64,120 | <p>I just found this tool today:</p>
<p><a href="http://ideone.com/clone/W4ePc" rel="nofollow noreferrer">ideone</a></p>
<p>It lets you choose from a number of languages (including SQL), write your code and then execute it. Pretty cool</p>
<p>Thanks to <a href="https://stackoverflow.com/users/632736/freeasinbeer">FreeAsInBeer</a> for pointing me towards it.</p> |
5,842,487 | Python scripts in HTML | <p>Is it possible to write <code>Python</code> scripts in HTML code similarly as you write PHP between <code><?php ... ?></code> tags?</p>
<p>I'd like to achieve that my <code>Python</code> application will run in the browser.</p>
<p>thank you for help</p> | 5,842,533 | 5 | 1 | null | 2011-04-30 14:47:12.46 UTC | 3 | 2019-07-22 01:41:08.367 UTC | 2013-08-19 18:08:09.447 UTC | null | 653,379 | null | 653,379 | null | 1 | 9 | python|html | 49,639 | <p>PHP doesn't run in the browser, as it is a server side language. You could try <a href="http://www.skulpt.org/" rel="noreferrer">Skulpt</a> to try to run python in the browser.</p> |
52,690,296 | "Missing autofillHints attribute" | <p>I have an issue with <code>Palette -> Text</code><br>
When I want to set some view, I receive a message problem <code>"Missing autofillHints attribute"</code><br>
Any suggestions? </p> | 52,690,434 | 3 | 1 | null | 2018-10-07 15:58:01.683 UTC | 9 | 2021-07-02 03:14:55.397 UTC | 2019-02-13 13:46:08.023 UTC | null | 1,824,361 | null | 10,469,369 | null | 1 | 125 | android | 111,504 | <p>Perhaps you are using an <code>EditText</code>. <a href="https://developer.android.com/reference/android/view/View.html#attr_android:autofillHints" rel="noreferrer"><strong><code>autofillHints</code></strong></a> is used in API 26 and above for filling empty <code>EditText</code>s and it's actually suggesting which type of content should be placed in there.</p>
<p>Just add :</p>
<pre><code>android:autofillHints="username" // the type of content you want
</code></pre>
<p>To your <code>EditText</code> and warning will disappear. </p>
<blockquote>
<p>You do this using the new <code>android:autofillHints</code> attribute to tell
<code>autofill</code> <strong><em>what type of content you expect</em></strong>, and
<code>android:importantForAutofill</code> to tell <code>autofill</code> which views you want (or
do not want) to be filled.</p>
</blockquote>
<p><strong>Read:</strong> <a href="https://medium.com/@bherbst/getting-androids-autofill-to-work-for-you-21435debea1" rel="noreferrer">https://medium.com/@bherbst/getting-androids-autofill-to-work-for-you-21435debea1</a></p>
<p><strong>And this:</strong> <a href="https://developer.android.com/guide/topics/text/autofill-services" rel="noreferrer">https://developer.android.com/guide/topics/text/autofill-services</a></p>
<hr>
<p><strong>Edit:</strong></p>
<p>You can however set:</p>
<pre><code>android:importantForAutofill="no"
</code></pre>
<p>To the component to tell it is not important to fill and get rid of the error.</p> |
34,509,103 | Vue components communication | <p>I have two Vue components:</p>
<pre><code>Vue.component('A', {});
Vue.component('B', {});
</code></pre>
<p>How can I access component A from component B? How does the communication work between the components?</p> | 34,512,330 | 6 | 1 | null | 2015-12-29 10:28:01.133 UTC | 8 | 2022-07-15 20:30:42.197 UTC | 2017-01-26 20:09:03.483 UTC | null | 6,311,455 | null | 5,653,901 | null | 1 | 34 | javascript|vue.js | 15,351 | <p>Cross-component communication doesn't get much attention in the Vue.js docs, nor are there many tutorials that cover this subject. As components should be isolated, you should never "access" a component directly. This would tightly couple the components together, and thats exactly what you want to prevent doing.</p>
<p>Javascript has an excellent method for communication: events. Vue.js has a built-in event system, mainly used for parent-child communication. <a href="http://012.vuejs.org/guide/components.html#Event_System" rel="noreferrer">From the docs</a>:</p>
<blockquote>
<p>Although you can directly access a Vue instance’s children and parent, it is more convenient to use the built-in event system for cross-component communication. It also makes your code less coupled and easier to maintain. Once a parent-child relationship is established, you can dispatch and trigger events using each component’s event instance methods.</p>
</blockquote>
<p>Their example code to illustrate the event system:</p>
<pre><code>var parent = new Vue({
template: '<div><child></child></div>',
created: function () {
this.$on('child-created', function (child) {
console.log('new child created: ')
console.log(child)
})
},
components: {
child: {
created: function () {
this.$dispatch('child-created', this)
}
}
}
}).$mount()
</code></pre>
<p>Dan Holloran has recently written a piece on his "struggle" with cross-component messaging, in <a href="https://danholloran.me/blog/2015/12/07/vues-js-component-messaging/" rel="noreferrer">two</a> <a href="https://danholloran.me/blog/2015/12/08/vues-js-component-messaging-continued/" rel="noreferrer">pieces</a>. This might be helpful to you if you need communication between components that have no parent-child relationship.</p>
<p>Another approach I have experience with (other than using events for communication), is using a central component registry that has a reference to the public API with an instance of a component bound to it. The registry handles requests for a component and returns its public API.</p>
<p>In the context of Vue.js, events would by my weapon of choice.</p> |
1,468,394 | Keep a reference to a file after it has moved in objective-c? | <p>I have a Cocoa application that stores a reference to multimedia files (images, videos, etc) on the user's computer. I'm wondering if there is a way to get a reference to that file other that using a file path so that if the user moves that file to a different folder on their computer, I would still know where it is. I'm currently storing the array of file paths that are passed back from the standard Cocoa open dialogue:</p>
<pre><code>-(void)addMultimediaDidEnd:(NSOpenPanel*)sheet
returnCode:(int)returnCode
contextInfo:(NSString *)contextInfo
{
if(returnCode == NSOKButton) {
[sheet orderOut:nil];
[self saveFiles:[sheet filenames]];
}
}
</code></pre> | 1,469,016 | 2 | 0 | null | 2009-09-23 20:41:28.49 UTC | 12 | 2011-02-09 19:04:38.727 UTC | null | null | null | null | 32,854 | null | 1 | 14 | objective-c|cocoa|filesystems | 3,507 | <p>In OS X 10.6 (Snow Leopard), an <code>NSURL</code> can be converted to a file reference URL (using <code>-[NSURL fileReferenceURL]</code>) which references a file across moves while your application is running. If you want to persist this file reference, use <code>+[NSURL writeBookmarkData:toURL:options:error:]</code> passing the bookmark data generated with <code>-[NSURL bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error]</code>. The bookmark can be resolved later with <code>+[NSURL URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:]</code> passing the bookmark data returned from <code>+[NSURL bookmarkDataWithContentsOfURL:error:]</code>.</p>
<p>Prior to OS X 10.6, the same functionality (minus some network aware niceties) is available via the AliasManager, a Carbon-era interface to the OS X file alias system. There are a couple of Objective-C wrappers on top of the Alias Manager that make using it from Cocoa much nicer. My favorite is Wolf Rentzsch's additions to Chris Hanson's <code>BDAlias</code> (available on <a href="http://github.com/rentzsch/bdalias" rel="noreferrer">github</a>).</p> |
5,951,552 | Basic HTTP authentication in Node.JS? | <p>I'm trying to write a REST-API server with NodeJS like the one used by <a href="http://api.no.de" rel="noreferrer">Joyent</a>, and everything is ok except I can't verify a normal user's authentication. If I jump to a terminal and do <code>curl -u username:password localhost:8000 -X GET</code>, I can't get the values username:password on the NodeJS http server. If my NodeJS http server is something like </p>
<pre><code>var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
</code></pre>
<p>, shouldn't I get the values username:password somewhere in the <strong>req</strong> object that comes from the callback ?
How can I get those values without having to use <a href="http://senchalabs.github.com/connect/middleware-basicAuth.html" rel="noreferrer">Connect's basic http auth</a> ?</p> | 5,957,629 | 7 | 3 | null | 2011-05-10 14:23:26.503 UTC | 32 | 2022-01-31 06:02:31.513 UTC | 2011-05-10 15:02:41.94 UTC | null | 213,269 | null | 618,756 | null | 1 | 51 | http|authentication|node.js|basic-authentication | 77,463 | <p>The username:password is contained in the Authorization header <em>as a base64-encoded string</em>.</p>
<p>Try this:</p>
<pre><code>const http = require('http');
http.createServer(function (req, res) {
var header = req.headers.authorization || ''; // get the auth header
var token = header.split(/\s+/).pop() || ''; // and the encoded auth token
var auth = Buffer.from(token, 'base64').toString(); // convert from base64
var parts = auth.split(/:/); // split on colon
var username = parts.shift(); // username is first
var password = parts.join(':'); // everything else is the password
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('username is "' + username + '" and password is "' + password + '"');
}).listen(1337, '127.0.0.1');
</code></pre>
<p>From <a href="http://www.ietf.org/rfc/rfc2617.txt" rel="noreferrer">HTTP Authentication: Basic and Digest Access Authentication - Part 2 Basic Authentication Scheme (Pages 4-5)</a></p>
<p><em>Basic Authentication in Backus-Naur Form</em></p>
<pre><code>basic-credentials = base64-user-pass
base64-user-pass = <base64 [4] encoding of user-pass,
except not limited to 76 char/line>
user-pass = userid ":" password
userid = *<TEXT excluding ":">
password = *TEXT
</code></pre> |
17,964,830 | Where is the default "Welcome Aboard" page located in my app? | <p>I scoured my app's directories, and I can't find the html page for the default rails Welcome Aboard page. I also cannot find a route for the default Welcome Aboard page in routes.rb. How does my rails app route <code>http://localhost:3000/</code> to a non-existent page in my app?</p>
<p>The rails server produces this information:</p>
<pre><code>Started GET "/" for 127.0.0.1 at 2013-07-31 02:00:13 -0600
Processing by Rails::WelcomeController#index as HTML
Rendered /Users/7stud/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/railties-4.0.0/lib/rails/templates/rails/welcome/index.html.erb (0.1ms)
Completed 200 OK in 3ms (Views: 2.5ms | ActiveRecord: 0.0ms)
</code></pre>
<p>So it looks to me like there is a controller buried in a gem somewhere that handles the request.</p> | 17,965,106 | 1 | 1 | null | 2013-07-31 08:03:54.523 UTC | 8 | 2017-06-20 20:02:03.04 UTC | 2017-06-20 20:02:03.04 UTC | null | 926,143 | null | 926,143 | null | 1 | 57 | ruby-on-rails|ruby-on-rails-4 | 26,808 | <p>Since Rails 4, the "Welcome aboard" page is no longer located in <code>public/index.html</code>. It is - as you've already detected - located inside one of the Rails gems.</p>
<p>So you already answered the question yourself; the "Welcome aboard" page is - in your case - located at <code>/Users/7stud/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/railties-4.0.0/lib/rails/templates/rails/welcome/index.html.erb</code></p>
<p>To get rid of it, following the instructions on the page. Basically they are:</p>
<ol>
<li>Create a controller</li>
<li>Add a root route in <code>config/routes.rb</code> to route to that newly created controller.</li>
</ol>
<p>As for how the request to your application ends up at a controller inside railties, let's dig into the gem: Inside <a href="https://github.com/rails/rails/blob/master/railties/lib/rails/application/finisher.rb"><code>Rails::Application::Finisher</code></a> we find this:</p>
<pre><code>initializer :add_builtin_route do |app|
if Rails.env.development?
app.routes.append do
get '/rails/info/properties' => "rails/info#properties"
get '/rails/info/routes' => "rails/info#routes"
get '/rails/info' => "rails/info#index"
get '/' => "rails/welcome#index"
end
end
end
</code></pre>
<p>This block adds a few routes to your application when running in development mode - one of those is the route to the "Welcome aboard" action: <code>get '/' => "rails/welcome#index"</code></p>
<p>This - like any other initializer - is done when your start your application server (running <code>rails server</code> or however you do it). In the case of <code>Finisher</code>, all its initializer are run after all other initializers are run.</p>
<p>Note how the routes are appended so that they are appear last in the Routeset. This, combined with the fact that Rails uses the first matching route it finds, ensures those default routes will only get used if no other route is defined.</p> |
13,912,694 | Autosys Command List and Job Scheduling every half an hour | <p>Where can I find all the command list for Autosys JIL. What is the official site where I can get the complete list of Autosys commands with examples ?</p>
<p>For example I want to run a shell script every half an hour everyday of the week. </p> | 15,540,280 | 3 | 0 | null | 2012-12-17 10:51:09.743 UTC | null | 2017-12-19 21:30:07.513 UTC | null | null | null | null | 672,736 | null | 1 | 2 | autosys | 57,899 | <p>Specify the start time as 0, 30 which means every 30 mins and days of week as all as you want the job to run everyday</p>
<pre><code>/* ----------------- template ----------------- */
insert_job: template job_type: c
box_name: box1
command: ls -l
machine: localhost
owner: lyota01@TANT-A01
permission: gx,ge,wx,we,mx,me
date_conditions: 1
days_of_week: all
start_times: 0,30
</code></pre> |
25,020,582 | Scrolling to an Anchor using Transition/CSS3 | <p>I have a series of links which are using an anchor mechanism:</p>
<pre><code><div class="header">
<p class="menu"><a href="#S1">Section1</a></p>
<p class="menu"><a href="#S2">Section2</a></p>
...
</div>
<div style="width: 100%;">
<a name="S1" class="test">&nbsp;</a>
<div class="curtain">
Lots of text
</div>
<a name="S2" class="test">&nbsp;</a>
<div class="curtain">
lots of text
</div>
...
</div>
</code></pre>
<p>I am using the following CSS:</p>
<pre><code>.test
{
position:relative;
margin: 0;
padding: 0;
float: left;
display: inline-block;
margin-top: -100px; /* whatever offset this needs to be */
}
</code></pre>
<p>It's working fine. But of course, it's jumping from one section to the next when we click on the link. So I'd like to have a smooth transition, using a scroll of some sort to the start of selected
section.</p>
<p>I think I read on Stackoverflow that this is not possible (yet) with CSS3 but I'd like a confirmation and also I'd like to know what 'could' be the solution. I am happy to use JS but I can't use jQuery. I tried to use an on click function on the link, retrieve the "vertical position" of the div that needs to be displayed but I was unsuccessful. I am still learning JS and don't know it well enough to come up with a solution of my own.</p>
<p>Any help/ideas would be greatly appreciated.</p> | 25,036,794 | 10 | 1 | null | 2014-07-29 16:41:00.14 UTC | 26 | 2021-09-24 12:45:39.813 UTC | null | null | null | null | 1,794,325 | null | 1 | 52 | html|css | 232,142 | <p>While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.</p>
<p>So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:</p>
<p>HTML</p>
<pre><code><div class="header">
<p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
<p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
<p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
<p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
<div id="S1" class="curtain">
blabla
</div>
<div id="S2" class="curtain">
blabla
</div>
<div id="S3" class="curtain">
blabla
</div>
<div id="S4" class="curtain">
blabla
</div>
</div>
</code></pre>
<p><strong>NOTE THE "RETURN FALSE;" in the on click call.</strong> This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).</p>
<p>JS code:</p>
<pre><code><script>
function scrollTo(to, duration) {
if (document.body.scrollTop == to) return;
var diff = to - document.body.scrollTop;
var scrollStep = Math.PI / (duration / 10);
var count = 0, currPos;
start = element.scrollTop;
scrollInterval = setInterval(function(){
if (document.body.scrollTop != to) {
count = count + 1;
currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
document.body.scrollTop = currPos;
}
else { clearInterval(scrollInterval); }
},10);
}
function test(elID)
{
var dest = document.getElementById(elID);
scrollTo(dest.offsetTop, 500);
}
</script>
</code></pre>
<p>It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.</p>
<p>Thanks everyone for your help.</p>
<p>Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.</p> |
27,522,563 | Why StringJoiner when we already have StringBuilder? | <p>I recently encountered with a Java 8 class <a href="https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html" rel="noreferrer"><code>StringJoiner</code></a> which adds the String using the delimiters and adds prefix and suffix to it, but I can't understand the need of this class as it also uses <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html" rel="noreferrer"><code>StringBuilder</code></a> at the backend and also performs very simple operation of appending the Strings.</p>
<p>Am I missing something by not actually understanding the real purpose of this class?</p> | 27,522,845 | 5 | 1 | null | 2014-12-17 09:45:31.693 UTC | 15 | 2020-04-29 05:20:25.837 UTC | 2018-06-25 20:44:52.467 UTC | null | 49,678 | null | 3,992,420 | null | 1 | 75 | java|string|java-8|stringbuilder | 47,275 | <p><code>StringJoiner</code> is very useful, when you need to join Strings in a <code>Stream</code>.</p>
<p>As an example, if you have to following List of Strings:</p>
<pre><code>final List<String> strings = Arrays.asList("Foo", "Bar", "Baz");
</code></pre>
<p>It is much more simpler to use</p>
<pre><code>final String collectJoin = strings.stream().collect(Collectors.joining(", "));
</code></pre>
<p>as it would be with a <code>StringBuilder</code>:</p>
<pre><code>final String collectBuilder =
strings.stream().collect(Collector.of(StringBuilder::new,
(stringBuilder, str) -> stringBuilder.append(str).append(", "),
StringBuilder::append,
StringBuilder::toString));
</code></pre>
<p><strong>EDIT 6 years later</strong>
As noted in the comments, there are now much simpler solutions like <code>String.join(", ", strings)</code>, which were not available back then. But the use case is still the same.</p> |
27,776,129 | PHP cURL: CURLOPT_CONNECTTIMEOUT vs CURLOPT_TIMEOUT | <p>PHP has these two options related to timeout: <code>CURLOPT_CONNECTTIMEOUT</code> and <code>CURLOPT_TIMEOUT</code>.</p>
<p>The descriptions on the PHP site are a bit vague. What's the difference?</p>
<p>To use a real world example: say you're sending GET vars to a URL via cURL and you want to receive a XML back, would <code>CURLOPT_CONNECTTIMEOUT</code> relate to the maximum amount of time it can take to connect to the server and <code>CURLOPT_TIMEOUT</code> the maximum amount of time it can take to send the XML back?</p> | 27,776,164 | 5 | 2 | null | 2015-01-05 08:58:05.7 UTC | 9 | 2022-08-18 12:09:42.517 UTC | null | null | null | null | 2,338,825 | null | 1 | 47 | php|curl | 73,775 | <blockquote>
<p>CURLOPT_CONNECTTIMEOUT is the maximum amount of time in seconds that is allowed to make the connection to the server.
It can be set to 0 to disable this limit, but this is inadvisable in a production environment.</p>
<p>CURLOPT_TIMEOUT is a maximum amount of time in seconds to which the execution of individual cURL extension function calls will be limited.
Note that the value for this setting should include the value for CURLOPT_CONNECTTIMEOUT.</p>
<p>In other words,
CURLOPT_CONNECTTIMEOUT is a segment of the time represented by CURLOPT_TIMEOUT, so the value of the CURLOPT_TIMEOUT should be greater than the value of the CURLOPT_CONNECTTIMEOUT.</p>
</blockquote>
<p>From <a href="http://altafphp.blogspot.in/2012/12/difference-between-curloptconnecttimeou.html">Difference between CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT</a></p> |
44,790,923 | Docker Compose + Spring Boot + Postgres connection | <p>I have a Java Spring Boot app which works with a Postgres database. I want to use Docker for both of them. I initially put just the Postgres in Docker, and I had a <code>docker-compose.yml</code> file defined like this:</p>
<pre><code>version: '2'
services:
db:
container_name: sample_db
image: postgres:9.5
volumes:
- sample_db:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=sample
- POSTGRES_USER=sample
- POSTGRES_DB=sample
- PGDATA=/var/lib/postgresql/data/pgdata
ports:
- 5432:5432
volumes:
sample_db: {}
</code></pre>
<p>Then, when I issued the commands <code>sudo dockerd</code> and <code>sudo docker-compose -f docker-compose.yml up</code>, it was starting the database. I could connect using <code>pgAdmin</code> for example, by using <code>localhost</code> as server and port <code>5432</code>. Then, in my Spring Boot app, inside the <code>application.properties</code> file I defined the following properties.</p>
<pre><code>spring.datasource.url=jdbc:postgresql://localhost:5432/sample
spring.datasource.username=sample
spring.datasource.password=sample
spring.jpa.generate-ddl=true
</code></pre>
<p>At this point I could run my Spring Boot app locally through Spring Suite, and it all was working fine. Then, I wanted to also add my Spring Boot app as Docker image. I first of all created a Dockerfile in my project directory, which looks like this:</p>
<pre><code>FROM java:8
EXPOSE 8080
ADD /target/manager.jar manager.jar
ENTRYPOINT ["java","-jar","manager.jar"]
</code></pre>
<p>Then, I entered to the directory of the project issued <code>mvn clean</code> followed by <code>mvn install</code>. Next, issued <code>docker build -f Dockerfile -t manager .</code> followed by <code>docker tag 9c6b1e3f1d5e myuser/manager:latest</code> (the id is correct). Finally, I edited my existing <code>docker-compose.yml</code> file to look like this:</p>
<pre><code>version: '2'
services:
web:
image: myuser/manager:latest
ports:
- 8080:8080
depends_on:
- db
db:
container_name: sample_db
image: postgres:9.5
volumes:
- sample_db:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=sample
- POSTGRES_USER=sample
- POSTGRES_DB=sample
- PGDATA=/var/lib/postgresql/data/pgdata
ports:
- 5432:5432
volumes:
sample_db: {}
</code></pre>
<p>But, now if I issue <code>sudo docker-compose -f docker-compose.yml up</code> command, the database again starts correctly, but I get errors and exit code 1 for the web app part. The problem is the connection string. I believe I have to change it to something else, but I don't know what it should be. I get the following error messages:</p>
<pre><code>web_1 | 2017-06-27 22:11:54.418 ERROR 1 --- [ main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
web_1 |
web_1 | org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
</code></pre>
<p>Any ideas?</p> | 44,791,825 | 4 | 1 | null | 2017-06-27 22:28:15.97 UTC | 10 | 2022-05-01 00:09:45.407 UTC | null | null | null | null | 6,360,938 | null | 1 | 26 | spring|postgresql|docker|docker-compose|dockerfile | 37,490 | <p>Each container has its own network interface with its own localhost. So change how Java points to Postgres: </p>
<pre><code>spring.datasource.url=jdbc:postgresql://localhost:5432/sample
</code></pre>
<p>To:</p>
<pre><code>spring.datasource.url=jdbc:postgresql://db:5432/sample
</code></pre>
<p><code>db</code> will resolve to the proper Postgres IP.</p>
<hr>
<p>Bonus. With docker-compose you don't need to build your image by hand. So change:</p>
<pre><code>web:
image: myuser/manager:latest
</code></pre>
<p>To:</p>
<pre><code>web:
build: .
</code></pre> |
32,945,099 | How to detect current slide in swiper js? | <p>Working with swiper js for a slider and want to detect the current image/slide. how i can detect with HTML and JS? any idea?</p>
<pre><code><div class="swiper-container">
<div class="swiper-wrapper" align="center">
<div class="swiper-slide">
<img src="images/card_gold.png" width="80%" align="middle" onclick="desc(\'' + card1 + '\')">
</div>
<div class="swiper-slide">
<img src="images/card_platinum.png" width="80%" align="middle" onclick="desc(\'' + card2 + '\')">
</div>
<div class="swiper-slide">
<img src="images/card_silver.png" width="80%" align="middle" onclick="desc(\'' + card3 + '\')">
</div>
</div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</code></pre> | 40,258,570 | 5 | 2 | null | 2015-10-05 09:22:26.23 UTC | 7 | 2022-09-13 07:53:41.33 UTC | 2015-10-05 09:23:54.577 UTC | null | 2,025,923 | null | 3,665,010 | null | 1 | 17 | javascript|swiper.js | 95,644 | <p>its very easy. just use this:</p>
<pre><code>swiper.activeIndex
</code></pre> |
9,358,643 | How to pop up a select list, and update the site with the selection? | <p>I have some text in a DIV container. When the user clicks that text, i would like to have a selection list poppup. When the user chooses a value from the selection list, and clicks a save button, the DIV container should be updated with the text from the selection list.</p>
<p>How should i approach this? Im not sure how to make the selection list pop up. If i make it pop up in a new tab, how can i save it on the previous site?</p>
<p>Thanks</p> | 9,358,734 | 2 | 0 | null | 2012-02-20 09:18:47.297 UTC | 4 | 2015-06-05 08:50:50.46 UTC | null | null | null | null | 915,414 | null | 1 | 6 | javascript|jquery|html | 42,789 | <p>If you are familiar with jQuery you can use a plugin, which is called <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow">Jeditable</a>, it is powerful and you can make amazing things with it.</p>
<p>Here is some example code:</p>
<pre><code><div class="edit" id="div_1">Dolor</div>
<div class="edit_area" id="div_2">Lorem ipsum dolor sit amet, consectetuer
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore
magna aliquam erat volutpat.</div>
</code></pre>
<p>There is only one mandatory parameter. URL where browser posts edited content.</p>
<pre><code>$(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
</code></pre>
<p><em>Code above does several things:</em> Elements with class <code>.edit</code> become editable. Editing starts with single mouse click. Form input element is text. Width and height of input element matches the original element. If users clicks outside form changes are discarded. Same thing happens if users hits <code>ESC</code>. When user hits <code>ENTER</code> browser submits text to <code>save.php</code> at <code>www.example.com</code>.</p>
<p>When submitting change, following data will be <code>POST</code>:ed to server:
<code>id=elements_id&value=user_edited_content</code></p> |
9,311,570 | HTML5 video seeking | <p>How can I get my video player to skip/seek to a certain time. I have had a go at this and it works when the page first loads (In Chrome) but not in any other browser. I also have a flash fallback which could be a pain, but for now the priority is the HTML side of things
The major issue is that it doesn't work outside Chrome! </p>
<p>EDIT: This now works in IE9, Chrome and Firefox. However, not with the flash fallback!</p>
<p>Below is my attempt so far.</p>
<p>I'm using the following JS so far: </p>
<pre><code> <script language="javascript">
$(function () {
var v = $("#video").get(0);
$('#play').click(function(){
v.play();
});
$('.s').click(function(){
alert("Clicked: "+$(this).html() +"- has time of -" + $(this).attr('s') );
v.currentTime = $(this).attr('s'); v.play();
});
});
</script>
</code></pre>
<p>Which links to the following:</p>
<pre><code><video id="video" controls width="500">
<!-- if Firefox -->
<source src="video.ogg" type="video/ogg" />
<!-- if Safari/Chrome-->
<source src="video.mp4" type="video/mp4" />
<!-- If the browser doesn't understand the <video> element, then reference a Flash file. You could also write something like "Use a Better Browser!" if you're feeling nasty. (Better to use a Flash file though.) -->
<object type="application/x-shockwave-flash" data="player.swf"
width="854" height="504">
<param name="allowfullscreen" value="true">
<param name="allowscriptaccess" value="always">
<param name="flashvars" value="file=video.mp4">
<!--[if IE]><param name="movie" value="player.swf"><![endif]-->
<p>Your browser can’t play HTML5 video.</p>
</object>
</video>
</code></pre>
<p>With the context of having buttons with a class <code>s</code> and custom attribute <code>s=60</code> for "60 seconds" etc.</p> | 9,311,671 | 2 | 0 | null | 2012-02-16 12:50:48.07 UTC | 10 | 2018-07-15 06:20:06.03 UTC | 2018-07-15 06:20:06.03 UTC | null | 1,033,581 | null | 934,777 | null | 1 | 14 | javascript|jquery|html|html5-video | 38,021 | <pre><code>seekToTime:function( value )
{
var seekToTime = this.videoPlayer.currentTime + value;
if( seekToTime < 0 || seekToTime > this.videoPlayer.duration )
return;
this.videoPlayer.currentTime = seekToTime;
}
</code></pre>
<p>This is the seek function we are using. It's in MooTools syntax, but you'll get the point. Hope it helps.</p> |
9,437,366 | Entity Framework 4.3 code first multiple many to many using the same tables | <p>I have a model like</p>
<pre><code>public class User
{
[Key]
public long UserId { get; set; }
[Required]
public String Nickname { get; set; }
public virtual ICollection<Town> Residencies { get; set; }
public virtual ICollection<Town> Mayorships { get; set; }
}
</code></pre>
<p>and</p>
<pre><code>public class Town
{
[Key]
public long TownId { get; set; }
[Required]
public String Name { get; set; }
public virtual ICollection<User> Residents { get; set; }
public virtual ICollection<User> Mayors { get; set; }
}
</code></pre>
<p>I was hoping EF would create two many to many relationships using automatically created TownResidents and TownMayors table. I can't seem to find the necessary convention or explicit annotation to get this result.</p>
<p>Instead I am getting two FK UserIds in the Town table and two FK TownIds in the User table. </p>
<p>Any ideas how to get EF to see these at two many to many relationships? </p>
<p>Thanks </p> | 9,439,052 | 1 | 0 | null | 2012-02-24 20:12:00.487 UTC | 10 | 2012-02-24 22:36:40.497 UTC | null | null | null | null | 1,231,545 | null | 1 | 32 | c#|entity-framework|ef-code-first|entity-framework-4.3 | 10,217 | <p>Well, EF doesn't have some kind of word and grammar recognition algorithm which would be required to identify that you (probably) want that <code>User.Residencies</code> and <code>Town.Residents</code> form a pair of navigation properties and <code>User.Mayorships</code> and <code>Town.Mayors</code> form a second pair. Therefore it assumes that you have <em>four</em> one-to-many relationships and that each of the four navigation properties belongs to one of the relationships. (This is the reason for the four foreign keys you have seen in the database tables.)</p>
<p>This standard assumption is not what you want, hence you must define the relationships explicitly to override this standard convention:</p>
<p>Either with data annotations:</p>
<pre><code>public class User
{
[Key]
public long UserId { get; set; }
[Required]
public String Nickname { get; set; }
[InverseProperty("Residents")]
public virtual ICollection<Town> Residencies { get; set; }
[InverseProperty("Mayors")]
public virtual ICollection<Town> Mayorships { get; set; }
}
</code></pre>
<p>Or with Fluent API:</p>
<pre><code>modelBuilder.Entity<User>()
.HasMany(u => u.Residencies)
.WithMany(t => t.Residents)
.Map(x =>
{
x.MapLeftKey("UserId");
x.MapRightKey("TownId");
x.ToTable("TownResidents");
});
modelBuilder.Entity<User>()
.HasMany(u => u.Mayorships)
.WithMany(t => t.Mayors)
.Map(x =>
{
x.MapLeftKey("UserId");
x.MapRightKey("TownId");
x.ToTable("TownMayors");
});
</code></pre>
<p>Fluent API has the advantage that you can control the name of the link table (and the key column names as well). You cannot define those names with data annotations.</p> |
9,314,902 | jQuery: get parent tr for selected radio button | <p>I have the following HTML:</p>
<pre><code><table id="MwDataList" class="data" width="100%" cellspacing="10px">
....
<td class="centerText" style="height: 56px;">
<input id="selectRadioButton" type="radio" name="selectRadioGroup">
</td>
....
</table>
</code></pre>
<p>In other words I have a table with few rows, in each row in the last cell I have a radio button.<br>
How can I get <em>parent</em> row for selected radio button?</p>
<p>What I have tried:</p>
<pre><code>function getSelectedRowGuid() {
var row = $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr");
var guid = GetRowGuid(row);
return guid;
}
</code></pre>
<p>But it seems like this selector is incorrect.</p> | 9,314,949 | 2 | 0 | null | 2012-02-16 16:19:19.77 UTC | 12 | 2018-09-12 10:08:01.207 UTC | 2018-09-12 10:08:01.207 UTC | null | 814,702 | null | 769,557 | null | 1 | 80 | jquery|jquery-selectors|parent|tablerow | 181,050 | <p>Try this.</p>
<p>You don't need to prefix attribute name by <code>@</code> in jQuery selector. Use <code>closest()</code> method to get the closest parent element matching the selector.</p>
<pre><code>$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
</code></pre>
<p>You can simplify your method like this</p>
<pre><code>function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
</code></pre>
<p><code>closest()</code> - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</p>
<p>As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.</p> |
9,381,665 | How can we configure the internal Jackson mapper when using RestTemplate? | <p>I want to update the SerializationConfig.Feature... properties of the jackson mapper used by Spring RestTemplate, Any idea how I can get to it or where I can/should configure it.</p> | 9,381,832 | 5 | 0 | null | 2012-02-21 16:56:00.587 UTC | 21 | 2019-12-05 13:18:40.357 UTC | null | null | null | null | 706,727 | null | 1 | 85 | spring|jackson | 95,589 | <p>The default <code>RestTemplate</code> constructor registers a set of <code>HttpMessageConverter</code>s:</p>
<pre><code>this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter());
this.messageConverters.add(new SourceHttpMessageConverter());
this.messageConverters.add(new XmlAwareFormHttpMessageConverter());
if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jacksonPresent) {
this.messageConverters.add(new MappingJacksonHttpMessageConverter());
}
if (romePresent) {
this.messageConverters.add(new AtomFeedHttpMessageConverter());
this.messageConverters.add(new RssChannelHttpMessageConverter());
}
</code></pre>
<p>The <code>MappingJacksonHttpMessageConverter</code> in turns, creates <code>ObjectMapper</code> instance directly. You can either find this converter and replace <code>ObjectMapper</code> or register a new one before it. This should work:</p>
<pre><code>@Bean
public RestOperations restOperations() {
RestTemplate rest = new RestTemplate();
//this is crucial!
rest.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());
return rest;
}
@Bean
public MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
converter.setObjectMapper(myObjectMapper());
return converter;
}
@Bean
public ObjectMapper myObjectMapper() {
//your custom ObjectMapper here
}
</code></pre>
<p>In XML it is something along these lines:</p>
<pre><code><bean id="restOperations" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<util:list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="customObjectMapper"/>
</bean>
</util:list>
</property>
</bean>
<bean id="customObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
</code></pre>
<p>Note that the transition isn't really 1:1 - I have to explicitly create <code>messageConverters</code> list in XML while with <code>@Configuration</code> approach I could reference existing one and simply modify it. But this should work.</p> |
30,232,346 | 'in' operator in JavaScript. String comparison | <p>Hi I'm new in JavaScript and i find a basic problem:</p>
<p>When I use that piece of code in Python:</p>
<pre><code>'a' in 'aaa'
</code></pre>
<p>I get <code>True</code></p>
<p>When I do the same in JavaScript I get Error:</p>
<pre><code>TypeError: Cannot use 'in' operator to search for 'a' in aaa
</code></pre>
<p>How to get similar result as in Python?</p> | 30,232,372 | 5 | 2 | null | 2015-05-14 08:06:14.227 UTC | 2 | 2018-10-03 06:16:51.52 UTC | 2018-10-03 06:16:51.52 UTC | null | 3,669,624 | null | 3,787,993 | null | 1 | 37 | javascript|string | 4,553 | <p>I think one way is to use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer">String.indexOf()</a></p>
<pre><code>'aaa' .indexOf('a') > -1
</code></pre>
<p>In javascript the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in" rel="noreferrer">in operator</a> is used to check whether an object has a property</p> |
16,789,504 | Printing out 2d array elements in java | <p>I'm trying to print out elements in a 2d array, but can't seem to format it. Anytime I try to format it I get an error</p>
<pre><code> String [][] plants = new String[2][2];
plants[0][0] = "Rose";
plants[0][1] = "Red";
plants[1][0] = "Snowdrop";
plants[1][1] = "White";
//String plant;
//String color;
for (int i = 0; i<2; i++){
for (int j = 0; j<2; j++){
//plant = Arrays.toString(plants[i]);
//color = Arrays.deepToString(plants[j]);
//System.out.println(plant + " " + color);
System.out.println(plants[i][j]);
}
}
</code></pre>
<p>What I have so far prints out each element on an individual line, but I want it to print out like:</p>
<p>Rose Red</p>
<p>Snowdrop White</p>
<p>I've tried the methods commented out, but they won't work right either.</p>
<p>Any suggestions? Thanks</p> | 16,789,550 | 9 | 2 | null | 2013-05-28 10:16:46.207 UTC | 1 | 2018-12-04 12:23:44.517 UTC | null | null | null | null | 2,428,030 | null | 1 | 1 | java | 39,782 | <p>In the inner loop do <code>System.out.print(plants[i][j] + " ");</code></p>
<p>In the outer loop do <code>System.out.println();</code></p> |
7,048,941 | how to use the LightingColorFilter to make the image form dark to light | <p>I want to add light of the image, I want to use <code>LightingColorFilter</code></p>
<pre><code>LightingColorFilter lcf = new LightingColorFilter( mul, add);
imageView.setColorFilter(lcf);
</code></pre>
<p>but I don't know how to adjust <code>mul, add</code>, can you give some link or code or parameters to adjust the light of the image?</p>
<p>Thank you</p> | 7,049,965 | 2 | 0 | null | 2011-08-13 06:10:14 UTC | 11 | 2018-11-18 18:31:56.13 UTC | 2011-08-13 11:03:29.42 UTC | null | 415,347 | null | 233,618 | null | 1 | 13 | android|graphics|image-processing | 14,739 | <p>The integer values are colours (you may want to have a closer look here <a href="http://developer.android.com/reference/android/graphics/Color.html" rel="noreferrer">http://developer.android.com/reference/android/graphics/Color.html</a>)<br>
4 Bytes are used, one for alpha, one for red, one for green, one for blue range - every single from 0 to 255 (hex 0 to FF)</p>
<p>so the colour in hex looks like </p>
<pre><code>0 x 00 00 00 00
alpha red green blue
</code></pre>
<p>If you want to set for example red to zero, use</p>
<pre><code>mul: 0xFF00FFFF
add: 0x00000000
</code></pre>
<p>If you want to force blue to be full-on, use</p>
<pre><code>mul: 0xFFFFFFFF
add: 0x000000FF
</code></pre> |
7,109,707 | How do I make an expand/contract transition between views on iOS? | <p>I'm trying to make a transition animation in iOS where a view or view controller appears to expand to fill the whole screen, then contract back to its former position when done. I'm not sure what this type of transition is officially called, but you can see an example in the YouTube app for iPad. When you tap one of the search result thumbnails on the grid, it expands from the thumbnail, then contracts back into the thumbnail when you return to the search.</p>
<p>I'm interested in two aspects of this:</p>
<ol>
<li><p>How would you make this effect when transitioning between one view and another? In other words, if view A takes up some area of the screen, how would you transition it to view B which takes up the whole screen, and vice versa?</p></li>
<li><p>How would you transition to a modal view this way? In other words, if UIViewController C is currently showing and contains view D which takes up part of the screen, how do you make it look like view D is turning into UIViewController E which is presented modally on top of C?</p></li>
</ol>
<p><strong>Edit:</strong> I'm adding a bounty to see if that gets this question more love.</p>
<p><strong>Edit:</strong> I've got some source code that does this, and Anomie's idea works like a charm, with a few refinements. I had first tried animating the modal controller's view (E), but it didn't produce the effect of feeling like you're zooming into the screen, because it wasn't expanding all the stuff around the thumbnail view in (C). So then I tried animating the original controller's view (C), but the redrawing of it made for a jerky animation, and things like background textures did not zoom properly. So what I wound up doing is taking an image of the the original view controller (C) and zooming that inside the modal view (E). This method is substantially more complex than my original one, but it does look nice! I think it's how iOS must do its internal transitions as well. Anyway, here's the code, which I've written as a category on UIViewController.</p>
<p>UIViewController+Transitions.h:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface UIViewController (Transitions)
// make a transition that looks like a modal view
// is expanding from a subview
- (void)expandView:(UIView *)sourceView
toModalViewController:(UIViewController *)modalViewController;
// make a transition that looks like the current modal view
// is shrinking into a subview
- (void)dismissModalViewControllerToView:(UIView *)view;
@end
</code></pre>
<p>UIViewController+Transitions.m:</p>
<pre><code>#import "UIViewController+Transitions.h"
@implementation UIViewController (Transitions)
// capture a screen-sized image of the receiver
- (UIImageView *)imageViewFromScreen {
// make a bitmap copy of the screen
UIGraphicsBeginImageContextWithOptions(
[UIScreen mainScreen].bounds.size, YES,
[UIScreen mainScreen].scale);
// get the root layer
CALayer *layer = self.view.layer;
while(layer.superlayer) {
layer = layer.superlayer;
}
// render it into the bitmap
[layer renderInContext:UIGraphicsGetCurrentContext()];
// get the image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// close the context
UIGraphicsEndImageContext();
// make a view for the image
UIImageView *imageView =
[[[UIImageView alloc] initWithImage:image]
autorelease];
return(imageView);
}
// make a transform that causes the given subview to fill the screen
// (when applied to an image of the screen)
- (CATransform3D)transformToFillScreenWithSubview:(UIView *)sourceView {
// get the root view
UIView *rootView = sourceView;
while (rootView.superview) rootView = rootView.superview;
// convert the source view's center and size into the coordinate
// system of the root view
CGRect sourceRect = [sourceView convertRect:sourceView.bounds toView:rootView];
CGPoint sourceCenter = CGPointMake(
CGRectGetMidX(sourceRect), CGRectGetMidY(sourceRect));
CGSize sourceSize = sourceRect.size;
// get the size and position we're expanding it to
CGRect screenBounds = [UIScreen mainScreen].bounds;
CGPoint targetCenter = CGPointMake(
CGRectGetMidX(screenBounds),
CGRectGetMidY(screenBounds));
CGSize targetSize = screenBounds.size;
// scale so that the view fills the screen
CATransform3D t = CATransform3DIdentity;
CGFloat sourceAspect = sourceSize.width / sourceSize.height;
CGFloat targetAspect = targetSize.width / targetSize.height;
CGFloat scale = 1.0;
if (sourceAspect > targetAspect)
scale = targetSize.width / sourceSize.width;
else
scale = targetSize.height / sourceSize.height;
t = CATransform3DScale(t, scale, scale, 1.0);
// compensate for the status bar in the screen image
CGFloat statusBarAdjustment =
(([UIApplication sharedApplication].statusBarFrame.size.height / 2.0)
/ scale);
// transform to center the view
t = CATransform3DTranslate(t,
(targetCenter.x - sourceCenter.x),
(targetCenter.y - sourceCenter.y) + statusBarAdjustment,
0.0);
return(t);
}
- (void)expandView:(UIView *)sourceView
toModalViewController:(UIViewController *)modalViewController {
// get an image of the screen
UIImageView *imageView = [self imageViewFromScreen];
// insert it into the modal view's hierarchy
[self presentModalViewController:modalViewController animated:NO];
UIView *rootView = modalViewController.view;
while (rootView.superview) rootView = rootView.superview;
[rootView addSubview:imageView];
// make a transform that makes the source view fill the screen
CATransform3D t = [self transformToFillScreenWithSubview:sourceView];
// animate the transform
[UIView animateWithDuration:0.4
animations:^(void) {
imageView.layer.transform = t;
} completion:^(BOOL finished) {
[imageView removeFromSuperview];
}];
}
- (void)dismissModalViewControllerToView:(UIView *)view {
// take a snapshot of the current screen
UIImageView *imageView = [self imageViewFromScreen];
// insert it into the root view
UIView *rootView = self.view;
while (rootView.superview) rootView = rootView.superview;
[rootView addSubview:imageView];
// make the subview initially fill the screen
imageView.layer.transform = [self transformToFillScreenWithSubview:view];
// remove the modal view
[self dismissModalViewControllerAnimated:NO];
// animate the screen shrinking back to normal
[UIView animateWithDuration:0.4
animations:^(void) {
imageView.layer.transform = CATransform3DIdentity;
}
completion:^(BOOL finished) {
[imageView removeFromSuperview];
}];
}
@end
</code></pre>
<p>You might use it something like this in a UIViewController subclass:</p>
<pre><code>#import "UIViewController+Transitions.h"
...
- (void)userDidTapThumbnail {
DetailViewController *detail =
[[DetailViewController alloc]
initWithNibName:nil bundle:nil];
[self expandView:thumbnailView toModalViewController:detail];
[detail release];
}
- (void)dismissModalViewControllerAnimated:(BOOL)animated {
if (([self.modalViewController isKindOfClass:[DetailViewController class]]) &&
(animated)) {
[self dismissModalViewControllerToView:thumbnailView];
}
else {
[super dismissModalViewControllerAnimated:animated];
}
}
</code></pre>
<p><strong>Edit:</strong> Well, it turns out that doesn't really handle interface orientations other than portrait. So I had to switch to animating the transition in a UIWindow using a view controller to pass along the rotation. See the much more complicated version below:</p>
<p>UIViewController+Transitions.m:</p>
<pre><code>@interface ContainerViewController : UIViewController { }
@end
@implementation ContainerViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation {
return(YES);
}
@end
...
// get the screen size, compensating for orientation
- (CGSize)screenSize {
// get the size of the screen (swapping dimensions for other orientations)
CGSize size = [UIScreen mainScreen].bounds.size;
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
CGFloat width = size.width;
size.width = size.height;
size.height = width;
}
return(size);
}
// capture a screen-sized image of the receiver
- (UIImageView *)imageViewFromScreen {
// get the root layer
CALayer *layer = self.view.layer;
while(layer.superlayer) {
layer = layer.superlayer;
}
// get the size of the bitmap
CGSize size = [self screenSize];
// make a bitmap to copy the screen into
UIGraphicsBeginImageContextWithOptions(
size, YES,
[UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
// compensate for orientation
if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
CGContextTranslateCTM(context, size.width, 0);
CGContextRotateCTM(context, M_PI_2);
}
else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
CGContextTranslateCTM(context, 0, size.height);
CGContextRotateCTM(context, - M_PI_2);
}
else if (self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
CGContextTranslateCTM(context, size.width, size.height);
CGContextRotateCTM(context, M_PI);
}
// render the layer into the bitmap
[layer renderInContext:context];
// get the image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// close the context
UIGraphicsEndImageContext();
// make a view for the image
UIImageView *imageView =
[[[UIImageView alloc] initWithImage:image]
autorelease];
// done
return(imageView);
}
// make a transform that causes the given subview to fill the screen
// (when applied to an image of the screen)
- (CATransform3D)transformToFillScreenWithSubview:(UIView *)sourceView
includeStatusBar:(BOOL)includeStatusBar {
// get the root view
UIView *rootView = sourceView;
while (rootView.superview) rootView = rootView.superview;
// by default, zoom from the view's bounds
CGRect sourceRect = sourceView.bounds;
// convert the source view's center and size into the coordinate
// system of the root view
sourceRect = [sourceView convertRect:sourceRect toView:rootView];
CGPoint sourceCenter = CGPointMake(
CGRectGetMidX(sourceRect), CGRectGetMidY(sourceRect));
CGSize sourceSize = sourceRect.size;
// get the size and position we're expanding it to
CGSize targetSize = [self screenSize];
CGPoint targetCenter = CGPointMake(
targetSize.width / 2.0,
targetSize.height / 2.0);
// scale so that the view fills the screen
CATransform3D t = CATransform3DIdentity;
CGFloat sourceAspect = sourceSize.width / sourceSize.height;
CGFloat targetAspect = targetSize.width / targetSize.height;
CGFloat scale = 1.0;
if (sourceAspect > targetAspect)
scale = targetSize.width / sourceSize.width;
else
scale = targetSize.height / sourceSize.height;
t = CATransform3DScale(t, scale, scale, 1.0);
// compensate for the status bar in the screen image
CGFloat statusBarAdjustment = includeStatusBar ?
(([UIApplication sharedApplication].statusBarFrame.size.height / 2.0)
/ scale) : 0.0;
// transform to center the view
t = CATransform3DTranslate(t,
(targetCenter.x - sourceCenter.x),
(targetCenter.y - sourceCenter.y) + statusBarAdjustment,
0.0);
return(t);
}
- (void)expandView:(UIView *)sourceView
toModalViewController:(UIViewController *)modalViewController {
// get an image of the screen
UIImageView *imageView = [self imageViewFromScreen];
// show the modal view
[self presentModalViewController:modalViewController animated:NO];
// make a window to display the transition on top of everything else
UIWindow *window =
[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.hidden = NO;
window.backgroundColor = [UIColor blackColor];
// make a view controller to display the image in
ContainerViewController *vc = [[ContainerViewController alloc] init];
vc.wantsFullScreenLayout = YES;
// show the window
[window setRootViewController:vc];
[window makeKeyAndVisible];
// add the image to the window
[vc.view addSubview:imageView];
// make a transform that makes the source view fill the screen
CATransform3D t = [self
transformToFillScreenWithSubview:sourceView
includeStatusBar:(! modalViewController.wantsFullScreenLayout)];
// animate the transform
[UIView animateWithDuration:0.4
animations:^(void) {
imageView.layer.transform = t;
} completion:^(BOOL finished) {
// we're going to crossfade, so change the background to clear
window.backgroundColor = [UIColor clearColor];
// do a little crossfade
[UIView animateWithDuration:0.25
animations:^(void) {
imageView.alpha = 0.0;
}
completion:^(BOOL finished) {
window.hidden = YES;
[window release];
[vc release];
}];
}];
}
- (void)dismissModalViewControllerToView:(UIView *)view {
// temporarily remove the modal dialog so we can get an accurate screenshot
// with orientation applied
UIViewController *modalViewController = [self.modalViewController retain];
[self dismissModalViewControllerAnimated:NO];
// capture the screen
UIImageView *imageView = [self imageViewFromScreen];
// put the modal view controller back
[self presentModalViewController:modalViewController animated:NO];
[modalViewController release];
// make a window to display the transition on top of everything else
UIWindow *window =
[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.hidden = NO;
window.backgroundColor = [UIColor clearColor];
// make a view controller to display the image in
ContainerViewController *vc = [[ContainerViewController alloc] init];
vc.wantsFullScreenLayout = YES;
// show the window
[window setRootViewController:vc];
[window makeKeyAndVisible];
// add the image to the window
[vc.view addSubview:imageView];
// make the subview initially fill the screen
imageView.layer.transform = [self
transformToFillScreenWithSubview:view
includeStatusBar:(! self.modalViewController.wantsFullScreenLayout)];
// animate a little crossfade
imageView.alpha = 0.0;
[UIView animateWithDuration:0.15
animations:^(void) {
imageView.alpha = 1.0;
}
completion:^(BOOL finished) {
// remove the modal view
[self dismissModalViewControllerAnimated:NO];
// set the background so the real screen won't show through
window.backgroundColor = [UIColor blackColor];
// animate the screen shrinking back to normal
[UIView animateWithDuration:0.4
animations:^(void) {
imageView.layer.transform = CATransform3DIdentity;
}
completion:^(BOOL finished) {
// hide the transition stuff
window.hidden = YES;
[window release];
[vc release];
}];
}];
}
</code></pre>
<p>Whew! But now it looks just about like Apple's version without using any restricted APIs. Also, it works even if the orientation changes while the modal view is in front.</p> | 7,193,234 | 2 | 0 | null | 2011-08-18 15:08:18.727 UTC | 36 | 2011-08-30 19:59:50.86 UTC | 2011-08-30 19:59:50.86 UTC | null | 745,831 | null | 745,831 | null | 1 | 37 | ios|animation|uiview|transition|modalviewcontroller | 15,936 | <ol>
<li><p>Making the effect is simple. You take the full-sized view, initialize its <code>transform</code> and <code>center</code> to position it on top of the thumbnail, add it to the appropriate superview, and then in an animation block reset the <code>transform</code> and <code>center</code> to position it in the final position. To dismiss the view, just do the opposite: in an animation block set <code>transform</code> and <code>center</code> to position it on top of the thumbnail, and then remove it completely in the completion block.</p>
<p>Note that trying to zoom from a point (i.e. a rectangle with 0 width and 0 height) will screw things up. If you're wanting to do that, zoom from a rectangle with width/height something like 0.00001 instead.</p></li>
<li><p>One way would be to do the same as in #1, and then call <code>presentModalViewController:animated:</code> with animated NO to present the actual view controller when the animation is complete (which, if done right, would result in no visible difference due to the <code>presentModalViewController:animated:</code> call). And <code>dismissModalViewControllerAnimated:</code> with NO followed by the same as in #1 to dismiss.</p>
<p>Or you could manipulate the modal view controller's view directly as in #1, and accept that <code>parentViewController</code>, <code>interfaceOrientation</code>, and some other stuff just won't work right in the modal view controller since Apple doesn't support us creating our own container view controllers.</p></li>
</ol> |
23,155,244 | spring boot hotswap with Intellij IDE | <p>I have a spring boot application running fine with Intellij IDE. i.e i started the Application class that has the main method which delegates to SpringApplication.run. Everything works great except hotswap. When I change the source, I am forced to re-start the application. Even If I start the application in debug mode, I dont see hotswap working. I could see that Intellij's Debug settings have hotswap enabled.</p>
<p>My observation shows that when I run the springboot application, classpath used is my </p>
<pre>
/projects/MyProject/<b>classes/production/</b>....
</pre>
<p>Files under <code>classes/production</code> are not getting updated when I change the code. Intellij IDE compiles the files but does not update classes/production directory. How do I get hotswap working with IntelliJ IDE for spring-boot?</p> | 23,155,442 | 10 | 1 | null | 2014-04-18 13:32:25.34 UTC | 40 | 2022-07-13 08:42:27.207 UTC | null | null | null | null | 2,184,930 | null | 1 | 84 | intellij-idea|spring-boot|hotswap | 68,031 | <p>Found out the root cause. This has nothing to do with Spring-boot. On changing my groovy source files, files were not auto-compiled. </p>
<p>To recompile changed files and swap them:</p>
<ul>
<li><code>Ctrl+Shift+F9</code> on Windows</li>
<li><code>Cmd+Shift+F9</code> on Mac</li>
</ul> |
31,263,637 | How to convert Laravel migrations to raw SQL scripts? | <p>Developers of my team are really used to the power of Laravel migrations, they are working great on local machines and our dev servers.
But customer's database admin will not accept Laravel migrations. He asks for raw SQL scripts for each new version of our application.</p>
<p><strong>Is there any tool or programming technique to capture the output from Laravel migrations to up/down SQL scripts?</strong> </p>
<p>It would be perfect if we could integrate SQL script generation in our CI system (TeamCity) when creating production builds.</p>
<p>By the way, we will be using Laravel 5 and PostgreSQL for this project.</p> | 31,263,746 | 5 | 3 | null | 2015-07-07 08:35:39.017 UTC | 26 | 2021-04-11 18:24:29.397 UTC | null | null | null | null | 217,823 | null | 1 | 57 | sql|laravel|laravel-migrations | 34,088 | <h1>Use the migrate command</h1>
<p>You can add the <code>--pretend</code> flag when you run <code>php artisan migrate</code> to output the queries to the terminal:</p>
<pre><code>php artisan migrate --pretend
</code></pre>
<p>This will look something like this:</p>
<pre><code>Migration table created successfully.
CreateUsersTable: create table "users" ("id" integer not null primary key autoincrement, "name" varchar not null, "email" varchar not null, "password" varchar not null, "remember_token" varchar null, "created_at" datetime not null, "updated_at" datetime not null)
CreateUsersTable: create unique index users_email_unique on "users" ("email")
CreatePasswordResetsTable: create table "password_resets" ("email" varchar not null, "token" varchar not null, "created_at" datetime not null)
CreatePasswordResetsTable: create index password_resets_email_index on "password_resets" ("email")
CreatePasswordResetsTable: create index password_resets_token_index on "password_resets" ("token")
</code></pre>
<p>To save this to a file, just redirect the output <strong>without ansi</strong>:</p>
<pre><code>php artisan migrate --pretend --no-ansi > migrate.sql
</code></pre>
<blockquote>
<p>This command only include the migrations that hasn't been migrated yet.</p>
</blockquote>
<hr>
<h1>Hack the migrate command</h1>
<p>To further customize how to get the queries, consider hacking the source and make your own custom command or something like that. To get you started, here is some quick code to get all the migrations.</p>
<h3>Example code</h3>
<pre><code>$migrator = app('migrator');
$db = $migrator->resolveConnection(null);
$migrations = $migrator->getMigrationFiles('database/migrations');
$queries = [];
foreach($migrations as $migration) {
$migration_name = $migration;
$migration = $migrator->resolve($migration);
$queries[] = [
'name' => $migration_name,
'queries' => array_column($db->pretend(function() use ($migration) { $migration->up(); }), 'query'),
];
}
dd($queries);
</code></pre>
<h3>Example output</h3>
<pre><code>array:2 [
0 => array:2 [
"name" => "2014_10_12_000000_create_users_table"
"queries" => array:2 [
0 => "create table "users" ("id" integer not null primary key autoincrement, "name" varchar not null, "email" varchar not null, "password" varchar not null, "remember_token" varchar null, "created_at" datetime not null, "updated_at" datetime not null)"
1 => "create unique index users_email_unique on "users" ("email")"
]
]
1 => array:2 [
"name" => "2014_10_12_100000_create_password_resets_table"
"queries" => array:3 [
0 => "create table "password_resets" ("email" varchar not null, "token" varchar not null, "created_at" datetime not null)"
1 => "create index password_resets_email_index on "password_resets" ("email")"
2 => "create index password_resets_token_index on "password_resets" ("token")"
]
]
]
</code></pre>
<blockquote>
<p>This code will include <strong>all</strong> the migrations. To see how to only get what isn't already migrated take a look at the <code>run()</code> method in <code>vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php</code>.</p>
</blockquote> |
19,000,356 | IOS 7 - How to get the indexPath from button placed in UITableViewCell | <p>I've programmatically created a UITableView and added UISwitch to it's cell accessory view. </p>
<p>This is my code for UISwitch in cell accessory view in <code>cellForRowAtIndexPath</code> method.</p>
<pre><code>UISwitch *accessorySwitch = [[UISwitch alloc]initWithFrame:CGRectZero];
[accessorySwitch setOn:NO animated:YES];
[accessorySwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = accessorySwitch;
</code></pre>
<p>This is the method which is called after the button is clicked.</p>
<pre><code>- (void)changeSwitch:(UISwitch *)sender{
UITableViewCell *cell = (UITableViewCell *)[sender superview];
NSIndexPath *indexPath = [self.filterTableView indexPathForCell:cell];
NSLog(@"%ld",(long)indexPath);
……………. My other code…….
}
</code></pre>
<p>I am able to print the index path value in iOS 6
But in iOS 7 it prints nil,</p>
<p>Am i missing anything in iOS 7 or there is some other approach to get the indexPath in iOS 7 </p>
<p>Thanks,
Arun.</p> | 19,000,484 | 9 | 0 | null | 2013-09-25 08:53:21.147 UTC | 12 | 2021-06-10 10:03:02.87 UTC | null | null | null | null | 2,046,533 | null | 1 | 29 | iphone|ios|uitableview|ios7 | 26,859 | <p><code>NSLog(@"%ld",(long)indexPath);</code> is wrong this will print the pointer address of indexPath</p>
<p>try using following codes</p>
<pre><code>CGPoint center= sender.center;
CGPoint rootViewPoint = [sender.superview convertPoint:center toView:self.filterTableView];
NSIndexPath *indexPath = [self.filterTableView indexPathForRowAtPoint:rootViewPoint];
NSLog(@"%@",indexPath);
</code></pre> |
36,982,858 | Object of type 'map' has no len() in Python 3 | <p>I have a problem with Python 3. I got Python 2.7 code and at the moment I am trying to update it. I get the error:</p>
<blockquote>
<p>TypeError: object of type 'map' has no len()</p>
</blockquote>
<p>at this part:</p>
<pre><code>str(len(seed_candidates))
</code></pre>
<p>Before I initialized it like this:</p>
<pre><code>seed_candidates = map(modify_word, wordlist)
</code></pre>
<p>So, can someone explain me what I have to do?</p>
<p>(EDIT: Previously this code example was wrong because it used <code>set</code> instead of <code>map</code>. It has been updated now.)</p> | 36,982,926 | 2 | 2 | null | 2016-05-02 12:48:01.697 UTC | 5 | 2020-05-14 12:57:30.69 UTC | 2018-08-08 14:50:56.98 UTC | null | 7,098,259 | null | 5,986,558 | null | 1 | 63 | python|python-3.x|variable-length | 85,256 | <p>In Python 3, <code>map</code> returns a map object not a <code>list</code>:</p>
<pre><code>>>> L = map(str, range(10))
>>> print(L)
<map object at 0x101bda358>
>>> print(len(L))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'map' has no len()
</code></pre>
<p>You can convert it into a list then get the length from there:</p>
<pre><code>>>> print(len(list(L)))
10
</code></pre> |
17,682,934 | Linux Terminal: typing feedback gone, line breaks not displayed | <p>From time to time I have to run a command-line tool (a Python script) whose output seems to break my terminal.
After the execution is finished, the typing feedback is gone (I can't see what I'm typing), and also line breaks are not displayed. This happens if the terminal is started remotely via <code>Putty</code>, and also locally when using <code>gnome-terminal</code>.</p>
<p>For example, after the problem happens, if I type <kbd>ENTER</kbd> <code>pwd</code> <kbd>ENTER</kbd>, I would expect to see:</p>
<pre><code>[userA@host006 ~]$
[userA@host006 ~]$ pwd
/home/userA
[userA@host006 ~]$
</code></pre>
<p>But actually the output is:</p>
<pre><code>[userA@host006 ~]$ [userA@host006 ~]$ /home/userA
[userA@host006 ~]$
</code></pre>
<p>The only way to fix it is to close that terminal and start a new one.</p>
<p>Maybe be related: the script output contains some terminal-based formatting (e.g. invert foreground/background to highlight some status messages). If I dump this output to a file I can see things like <code>[07mSome Message Here[0m</code>.</p>
<p>Any ideas what I could do to prevent this?</p> | 17,683,085 | 2 | 4 | null | 2013-07-16 17:13:13.857 UTC | 19 | 2020-08-26 21:34:46.56 UTC | null | null | null | null | 15,931 | null | 1 | 76 | linux|bash|terminal|putty|gnome-terminal | 40,746 | <p>Execute the command <code>reset</code> and your terminal should be restored (<a href="http://www.commandlinefu.com/commands/view/32/salvage-a-borked-terminal" rel="noreferrer">reference</a>).</p>
<p>This issue happens generally when dumping binary data to the terminal <code>STDOUT</code> which when the escape codes received are processed can do anything from change the color of the text, disable echo, even change character set.</p>
<p>The easy way to avoid this is to ensure you do not dump unknown binary data to the terminal, and if you must then convert it to hexadecimal to ensure it doesn't change the terminal settings.</p> |
8,694,984 | Remove part of string in Java | <p>I want to remove a part of string from one character, that is:</p>
<p>Source string: </p>
<pre><code>manchester united (with nice players)
</code></pre>
<p>Target string: </p>
<pre><code>manchester united
</code></pre> | 8,695,026 | 12 | 1 | null | 2012-01-01 19:28:40.64 UTC | 24 | 2020-01-25 01:02:57.047 UTC | 2018-08-14 13:38:38.307 UTC | null | 5,997,596 | null | 1,114,739 | null | 1 | 90 | java|string | 457,301 | <p>There are multiple ways to do it. If you have the string which you want to replace you can use the <code>replace</code> or <code>replaceAll</code> methods of the <code>String</code> class. If you are looking to replace a substring you can get the substring using the <code>substring</code> API.</p>
<p>For example</p>
<pre><code>String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
</code></pre>
<p>To replace content within "()" you can use:</p>
<pre><code>int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
</code></pre> |
19,512,241 | Navigation drawer and view pager in same activity | <p>I am trying to implement both navigation drawer and view pager in same activity. Navigation drawer works fine but the view pager is not working, also i am getting null pointer on right swipe when navigation drawer is opened (Null pointer at android. support. v4. widget. DrawerLayout. isContentView(DrawerLayout.java:840). I am attaching the main xml layout and code below.
</p>
<pre><code><android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p></p>
<p>Activity class is given below</p>
<pre><code>public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private MainActivity mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
CustomPagerAdapter adapter = new CustomPagerAdapter(mContext);
vp.setAdapter(adapter);
vp.setPageTransformer(false, new ViewPager.PageTransformer() {
@Override
public void transformPage(View page, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setScaleX(normalizedposition / 2 + 0.5f);
page.setScaleY(normalizedposition / 2 + 0.5f);
}
});
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /*
* "open drawer" description for
* accessibility
*/
R.string.drawer_close /*
* "close drawer" description for
* accessibility
*/
) {
@Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
return true;
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public class CustomPagerAdapter extends PagerAdapter {
private Context context;
int index = 2;
// public CustomPagerAdapter(Context context, Vector<View> pages) {
// this.context = context;
// this.pages = pages;
// }
public CustomPagerAdapter(Context context) {
this.context = context;
this.index = 2;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater.from(container.getContext()));
// View page = pages.get(position);
View view = null;
if (position == 0) {
view = inflater.inflate(R.layout.page_one_views, null);
((ViewPager) container).addView(view);
}
else {
// page.setBackgroundColor(colors.get(position));
// container.addView(page);
view = inflater.inflate(R.layout.page_two, null);
((ViewPager) container).addView(view);
}
return view;
}
@Override
public int getCount() {
return index;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
</code></pre>
<p>}</p>
<p>Please help me. Thanks in advance</p> | 19,513,045 | 3 | 1 | null | 2013-10-22 08:00:41 UTC | 11 | 2016-04-12 13:19:00.897 UTC | null | null | null | null | 1,651,509 | null | 1 | 22 | android|android-viewpager|navigation-drawer|drawerlayout | 29,727 | <p>The <code>DrawerLayout</code> should be the root element. Put the <code>ViewPager</code> inside it.</p>
<pre><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
</code></pre> |
574,730 | Python: How to ignore an exception and proceed? | <p>I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?</p> | 574,734 | 4 | 0 | null | 2009-02-22 11:02:22.227 UTC | 92 | 2020-10-14 03:36:58.807 UTC | 2010-01-02 01:03:27.867 UTC | S.Lott | 3,542 | The.Anti.9 | 2,128 | null | 1 | 526 | python|exception | 764,880 | <pre><code>except Exception:
pass
</code></pre>
<p><a href="https://docs.python.org/3.7/tutorial/controlflow.html#pass-statements" rel="noreferrer">Python docs for the pass statement</a></p> |
723,998 | What are database normal forms and can you give examples? | <p>In relational database design, there is a concept of database normalization or simply normalization, which is a process of organizing columns (attributes) and tables (relations) to reduce data redundancy and improve data integrity. (as written on <a href="https://en.wikipedia.org/wiki/Database_normalization" rel="noreferrer">Wikipedia</a>).</p>
<p>As most articles are somewhat technical and thus harder to understand, I'm asking for someone to write an easier to understand explanation based on examples about what 1NF, 2NF, 3NF, even 3.5NF (Boyce-Codd) mean.</p> | 724,032 | 4 | 0 | null | 2009-04-07 02:43:56.39 UTC | 220 | 2018-03-15 17:24:07.643 UTC | 2018-03-15 17:24:07.643 UTC | null | 23 | null | 1,390,354 | null | 1 | 289 | database|database-design|database-normalization | 249,450 | <p>1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.</p>
<p>2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:</p>
<p>The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me <a href="http://en.wikipedia.org/wiki/Ted_Codd" rel="noreferrer">Codd</a>).</p>
<h2>2NF</h2>
<p>Say you have a table containing courses that are taken in a certain semester, and you have the following data:</p>
<pre><code>|-----Primary Key----| uh oh |
V
CourseID | SemesterID | #Places | Course Name |
------------------------------------------------|
IT101 | 2009-1 | 100 | Programming |
IT101 | 2009-2 | 100 | Programming |
IT102 | 2009-1 | 200 | Databases |
IT102 | 2010-1 | 150 | Databases |
IT103 | 2009-2 | 120 | Web Design |
</code></pre>
<p>This is <strong>not in 2NF</strong>, because the fourth column does not rely upon the <em>entire</em> key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.</p>
<pre><code>Primary Key |
CourseID | Course Name |
---------------------------|
IT101 | Programming |
IT102 | Databases |
IT103 | Web Design |
</code></pre>
<p>No redundancy!</p>
<h2>3NF</h2>
<p>Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:</p>
<pre><code>|-----Primary Key----| uh oh |
V
Course | Semester | #Places | TeacherID | TeacherName |
---------------------------------------------------------------|
IT101 | 2009-1 | 100 | 332 | Mr Jones |
IT101 | 2009-2 | 100 | 332 | Mr Jones |
IT102 | 2009-1 | 200 | 495 | Mr Bentley |
IT102 | 2010-1 | 150 | 332 | Mr Jones |
IT103 | 2009-2 | 120 | 242 | Mrs Smith |
</code></pre>
<p>Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is <strong>not in 3NF</strong>. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.</p>
<pre><code> Primary Key |
TeacherID | TeacherName |
---------------------------|
332 | Mr Jones |
495 | Mr Bentley |
242 | Mrs Smith |
</code></pre>
<p>No redundancy!!</p>
<p>One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires <em>everything</em> that the lower normal forms had, plus some extra conditions, which must <em>all</em> be fulfilled.</p> |
29,828,624 | What's a Chocolatey "Install" package? | <p>On reviewing the <a href="https://chocolatey.org/packages">chocolatey packages</a> available, I came across a few that have two (or sometimes more) packages apparently for the same product. At first glance is not possible to tell the difference.</p>
<p>For example, there is the <em>AutohotKey</em> package, and then there is also an <em>Autohotkey.<strong>install</em></strong> package.</p>
<p>What is the difference between both types of packages?</p> | 29,832,028 | 2 | 0 | null | 2015-04-23 15:57:01.797 UTC | 9 | 2021-03-07 14:15:26.027 UTC | 2015-04-24 15:48:40.96 UTC | null | 3,619 | null | 1,960,071 | null | 1 | 42 | package|chocolatey | 11,512 | <p>Have a look at the FAQ in the Chocolatey wiki here:</p>
<p><a href="https://github.com/chocolatey/choco/wiki/ChocolateyFAQs#what-is-the-difference-between-packages-no-suffix-as-compared-to-install-portable" rel="noreferrer">https://github.com/chocolatey/choco/wiki/ChocolateyFAQs#what-is-the-difference-between-packages-no-suffix-as-compared-to-install-portable</a></p>
<p>Quoting from that article:</p>
<blockquote>
<p>tl;dr: Nearly 100% of the time, the package with no suffix (autohotkey in this example) is going to ensure the *.install. The package without the suffix is for both discoverability and for other packages to take a dependency on.</p>
<p>Chocolatey has the concept of virtual packages (coming) and meta packages. Virtual packages are packages that represent other packages when used as a dependency. Metapackages are packages that only exist to provide a grouping of dependencies.</p>
<p>A package with no suffix that is surrounded by packages with suffixes is to provide a virtual package. So in the case of git, git.install, and git.commandline (deprecated for .portable) – git is that virtual package (currently it is really just a metapackage until the virtual packages feature is complete). That means that other packages could depend on it and you could have either git.install or git.portable installed and you would meet the dependency of having git installed. That keeps Chocolatey from trying to install something that already meets the dependency requirement for a package.</p>
<p>Talking specifically about the *.install package suffix – those are for the packages that have a native installer that they have bundled or they download and run.</p>
<p><strong>NOTE:</strong> the suffix *.app has been used previously to mean the same as *.install. But the *.app suffix is now deprecated and should not be used for new packages.</p>
<p>The *.portable packages are the packages that will usually result in an executable on your path somewhere but do not get installed onto the system (Add/Remove Programs). Previously the suffixes *.tool and *.commandline have been used to refer to the same type of packages.</p>
<p><strong>NOTE:</strong> now *.tool and *.commandline are deprecated and should not be used for new packages.</p>
<p>Want more information? See <a href="http://ferventcoder.com/archive/2012/02/25/chocolatey---guidance-on-packaging-apps-with-both-an-install.aspx" rel="noreferrer">http://ferventcoder.com/archive/2012/02/25/chocolatey---guidance-on-packaging-apps-with-both-an-install.aspx</a></p>
</blockquote> |
36,924,873 | pyspark Column is not iterable | <p>Having this dataframe I am getting Column is not iterable when I try to groupBy and getting max: </p>
<pre><code>linesWithSparkDF
+---+-----+
| id|cycle|
+---+-----+
| 31| 26|
| 31| 28|
| 31| 29|
| 31| 97|
| 31| 98|
| 31| 100|
| 31| 101|
| 31| 111|
| 31| 112|
| 31| 113|
+---+-----+
only showing top 10 rows
ipython-input-41-373452512490> in runlgmodel2(model, data)
65 linesWithSparkDF.show(10)
66
---> 67 linesWithSparkGDF = linesWithSparkDF.groupBy(col("id")).agg(max(col("cycle")))
68 print "linesWithSparkGDF"
69
/usr/hdp/current/spark-client/python/pyspark/sql/column.py in __iter__(self)
241
242 def __iter__(self):
--> 243 raise TypeError("Column is not iterable")
244
245 # string methods
TypeError: Column is not iterable
</code></pre> | 36,924,945 | 4 | 0 | null | 2016-04-28 20:28:20.243 UTC | 3 | 2022-05-20 06:09:14.26 UTC | 2016-05-03 15:46:19.21 UTC | null | 6,083,675 | null | 203,968 | null | 1 | 27 | apache-spark|pyspark | 87,407 | <p>It's because, you've overwritten the <code>max</code> definition provided by <code>apache-spark</code>, it was easy to spot because <code>max</code> was expecting an <code>iterable</code>.</p>
<p>To fix this, you can use <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=agg#pyspark.sql.DataFrame.agg">a different syntax</a>, and it should work.</p>
<pre class="lang-py prettyprint-override"><code>inesWithSparkGDF = linesWithSparkDF.groupBy(col("id")).agg({"cycle": "max"})
</code></pre>
<p>or alternatively</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import max as sparkMax
linesWithSparkGDF = linesWithSparkDF.groupBy(col("id")).agg(sparkMax(col("cycle")))
</code></pre> |
27,323,065 | Must be possible to filter table names in a single database? | <p>As far as I can tell, the search filter in the navigator will only search available database names, not table names.</p>
<p>If you click on a table name and start typing, it appears that a simple search can be performed beginning with the first letter of the tables.</p>
<p>I'm looking for way to be able to search all table names in a selected database. Sometimes there can be a lot of tables to sort through. It seems like a feature that would likely be there and I can't find it.</p> | 29,131,185 | 2 | 0 | null | 2014-12-05 19:14:07.297 UTC | 15 | 2016-08-19 13:24:12.13 UTC | null | null | null | null | 425,767 | null | 1 | 62 | mysql-workbench | 13,940 | <p>Found out the answer...</p>
<p>If you type for example <code>*.test_table</code> or the schema name instead of the asterisk it will filter them. The key is that the schema/database must be specified in the search query. The asterisk notation works with the table names as well. For example <code>*.*test*</code> will filter any table in any schema with test anywhere in the table name.</p> |
27,635,292 | Transfer files using lftp in bash script | <p>I have server A <code>test-lx</code>, and server B <code>test2-lx</code>, I want to transfer files from server A to server B.
While transfering the files i'll need to create a driectory only if it's not exist, how can i check if a directory exist during the lftp conenction? How can i out several files in one command instead of doing this in 2 lines.
Is there an option to use <code>find -maxdepth 1 -name DirName</code></p>
<p>Here is my code:</p>
<pre><code>lftp -u drop-up,1Q2w3e4R ftp://ta1bbn01:21 << EOF
cd $desFolder
mkdir test
cd test
put $srcFil
put $srcFile
bye
EOF
</code></pre> | 27,635,444 | 3 | 0 | null | 2014-12-24 10:20:55.577 UTC | 1 | 2020-01-22 12:52:14.333 UTC | 2014-12-24 13:27:32 UTC | null | 3,502,786 | null | 3,502,786 | null | 1 | 8 | linux|bash|unix|centos | 79,063 | <p>Simple way with ftp:</p>
<pre><code>#!/bin/bash
ftp -inv ip << EOF
user username password
cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload
bye
EOF
</code></pre>
<p>With lftp:</p>
<pre><code>#!/bin/bash
lftp -u username,password ip << EOF
cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload
bye
EOF
</code></pre>
<p>From lftp manual:</p>
<pre><code>-u <user>[,<pass>] use the user/password for authentication
</code></pre>
<p>You can use mkdir for create a directory. And you can use put command several time like this:</p>
<pre><code>put what_you_want_to_upload
put what_you_want_to_upload2
put what_you_want_to_upload3
</code></pre>
<p>And you can close connection with <code>bye</code></p>
<hr>
<p>You can check folder is exist or not like this:</p>
<pre><code>#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test1231")
if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exist"
fi
</code></pre>
<p>From lftp manual:</p>
<pre><code>-c <cmd> execute the commands and exit
</code></pre>
<p>And you can open another connection for put some files.</p>
<hr>
<p>I don't know how to check folder is exist or not with one connection, but I can do that like this. Maybe you can find better solution:</p>
<pre><code>#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test2")
if [ "$checkfolder" == "" ];
then
lftp -u user,pass ip << EOF
mkdir test2
cd test2
put testfile.txt
bye
EOF
else
echo "The directory already exists - exiting"
fi
</code></pre> |
43,541,859 | Change NuGet package folders used by Visual Studio 2017 | <p>There is no more <code>packages</code> solution folder in any <code>csproj</code> or <code>project.json</code>-based .NET Core project.</p>
<p><a href="https://docs.microsoft.com/en-us/nuget/consume-packages/managing-the-nuget-cache" rel="noreferrer">NuGet CLI</a> gets the list of used cache folders:</p>
<pre><code>nuget locals all -list
</code></pre>
<p>Response:</p>
<pre><code>http-cache: C:\Users\<foo>\AppData\Local\NuGet\v3-cache
global-packages: C:\Users\<foo>\.nuget\packages\
temp: C:\Users\<foo>\AppData\Local\Temp\NuGetScratch
</code></pre>
<p>How to change or override these locations?</p> | 43,541,864 | 3 | 0 | null | 2017-04-21 11:43:13.58 UTC | 15 | 2020-10-28 17:57:04.037 UTC | 2017-04-22 16:47:54.683 UTC | null | 5,112,433 | null | 5,112,433 | null | 1 | 39 | nuget|.net-core|visual-studio-2017 | 41,252 | <h3>Cache locations</h3>
<p>Solution-local packages folders are no longer exist for .NET Core and Visual Studio 2017.</p>
<p><a href="http://blog.nuget.org/20170316/NuGet-now-fully-integrated-into-MSBuild.html" rel="noreferrer">NuGet is now fully integrated into MSBuild:</a></p>
<blockquote>
<p>Solution-local packages folders are no longer used – Packages are now
resolved against the user’s cache at %userdata%.nuget, rather than a
solution specific packages folder. This makes PackageReference perform
faster and consume less disk space by using a shared folder of
packages on your workstation.</p>
</blockquote>
<p>NuGet 4.0+ uses at least two global package locations:</p>
<ul>
<li>User-specific: <code>%userprofile%\.nuget\packages\</code></li>
<li>Machine-wide: <code>%ProgramFiles(x86)%\Microsoft SDKs\NuGetPackages\"</code></li>
</ul>
<p>You can list all user-specific folders using the following console command:</p>
<pre><code>nuget locals all -list
</code></pre>
<p>Notice that the machine-wide folder isn't listed there. However, it is defined at Visual Studio settings: </p>
<pre><code>Options -> NuGet Package Manager -> Package Sources
</code></pre>
<h3>Configuration files</h3>
<p><code>NuGet.config</code> files <a href="https://docs.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior" rel="noreferrer">are located here</a>:</p>
<ul>
<li>User-specific: <code>%APPDATA%\NuGet\</code></li>
<li>Machine-wide: <code>%ProgramFiles(x86)%\NuGet\Config\</code></li>
</ul>
<p>It is possible to change and override NuGet settings at many levels:</p>
<ul>
<li>project</li>
<li>solution</li>
<li>user</li>
<li>machine</li>
</ul>
<p>And even more! Read more about <code>NuGet.config</code> hierarchical priority ordering here: <a href="https://docs.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior#how-settings-are-applied" rel="noreferrer">How settings are applied</a>. </p>
<p>For example, <code>globalPackagesFolder</code> parameter changes a package cache location. Look at this <code>NuGet.config</code> example:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<config>
<clear />
<add key="globalPackagesFolder" value="c:\packages" />
</config>
</configuration>
</code></pre> |
43,633,273 | Copy current location to clipboard | <p>How do I copy the current working directory to clipboard?</p>
<pre><code>PS C:\jacek> pwd | CLIP
</code></pre>
<p>I get content like below. How can I copy only location/value without any whitespace or description?</p>
<pre>
Path
--
C:\jacek
</pre> | 43,633,385 | 2 | 0 | null | 2017-04-26 11:44:58.783 UTC | 9 | 2020-12-01 14:49:27.993 UTC | 2017-04-26 11:54:22.423 UTC | null | 2,208,505 | null | 650,148 | null | 1 | 20 | powershell | 4,667 | <p>Update your code to just return the <code>Path</code>:</p>
<pre><code>(pwd).Path | CLIP
</code></pre>
<hr />
<p>If you're using PowerShell v5 or newer you can use <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-clipboard" rel="noreferrer">Set-Clipboard</a> instead of clip(.exe).</p>
<pre><code>(pwd).Path | Set-Clipboard
</code></pre> |
34,830,597 | Pandas Melt Function | <p>I have a dataframe:</p>
<pre><code>df = pd.DataFrame([[2, 4, 7, 8, 1, 3, 2013], [9, 2, 4, 5, 5, 6, 2014]], columns=['Amy', 'Bob', 'Carl', 'Chris', 'Ben', 'Other', 'Year'])
</code></pre>
<pre class="lang-none prettyprint-override"><code> Amy Bob Carl Chris Ben Other Year
0 2 4 7 8 1 3 2013
1 9 2 4 5 5 6 2014
</code></pre>
<p>And a dictionary:</p>
<pre><code>d = {'A': ['Amy'], 'B': ['Bob', 'Ben'], 'C': ['Carl', 'Chris']}
</code></pre>
<p>I would like to reshape my dataframe to look like this:</p>
<pre class="lang-none prettyprint-override"><code> Group Name Year Value
0 A Amy 2013 2
1 A Amy 2014 9
2 B Bob 2013 4
3 B Bob 2014 2
4 B Ben 2013 1
5 B Ben 2014 5
6 C Carl 2013 7
7 C Carl 2014 4
8 C Chris 2013 8
9 C Chris 2014 5
10 Other 2013 3
11 Other 2014 6
</code></pre>
<p>Note that <code>Other</code> doesn't have any values in the <code>Name</code> column and the order of the rows does not matter. I think I should be using the <code>melt</code> function but the examples that I've come across aren't too clear.</p> | 34,830,810 | 2 | 0 | null | 2016-01-16 18:31:54.25 UTC | 6 | 2018-09-14 09:18:16.43 UTC | 2018-09-14 09:18:16.43 UTC | null | 1,671,066 | null | 2,955,541 | null | 1 | 23 | python|pandas | 50,888 | <p><code>melt</code> gets you part way there.</p>
<pre><code>In [29]: m = pd.melt(df, id_vars=['Year'], var_name='Name')
</code></pre>
<p>This has everything except <code>Group</code>. To get that, we need to reshape <code>d</code> a bit as well.</p>
<pre><code>In [30]: d2 = {}
In [31]: for k, v in d.items():
for item in v:
d2[item] = k
....:
In [32]: d2
Out[32]: {'Amy': 'A', 'Ben': 'B', 'Bob': 'B', 'Carl': 'C', 'Chris': 'C'}
In [34]: m['Group'] = m['Name'].map(d2)
In [35]: m
Out[35]:
Year Name value Group
0 2013 Amy 2 A
1 2014 Amy 9 A
2 2013 Bob 4 B
3 2014 Bob 2 B
4 2013 Carl 7 C
.. ... ... ... ...
7 2014 Chris 5 C
8 2013 Ben 1 B
9 2014 Ben 5 B
10 2013 Other 3 NaN
11 2014 Other 6 NaN
[12 rows x 4 columns]
</code></pre>
<p>And moving 'Other' from <code>Name</code> to <code>Group</code></p>
<pre><code>In [8]: mask = m['Name'] == 'Other'
In [9]: m.loc[mask, 'Name'] = ''
In [10]: m.loc[mask, 'Group'] = 'Other'
In [11]: m
Out[11]:
Year Name value Group
0 2013 Amy 2 A
1 2014 Amy 9 A
2 2013 Bob 4 B
3 2014 Bob 2 B
4 2013 Carl 7 C
.. ... ... ... ...
7 2014 Chris 5 C
8 2013 Ben 1 B
9 2014 Ben 5 B
10 2013 3 Other
11 2014 6 Other
[12 rows x 4 columns]
</code></pre> |
50,614,661 | How to underline text in flutter | <p>How to underline text in flutter inside <code>Text</code> widget?</p>
<p>I cannot seem to find underline inside <code>fontStyle</code> property of <code>TextStyle</code></p> | 54,246,505 | 10 | 0 | null | 2018-05-30 23:31:09.35 UTC | 22 | 2022-07-22 16:28:00.88 UTC | null | null | null | null | 4,211,520 | null | 1 | 245 | flutter | 220,638 | <p>When underlining everything you can set a TextStyle on the Text widget.</p>
<p><a href="https://i.stack.imgur.com/XM4mb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XM4mb.png" alt="enter image description here"></a></p>
<pre><code>Text(
'Hello world',
style: TextStyle(
decoration: TextDecoration.underline,
),
)
</code></pre>
<p>If you only want to underline part of the text then you need to use <code>Text.rich()</code> (or a RichText widget) and break the string into TextSpans that you can add a style to.</p>
<p><a href="https://i.stack.imgur.com/7GZbs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7GZbs.png" alt="enter image description here"></a></p>
<pre><code>Text.rich(
TextSpan(
text: 'Hello ',
style: TextStyle(fontSize: 50),
children: <TextSpan>[
TextSpan(
text: 'world',
style: TextStyle(
decoration: TextDecoration.underline,
)),
// can add more TextSpans here...
],
),
)
</code></pre>
<p>TextSpan is a little strange. The <code>text</code> parameter is the default style but the <code>children</code> list contains the styled (and possibly unstyled) text that follow it. You can use an empty string for <code>text</code> if you want to start with styled text.</p>
<p>You can also add a TextDecorationStyle to change how the decoration looks. Here is dashed:</p>
<p><a href="https://i.stack.imgur.com/lc6dH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lc6dH.png" alt="enter image description here"></a></p>
<pre><code>Text(
'Hello world',
style: TextStyle(
decoration: TextDecoration.underline,
decorationStyle: TextDecorationStyle.dashed,
),
)
</code></pre>
<p>and <code>TextDecorationStyle.dotted</code>:</p>
<p><a href="https://i.stack.imgur.com/bhHwA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bhHwA.png" alt="enter image description here"></a></p>
<p>and <code>TextDecorationStyle.double</code>:</p>
<p><a href="https://i.stack.imgur.com/q3eBT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q3eBT.png" alt="enter image description here"></a></p>
<p>and <code>TextDecorationStyle.wavy</code>:</p>
<p><a href="https://i.stack.imgur.com/YIQnj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YIQnj.png" alt="enter image description here"></a></p> |
53,254,017 | React Hooks and Component Lifecycle Equivalent | <p>What are the equivalents of the <code>componentDidMount</code>, <code>componentDidUpdate</code>, and <code>componentWillUnmount</code> lifecycle hooks using React hooks like <code>useEffect</code>?</p> | 53,254,018 | 4 | 1 | null | 2018-11-11 22:49:26 UTC | 28 | 2021-08-07 02:12:03.697 UTC | null | null | null | null | 1,751,946 | null | 1 | 39 | javascript|reactjs|react-hooks | 15,591 | <h2><code>componentDidMount</code></h2>
<p>Pass an empty array as the second argument to <code>useEffect()</code> to run only the callback on mount only.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ComponentDidMount() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('componentDidMount');
}, []);
return (
<div>
<p>componentDidMount: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentDidMount />
</div>,
document.querySelector("#app")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p>
<h2><code>componentDidUpdate</code></h2>
<p><code>componentDidUpdate()</code> is invoked immediately after updating occurs. This method is not called for the initial render. <code>useEffect</code> runs on every render including the first. So if you want to have a strict equivalent as <code>componentDidUpdate</code>, you have to use <code>useRef</code> to determine if the component has been mounted once. If you want to be even stricter, use <code>useLayoutEffect()</code>, but it fires synchronously. In most cases, <code>useEffect()</code> should be sufficient.</p>
<p>This <a href="https://stackoverflow.com/a/53254028/1751946">answer is inspired by Tholle</a>, all credit goes to him.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ComponentDidUpdate() {
const [count, setCount] = React.useState(0);
const isFirstUpdate = React.useRef(true);
React.useEffect(() => {
if (isFirstUpdate.current) {
isFirstUpdate.current = false;
return;
}
console.log('componentDidUpdate');
});
return (
<div>
<p>componentDidUpdate: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<ComponentDidUpdate />,
document.getElementById("app")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p>
<h2><code>componentWillUnmount</code></h2>
<p>Return a callback in useEffect's callback argument and it will be called before unmounting.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ComponentWillUnmount() {
function ComponentWillUnmountInner(props) {
React.useEffect(() => {
return () => {
console.log('componentWillUnmount');
};
}, []);
return (
<div>
<p>componentWillUnmount</p>
</div>
);
}
const [count, setCount] = React.useState(0);
return (
<div>
{count % 2 === 0 ? (
<ComponentWillUnmountInner count={count} />
) : (
<p>No component</p>
)}
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentWillUnmount />
</div>,
document.querySelector("#app")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p> |
29,767,084 | Convert between LocalDate and XMLGregorianCalendar | <p>What's the best way to convert between <code>LocalDate</code> from Java 8 and <code>XMLGregorianCalendar</code>?</p> | 29,770,443 | 4 | 2 | null | 2015-04-21 08:42:02.437 UTC | 9 | 2019-03-05 09:38:32.93 UTC | null | null | null | null | 2,224,996 | null | 1 | 60 | java|java-8|converter|java-time | 77,333 | <p>Converting from <code>LocalDate</code> to <code>XMLGregorianCalendar</code>:</p>
<pre><code>LocalDate date = LocalDate.now();
GregorianCalendar gcal = GregorianCalendar.from(date.atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
</code></pre>
<p>Converting back is simpler:</p>
<pre><code>xcal.toGregorianCalendar().toZonedDateTime().toLocalDate();
</code></pre> |
4,621,313 | Using javax.xml.ws.Endpoint with HTTPS | <p>I'm working on a project to control light and heating in buildings. The backend (written in Java) will run on a Mac Mini and should be accessible via SOAP. </p>
<p>I want to keep the complexity of this project to a minimum because I don't want everyone using it having to set up an application server. So up till now I worked with javax.xml.ws.Endpoint:</p>
<pre><code> Endpoint endpoint = Endpoint.create(frontendInterface);
String uri = "http://"+config.getHost()+":"+config.getPort()+config.getPath();
endpoint.publish(uri);
</code></pre>
<p>This works surprisingly well (hey, when did you last see something in Java working with just 3 lines of code?), but now I'm looking for a way to use HTTPS instead of HTTP. </p>
<p>Is there a way to do this without using an application server or is there another way to secure this connection?</p>
<p>Greetings,
Marek</p> | 4,737,168 | 1 | 0 | null | 2011-01-07 00:02:24.847 UTC | 11 | 2019-11-25 19:26:33.3 UTC | 2011-01-07 00:20:24.64 UTC | null | 142,162 | null | 496,118 | null | 1 | 10 | java|soap|https | 15,010 | <p>For server:</p>
<pre><code>SSLContext ssl = SSLContext.getInstance("TLS");
KeyManagerFactory keyFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance("JKS");
store.load(new FileInputStream(keystoreFile),keyPass.toCharArray());
keyFactory.init(store, keyPass.toCharArray());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(store);
ssl.init(keyFactory.getKeyManagers(),
trustFactory.getTrustManagers(), new SecureRandom());
HttpsConfigurator configurator = new HttpsConfigurator(ssl);
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(hostname, port), port);
httpsServer.setHttpsConfigurator(configurator);
HttpContext httpContext = httpsServer.createContext(uri);
httpsServer.start();
endpoint.publish(httpContext);
</code></pre>
<p>For client, be sure you do this:</p>
<pre><code>System.setProperty("javax.net.ssl.trustStore", "path");
System.setProperty("javax.net.ssl.keyStore", "password");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
//done to prevent CN verification in client keystore
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
</code></pre> |
34,615,898 | React Server side rendering of CSS modules | <p>The current practice for CSS with React components seems to be using webpack's style-loader to load it into the page in.</p>
<pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react';
import style from './style.css';
class MyComponent extends Component {
render(){
return (
<div className={style.demo}>Hello world!</div>
);
}
}
</code></pre>
<p>By doing this the style-loader will inject a <code><style></code> element into the DOM. However, the <code><style></code> will not be in the virtual DOM and so if doing server side rendering, the <code><style></code> will be omitted. This cause the page to have <a href="https://en.wikipedia.org/wiki/Flash_of_unstyled_content" rel="noreferrer">FOUC</a>.</p>
<p>Is there any other methods to load <a href="https://github.com/css-modules/css-modules" rel="noreferrer">CSS modules</a> that work on both server and client side?</p> | 34,861,808 | 3 | 3 | null | 2016-01-05 15:57:15.627 UTC | 14 | 2019-06-13 23:44:49.057 UTC | null | null | null | null | 278,477 | null | 1 | 37 | reactjs|webpack|webpack-style-loader | 22,102 | <p>You can have a look at the <a href="https://github.com/kriasoft/isomorphic-style-loader" rel="nofollow noreferrer">isomorphic-style-loader</a>. The loader was specifically created to solve this kind of issues.</p>
<p>However for using this you have to use an <code>_insertCss()</code> method provided by the loader. The documentation details how to use it.</p>
<p>Hope it helped.</p> |
34,579,099 | Fatal error: Uncaught Error: Call to undefined function mysql_connect() | <p>I am trying to do a simple connection with XAMPP and MySQL server, but whenever I try to enter data or connect to the database, I get this error.</p>
<blockquote>
<p>Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\register.php:22<br>
Stack trace: #0 {main} thrown in C:\xampp\htdocs\register.php on line 22</p>
</blockquote>
<p>Example of line 22:</p>
<pre><code>$link = mysql_connect($mysql_hostname , $mysql_username);
</code></pre> | 34,579,855 | 9 | 5 | null | 2016-01-03 16:55:16.297 UTC | 32 | 2022-02-24 01:36:27.58 UTC | 2018-02-15 22:55:00.667 UTC | null | 664,833 | null | 3,656,666 | null | 1 | 83 | php|mysql|xampp | 918,347 | <p><code>mysql_*</code> functions have been removed in PHP 7.</p>
<p>You probably have PHP 7 in XAMPP. You now have two alternatives: <a href="http://www.php.net/manual/en/book.mysqli.php" rel="nofollow noreferrer">MySQLi</a> and <a href="http://www.php.net/manual/en/book.pdo.php" rel="nofollow noreferrer">PDO</a>.</p> |
39,466,432 | Adding a column with a Default value? | <p>I am adding a column to my database table. It is a simple Char column with either a value of 'Y' or 'N'. </p>
<p>Is it possible to default the column to be 'N'? If so, how?</p>
<p>Current Script to add column:</p>
<pre><code>ALTER TABLE PERSON
ADD IS_ACTIVE VARCHAR2(1);
</code></pre> | 39,466,477 | 7 | 2 | null | 2016-09-13 09:20:34.647 UTC | 2 | 2017-08-24 18:44:29.917 UTC | 2016-09-13 09:22:57.703 UTC | null | 330,315 | null | 5,528,751 | null | 1 | 2 | sql|oracle|ddl|column-defaults | 74,401 | <pre><code>ALTER TABLE PERSON
ADD IS_ACTIVE VARCHAR2(1) DEFAULT 'N'
</code></pre>
<p>If you want, you can add a NOT NULL constraint:</p>
<pre><code>ALTER TABLE PERSON
ADD IS_ACTIVE VARCHAR2(1) DEFAULT 'N' NOT NULL
</code></pre> |
20,361,444 | Cropping an image with Python Pillow | <p>I installed Python <a href="https://en.wikipedia.org/wiki/Python_Imaging_Library" rel="noreferrer">Pillow</a> and am trying to crop an image.</p>
<p>Other effects work great (for example, thumbnail, blurring image, etc.)</p>
<p>Whenever I run the code below I get the error:</p>
<blockquote>
<p>tile cannot extend outside image</p>
</blockquote>
<pre><code>test_image = test_media.file
original = Image.open(test_image)
width, height = original.size # Get dimensions
left = width/2
top = height/2
right = width/2
bottom = height/2
cropped_example = original.crop((left, top, right, bottom))
cropped_example.show()
</code></pre>
<p>I used a cropping example I found for <a href="https://en.wikipedia.org/wiki/Python_Imaging_Library" rel="noreferrer">PIL</a>, because I couldn't find one for Pillow (which I assumed would be the same).</p> | 20,361,739 | 2 | 1 | null | 2013-12-03 20:53:25.323 UTC | 11 | 2022-03-18 20:16:33.133 UTC | 2020-08-17 10:30:43.187 UTC | null | 11,778,939 | null | 2,016,740 | null | 1 | 44 | python-3.x|image-processing|python-imaging-library | 77,595 | <p>The problem is with logic, not Pillow. Pillow is nearly 100% PIL compatible. You created an image of <code>0 * 0</code> (<code>left = right & top = bottom</code>) size. No display can show that. My code is as follows</p>
<pre><code>from PIL import Image
test_image = "Fedora_19_with_GNOME.jpg"
original = Image.open(test_image)
original.show()
width, height = original.size # Get dimensions
left = width/4
top = height/4
right = 3 * width/4
bottom = 3 * height/4
cropped_example = original.crop((left, top, right, bottom))
cropped_example.show()
</code></pre>
<p>Most probably this is not what you want. But this should guide you towards a clear idea of what should be done.</p> |
20,239,550 | difference between functional testing and system testing? | <p>I heard that system testing has two types</p>
<p>1)functional Testing
2)Non functional testing</p>
<p>But later in another website i have seen below statements</p>
<pre><code>In the types of functional testing following testing types should be cover:
Unit Testing
Smoke testing
Sanity testing
Integration Testing
Interface Testing
System Testing
Regression Testing
UAT
</code></pre>
<p>I am confused, Please clarify me that whether the system testing includes functional or functional testing includes system testing and the sequence of these testings(functional is performed first or system)</p>
<p>Thanks</p> | 20,239,807 | 6 | 1 | null | 2013-11-27 10:13:52.69 UTC | 4 | 2015-09-25 11:10:17.94 UTC | null | null | null | null | 3,041,254 | null | 1 | 12 | testing|functional-testing|system-testing | 52,301 | <p>Functional testing aims to figure out whether given functionality works as specified. System testing aims to figure out whether the whole system fulfills the requirements given to it.</p>
<p>So in functional testing you test that given part of the whole system functions in a specified way. And in system testing you test the system as a whole fulfills the requirements given to it.</p>
<p>For example testing that 1+1=2 tests the plus function and sum function. And thus is a functional test. Testing whether user can calculate correct amount of tip using the calculator or not, is a system test, since it tests a requirement (calculate tip), but not a specific function of the application.</p>
<p>And non-functional testing includes stuff like usability and performance.</p> |
55,298,422 | React Native FlatList not scrolling to end | <p>I've got (what I thought was) a simple <code>FlatList</code> which renders a list of <code>Cards</code> (code below)</p>
<p><strong>Problem</strong>: the list renders, but won't scroll to fully display the last element in the list, OR to the content below the <code>FlatList</code></p>
<p><strong>What I've tried</strong>: basically everything in related SO questions: </p>
<ul>
<li>Removing ALL styling </li>
<li>Wrapping the <code>FlatList</code> in a <code>View</code> or a <code>ScrollView</code> or both</li>
<li>Adding <code>style={{flex: 1}}</code> to the <code>FlatList</code> or wrappers (this causes **ALL* content to disappear)</li>
</ul>
<p>Any ideas? </p>
<pre><code><FlatList
data={props.filteredProducts}
renderItem={({item}) => (
<TouchableOpacity onPress={() => props.addItemToCart(item)}>
<Card
featuredTitle={item.key}
image={require('../assets/icon.png')}
/>
</TouchableOpacity>
)}
keyExtractor={item => item.key}
ListHeaderComponent={
<SearchBar />
}
/>
...
<Other Stuff>
</code></pre> | 59,183,680 | 11 | 3 | null | 2019-03-22 11:13:40.18 UTC | 5 | 2021-05-18 13:55:53.003 UTC | null | null | null | null | 3,783,510 | null | 1 | 34 | react-native|react-native-flatlist|react-native-elements | 31,005 | <p>Add <code>style={{flex: 1}}</code> for each View element who is a parent for FlatList.</p> |
7,211,704 | jQuery order by date in data attribute | <p>If i have this markup:</p>
<pre><code><p data-date="Fri, 26 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 24 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 25 Aug 2011 20:58:39 GMT">item 1</p>
</code></pre>
<p>How could i use jQuery to order these P's by their data-date attribute?</p>
<p>Thanks</p> | 7,211,762 | 3 | 1 | null | 2011-08-27 00:19:18.567 UTC | 10 | 2014-01-04 13:23:15.053 UTC | null | null | null | null | 478,144 | null | 1 | 11 | jquery | 24,777 | <h2><a href="http://jsfiddle.net/CQ3gg/2" rel="noreferrer">Demo</a></h2>
<p>Super simple with an array sort:</p>
<pre><code>$("p").sort(function(a,b){
return new Date($(a).attr("data-date")) > new Date($(b).attr("data-date"));
}).each(function(){
$("body").prepend(this);
})
</code></pre>
<p>Reverse order (in case I misunderstood you) is as easy as flipping the greater than symbol</p>
<pre><code>$("p").sort(function(a,b){
return new Date($(a).attr("data-date")) < new Date($(b).attr("data-date"));
}).each(function(){
$("body").prepend(this);
})
</code></pre> |
7,205,937 | Why do browsers allow onmousedown JS to change href? | <p>I've noticed for a very long time that when you try to copy a link location or open a link on Facebook, it modifies the link and passes it through <code>l.php</code>. </p>
<p>For example, I can be sent to </p>
<pre><code> http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.google.com%2F&h=DKVUritNDJDJLDLVbldoDLFKBLOD5dlfDJY_-d3fgDUaA9b
</code></pre>
<p>even though my browser render the link preview as <code>http://www.google.com/</code>. </p>
<p>Today, I took a closer look using Firebug and found that Facebook puts <code>onmousedown="UntrustedLink.bootstrap($(this)[...]</code> in the <code><a></code> tag. The second I right clicked the link, I saw the <code>href</code> attribute change in Firebug.</p>
<p>This worries me.</p>
<p>The advice many of us have given to less tech-savvy people (check where the link is taking you before you click so that you don't become a victim of phishing) now seems to have become useless. Isn't this a security risk? Can't phishing websites misuse this? </p>
<p>Why don't browsers prevent this behavior either by disallowing <code>onmousedown</code> to change the <code>href</code> or by running the javascript before reading the <code>href</code> attribute, so that I am sent to the location I thought I going to, not the one change while I was clicking it?</p>
<p><strong>Edit</strong>: I want to briefly emphasize that what bothers me more than the risk of phishing is that users are being misled and it simply feels wrong to me that this can happen, whether by a trusted source or not.</p> | 7,207,641 | 3 | 2 | null | 2011-08-26 14:10:29.577 UTC | 10 | 2015-10-22 12:17:14.113 UTC | 2011-08-26 15:06:15.103 UTC | null | 15,416 | null | 345,813 | null | 1 | 21 | javascript|security|href|phishing | 1,954 | <p>I agree that there is potential here for phishing. This was reported as a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=229050" rel="nofollow">bug in FireFox</a> quite a long time ago, but the problem is this:</p>
<pre><code><body onmousedown="document.getElementById('changeMe').href='www.somewhereelse.com'">
<a id="changeMe" href="www.google.com">google</a>
</body>
</code></pre>
<p>Events bubble up to their parent, you would need to detect if an onmousedown event was going to change the href of a child element. Sounds reasonable? Okay, how about this:</p>
<pre><code><script>
function switcher() {
window.location = "www.somewhereelse.com";
return false;
}
</script>
<body onmousedown="switcher()">
<a href="www.google.com">google</a>
</body>
</code></pre>
<p>So we need to look out for <code>window.location</code> in functions triggered by onmousedown events as well. Still sound reasonable? How about if I have the onmousedown event remove the link altogether, replace it with a new element and then trigger the click on that. I can keep coming up with examples.</p>
<p>The point is, Javascript can be used to misdirect people using the status bar - you shouldn't trust it, you can only trust the URL.</p>
<p>To change this browsers would need to give the set href value on a link at the time of the click presidency over any other events that might happen, basically disable mouse events on anchor tags. I would venture to guess they probably won't do this, it would break too many applications that already exist.</p>
<p><strong>Edit:</strong> Alternatively, I've seen people propose different methods of detecting and warning the user about possible link hijacking, but I've not seen any implemented yet.</p> |
7,136,615 | Open delegate for generic interface method | <p>I'm trying to create an <a href="http://peisker.net/dotnet/languages2005.htm#delegatetargets" rel="noreferrer">open instance delegate</a> for a generic interface method, but I keep receiving a NotSupportedException. Here is the simplified code that won't run:</p>
<pre><code>interface IFoo
{
void Bar<T>(T j);
}
class Foo : IFoo
{
public void Bar<T>(T j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar").MakeGenericMethod(typeof(int));
var x = Delegate.CreateDelegate(typeof(Action<IFoo, int>), null, bar);
}
</code></pre>
<p>The last line throws NotSupportedException, "Specified method is not supported". By comparison, a non-generic open instance delegate runs fine:</p>
<pre><code>interface IFoo
{
void Bar(int j);
}
class Foo : IFoo
{
public void Bar(int j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar");
var x = Delegate.CreateDelegate(typeof(Action<IFoo, int>), null, bar);
}
</code></pre>
<p>And a closed generic delegate also works:</p>
<pre><code>interface IFoo
{
void Bar<T>(T j);
}
class Foo : IFoo
{
public void Bar<T>(T j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar").MakeGenericMethod(typeof(int));
var x = Delegate.CreateDelegate(typeof(Action<int>), new Foo(), bar);
}
</code></pre>
<p>So the recipe for closed generic delegates and open instance delegates work separately, but not when combined. It's starting to look like either a runtime bug, or intentional omission. Anyone have any insight here?</p> | 7,368,641 | 3 | 5 | null | 2011-08-21 05:37:56.08 UTC | 13 | 2011-09-19 15:34:03.673 UTC | 2011-08-21 14:39:09.813 UTC | null | 144,873 | null | 144,873 | null | 1 | 26 | c#|generics|delegates | 3,790 | <p><a href="http://connect.microsoft.com/VisualStudio/feedback/details/685053/open-instance-delegate-to-generic-interface-method-does-not-work" rel="nofollow">Microsoft has answered</a> that it's a known problem that the CLR can't do this, but it can't be solved in the current version of .NET. It's still not at all clear <em>why</em> this isn't possible as I explain there. Open delegates must not reuse the dispatching logic used everywhere else in the CLR for some reason, which just seems bizarre to me.</p> |
7,439,192 | Xcode: Copy Headers: Public vs. Private vs. Project? | <p>I'm building a Cocoa Touch Static Library. How should I decide whether to copy a header file as public, private, or project?</p> | 8,016,333 | 3 | 0 | null | 2011-09-16 01:18:39.92 UTC | 27 | 2021-04-25 18:48:08.033 UTC | 2017-12-11 10:34:54.013 UTC | null | 1,363,156 | null | 242,933 | null | 1 | 75 | xcode|header|static-libraries | 26,733 | <blockquote>
<p><strong>Public:</strong> The interface is finalized and meant to be used by your product’s clients. A public header is included in the product as readable source code without restriction.</p>
<p><strong>Private:</strong> The interface isn’t intended for your clients or it’s in early stages of development. A private header is included in the product, but it’s marked “private”. Thus the symbols are visible to all clients, but clients should understand that they're not supposed to use them.</p>
<p><strong>Project:</strong> The interface is for use only by implementation files in the current project. A project header is not included in the target, except in object code. The symbols are not visible to clients at all, only to you.</p>
</blockquote>
<p><strong>Source:</strong> Xcode Developer Library > Tools & Languages > IDEs > Project Editor Help > Setting the Visibility of a Header File</p> |
7,046,154 | How to Add ViewPager Indicator Headings Like Google+ App | <p>My goal is to create a screen similar in function to the Stream page in the Google+ app (picture below for those unfamiliar). For the paging, I am using a custom <code>ViewGroup</code> so that it has smooth transitions that "follow your finger" rather than just snapping to the destination after the fling gesture has been made.</p>
<p><strong>Question</strong></p>
<p>Currently, I am going the route of using some <code>TranslateAnimation</code>s to move the headings ("Nearby," "All circles," and "Incoming" in the screenshot) once a new page has been selected. This creates a couple of problems: the center heading doesn't follow the user's finger (as you can see the "All circles" heading does in the screenshot), and if the user begins on a page other than the middle one, I have not found an easy way to offset all of the animations temporarily without running them first since the animations do not move the actual views.</p>
<p>Am I going about this the correct way, or is there a much simpler way of accomplishing this that I am overlooking?</p>
<p>Thanks</p>
<p><img src="https://i.stack.imgur.com/OT0uA.png" alt=""></p> | 7,053,634 | 4 | 1 | null | 2011-08-12 20:49:28.09 UTC | 13 | 2012-08-18 09:48:20.673 UTC | 2011-08-15 16:17:47.023 UTC | null | 778,427 | null | 778,427 | null | 1 | 15 | android | 11,691 | <p>After hours of searching and a little luck with search terms, I came across <a href="http://www.zylinc.com/blog-reader/items/viewpager-page-indicator.html" rel="nofollow">A Google+ like ViewPager page indicator</a>.</p>
<p>I also came across <a href="https://github.com/JakeWharton/Android-ViewPagerIndicator" rel="nofollow">Android ViewPager Indicator</a>, created by the same developer who wrote ActionBarSherlock. Has a ton of examples, and is pretty easy to integrate with the FragmentPagerAdapter.</p> |
24,172,860 | How can Xcode 6 adaptive UIs be backwards-compatible with iOS 7 and iOS 6? | <p>I just watched the WWDC video #216, "Building Adaptive UI with UIKit."</p>
<p>At about 45:10 Tony Ricciardi talks about changes to IB in Xcode 6 to support the new changes. </p>
<p>He says "You can deploy these documents backwards to older versions of iOS".</p>
<p>(where "These documents" presumably means XIBs and storyboards that have specific settings for different size classes.)</p>
<p>I'm not making this up. Go watch the WWDC video.</p>
<p>How is that possible? Trait collections and size classes are only defined in iOS 8. How can runtime behavior that's dependent on UI constructs that are new to iOS 8 work in previous iOS versions?</p>
<p>If it <strong>is</strong> possible it would be wonderful. You could build apps that will run on iOS 6, 7, and 8, and take advantage of the new flexible UI layout abilities that Apple has added to Xcode 6. I've created adaptive UI logic myself in code, and it's quite a bit of work. </p> | 24,976,792 | 8 | 1 | null | 2014-06-11 21:26:32.077 UTC | 91 | 2014-12-23 12:57:24.79 UTC | 2014-09-11 01:47:35.28 UTC | null | 205,185 | null | 205,185 | null | 1 | 137 | xcode6|adaptive-ui | 42,733 | <p>Changes made to the UI with Size Classes in Interface Builder DO appear correctly on iOS 7 devices and the Preview in Xcode. For example, I changed some Auto Layout constraints and font sizes for Regular height Regular width and those changed constraints are visible in the iPad Simulator running iOS 7.0.</p>
<p>All size class optimizations are made available to iOS 7, except size classes that have a Compact Height. This has been confirmed by Apple and is now stated directly in the <a href="https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/DeployingSizeClassesonEarlieriOSVersions.html#//apple_ref/doc/uid/TP40014436-CH13-SW1" rel="noreferrer">documentation</a>:</p>
<p><strong>For apps supporting versions of iOS earlier than iOS 8, most size classes are backward compatible.<br><br>
Size classes are backward compatible when:<br>
- The app is built using Xcode version 6 or later<br>
- The deployment target of the app is earlier than iOS 8<br>
- Size classes are specified in a storyboard or xib<br>
- The value of the height component is not compact</strong></p>
<p>Because iOS 7 doesn't respect a couple of size classes, if you use them you'll run into issues. For example:
When you have Compact w Any h defined and then Compact w Compact h defined, on iOS 7 it will respect the Compact w Any h but on iOS 8 it renders the Compact w Compact h appearance.</p>
<p>So, if you would like to utilize those two size classes and maintain compatibility with iOS 7, I would do any optimizations you desire for iPhone in landscape in Any w Any h or Compact w Any h, then perform your other optimizations for different size classes as necessary, and that way you won't need to use any size class with compact height and will avoid running into issues.</p> |
7,949,040 | Restoring content when clicking back button with History.js | <p>I've implemented History.js on a local test application. Everything seems to work, however if I press the back button in the browser, the previous content does not get restored.</p>
<p>Do I actually have to load the content manually again (i.e. make another ajax call) when user presses the back button? Then how does github do it? I see they don't make another ajax call when clicking back button in the code tree.</p>
<p>Here is my code:</p>
<pre><code>History.Adapter.bind(window,'statechange',function()
{
var State = History.getState();
History.log(State.data, State.title, State.url);
});
$('a').each(function(index, link) {
if ($(link).attr('data-ajax-disabled') != 'true') {
$(link).click(function(event)
{
var clips = $(this).attr('data-ajax-clips') || '';
$.ajax($(this).attr('href'),
{
data: {_clips:clips},
success: function(data)
{
var data = $.parseJSON(data);
History.pushState({state:1}, data.title || document.title, 'http://127.0.0.1/site/www/');
$.each(data.clips, function(key, val)
{
$(key).replaceWith(val);
});
}
});
return false;
});
}
});
</code></pre>
<p>data.clips is a json array which contains id's of html objects as key and the actual html content as value. For example</p>
<blockquote>
<p>'#header' => 'content in header div'</p>
</blockquote>
<p>As noted, the replacement works fine. I output a random number in the header. Every click on a link spits out another random number in the header. However, if I push the back button the number stays the same, only the title will be restored (also random number).</p> | 7,952,739 | 1 | 1 | null | 2011-10-31 00:52:36.29 UTC | 8 | 2016-07-20 12:13:04.023 UTC | 2016-07-20 12:13:04.023 UTC | null | 30,512 | null | 990,827 | null | 1 | 13 | javascript|history.js|html5-history | 9,939 | <p>Ok I got it, also thanks to Tobias Cohen for the hint.</p>
<p>One has to store the loaded data in the history object (State.data). First let's see how the statechange callback changed:</p>
<pre><code>History.Adapter.bind(window, 'statechange', function()
{
var State = History.getState();
$.each(State.data.clips, function(key, val)
{
$(key).replaceWith(val);
});
History.log(State.data, State.title, State.url);
});
</code></pre>
<p>As you can see, on each statechange I can access State.data.clips and replace the html content.</p>
<p>NOTE: A statechange does also happen when calling History.pushState(). That means in my initial question the second code snippet is wrong in the fact that I do the content manipulation in there. There's no need for it. Just call History.pushState() and do any content manipulation within the statechange callback.</p>
<p>So for completeness, this is how I push the clips into the history object:</p>
<pre><code>History.pushState({state:1, clips:data.clips}, data.title || document.title, 'http://127.0.0.1/site/www/');
</code></pre> |
1,964,478 | Displaying exception debug information to users | <p>I'm currently working on adding exceptions and exception handling to my OSS application. Exceptions have been the general idea from the start, but I wanted to find a good exception framework and in all honesty, understand C++ exception handling conventions and idioms a bit better before starting to use them. I have a lot of experience with C#/.Net, Python and other languages that use exceptions. I'm no stranger to the idea (but far from a master). </p>
<p>In C# and Python, when an unhandled exception occurs, the user gets a nice stack trace and in general a lot of <strike>very useful</strike> priceless debugging information. If you're working on an OSS application, having users paste that info into issue reports is... well let's just say I'm finding it difficult to live without that. For this C++ project, I get "The application crashed", or from more informed users, "I did X, Y and Z, and then it crashed". But I want that debugging information too!</p>
<p>I've already (and with great difficulty) made my peace with the fact that I'll never see a cross-platform and cross-compiler way of getting a C++ exception stack trace, but I know I can get the function name and other relevant information.</p>
<p>And now I want that for my unhandled exceptions. I'm using <a href="http://www.boost.org/doc/libs/1_41_0/libs/exception/doc/boost-exception.html" rel="noreferrer">boost::exception</a>, and they have this very nice <a href="http://www.boost.org/doc/libs/1_41_0/libs/exception/doc/diagnostic_information.html" rel="noreferrer">diagnostic_information</a> thingamajig that can print out the (unmangled) function name, file, line and most importantly, other exception specific information the programmer added to that exception.</p>
<p>Naturally, I'll be handling exceptions inside the code whenever I can, but I'm not that naive to think I won't let a couple slip through (unintentionally, of course).</p>
<p>So what I want to do is wrap my main entry point inside a <code>try</code> block with a <code>catch</code> that creates a special dialog that informs the user that an error has occurred in the application, with more detailed information presented when the user clicks "More" or "Debug info" or whatever. This would contain the string from diagnostic_information. I could then instruct the users to paste this information into issue reports. </p>
<p>But a nagging gut feeling is telling me that wrapping everything in a try block is a really bad idea. Is what I'm about to do stupid? If it is (and even if it's not), what's a better way to achieve what I want?</p> | 1,964,490 | 4 | 0 | null | 2009-12-26 21:55:51.333 UTC | 11 | 2010-01-14 07:34:18.063 UTC | null | null | null | null | 146,752 | null | 1 | 7 | c++|debugging|boost|exception|debug-information | 6,533 | <p>Wrapping all your code in one <code>try/catch</code> block is a-ok. It won't slow down the execution of anything inside it, for example. In fact, all my programs have (code similar to) this framework:</p>
<pre><code>int execute(int pArgc, char *pArgv[])
{
// do stuff
}
int main(int pArgc, char *pArgv[])
{
// maybe setup some debug stuff,
// like splitting cerr to log.txt
try
{
return execute(pArgc, pArgv);
}
catch (const std::exception& e)
{
std::cerr << "Unhandled exception:\n" << e.what() << std::endl;
// or other methods of displaying an error
return EXIT_FAILURE;
}
catch (...)
{
std::cerr << "Unknown exception!" << std::endl;
return EXIT_FAILURE;
}
}
</code></pre> |
2,237,222 | How to correctly close a feature branch in Mercurial? | <p>I've finished working on a feature branch <code>feature-x</code>. I want to merge results back to the <code>default</code> branch and close <code>feature-x</code> in order to get rid of it in the output of <code>hg branches</code>.</p>
<p>I came up with the following scenario, but it has some issues:</p>
<pre><code>$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
</code></pre>
<p>So the <code>feature-x</code> branch (changests <code>40</code>-<code>41</code>) is closed, but there is <em>one new head</em>, the closing branch changeset <code>44</code>, that will be listed in <code>hg heads</code> every time:</p>
<pre><code>$ hg log ...
o 44 Closed branch feature-x
|
| @ 43 merge
|/|
| o 42 Changeset C
| |
o | 41 Changeset 2
| |
o | 40 Changeset 1
|/
o 39 Changeset B
|
o 38 Changeset A
|
</code></pre>
<p><strong>Update</strong>: It appears that since version 1.5 Mercurial doesn't show heads of closed branches in the output of <code>hg heads</code> anymore.</p>
<p>Is it possible to close a merged branch without leaving one more head? Is there more correct way to close a feature branch?</p>
<p>Related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/3638987/is-there-a-downside-to-this-mercurial-workflow-named-branch-dead-head">Is there a downside to this Mercurial workflow: named branch "dead" head?</a></li>
</ul> | 2,239,306 | 4 | 3 | null | 2010-02-10 13:50:29.46 UTC | 105 | 2015-12-01 23:23:17.74 UTC | 2017-05-23 12:34:35.107 UTC | null | -1 | null | 187,103 | null | 1 | 242 | merge|mercurial|branch|hg-merge | 102,413 | <p>One way is to just leave merged feature branches open (and inactive):</p>
<pre><code>$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
feature-x 41:...
(2 branches)
$ hg branches -a
default 43:...
(1 branch)
</code></pre>
<p>Another way is to close a feature branch before merging using an extra commit:</p>
<pre><code>$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
(1 branch)
</code></pre>
<p>The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using <code>--close-branch</code>, but one should know in advance which commit will be the last one.</p>
<p><strong>Update</strong>: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both <code>hg branches</code> and <code>hg heads</code> anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.</p>
<p><strong>Update 2</strong>: Since Mercurial 1.8 <em>bookmarks</em> have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/1780778/mercurial-branching-and-bookmarks">Mercurial branching and bookmarks</a></li>
</ul> |
10,646,978 | Returning List<T> with WCF service | <p>I got an <code>Employee</code> class and each employee has a list of applied leaves. Is it possible to have the list <code>AppliedLeave</code> as a <code>[DataMember]</code> in WCF?</p>
<pre><code>[DataContract]
public class Employee
{
[DataMember]
public string UserID { get; set; }
[DataMember]
public int EmployeeNumber { get; set; }
[ForeignKey("EmployeeUserID")]
[DataMember]
public List<Leave> AppliedLeave
{
get { return _appliedLeaves; }
set { _appliedLeaves = value; }
}
private List<Leave> _appliedLeaves = new List<Leave>();
...
}
</code></pre>
<p>Is there any other way to do this?</p>
<p>thank you for your consideration of this matter</p>
<p><strong>I extend my Question</strong></p>
<p>This is my Leave Class:</p>
<pre><code>[DataContract]
public class Leave
{
[Key()]
[DataMember]
public Guid LeaveId { get; set; }
[DataMember]
public string LeaveType { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public string EmployeeUserID { get; set; }
}
</code></pre>
<p>this shows ServiceContract ----></p>
<pre><code>[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee GetEmployeeByUserId(string userId);
[OperationContract]
void AssignSupervisor(string userId, string supervisorUserId);
[OperationContract]
void DeleteEmployeeByUserId(string userId);
....
}
</code></pre>
<p>In Client application,</p>
<blockquote>
<p>EmployeeServiceClient employeeService = new EmployeeServiceClient();</p>
<p>Employee employee = employeeService.GetEmployeeByUserId(id);</p>
</blockquote>
<p>But when Employee gathered from the service its shows Null for leaves,</p>
<p><img src="https://i.stack.imgur.com/Sdb01.png" alt="enter image description here" /></p>
<p>Can somebody help me? what have I done wrong here?</p> | 10,647,027 | 3 | 2 | null | 2012-05-18 05:05:46.32 UTC | 1 | 2018-10-24 13:38:21.2 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,134,291 | null | 1 | 3 | c#|wcf | 41,937 | <p>Yes, it is possible to return generics from WCF service operations.</p>
<p>But by default they are casted to Array on client side. This can be customized while proxy generation.</p>
<p><a href="http://jeffbarnes.net/blog/post/2007/05/10/WCF-Serialization-and-Generics.aspx" rel="noreferrer">WCF: Serialization and Generics</a></p>
<p>Also you have to decorate the service with all the types to which generics can be resolved, using KnownTypeAttribute.</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/gg598929.aspx" rel="noreferrer">Known Types and the Generic Resolver</a></p> |
28,725,727 | VS 2015 + Bower: Does not work behind firewall | <h2>Problem</h2>
<p>In Visual Studio 2015, using bower, my package restores fail when behind a firewall with an error similar to:</p>
<blockquote>
<p>ECMDERR Failed to execute "git ls-remote --tags --heads git://github.com/jzaefferer/jquery-validation.git", exit code of #-532462766</p>
</blockquote>
<p>I have updated my git config to use <code>http</code> instead of git. When I run from my command line, the command is successful:</p>
<p><img src="https://i.stack.imgur.com/PGidw.png" alt="enter image description here"></p>
<p>But Visual Studio or one of its components appears to be using <code>git</code> instead of <code>http</code> regardless.</p>
<h2>Background & First Attempt to Resolve</h2>
<p>Using Visual Studio 2015 and Bower for package management. It works great when not behind a firewall, but when behind a firewall I cannot use the <code>git://</code> protocol.</p>
<p>The solution -- documented in many other places on SO (<a href="https://stackoverflow.com/questions/15669091/bower-install-using-only-https">example</a>), is to run:</p>
<pre><code>git config --global url."http://".insteadOf git://
</code></pre>
<p>I did this, and now my <code>git config -l</code> looks like:</p>
<pre><code>ore.symlinks=false
core.autocrlf=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=Sean Killeen
[email protected]
url.http://.insteadof=git://
</code></pre>
<p>But despite this, either Visual Studio / npm is not respecting my configuration, or is using an old, cached version of it.</p>
<h2>Second Attempt to Resolve</h2>
<p>Per <a href="https://github.com/npm/npm/issues/5257#issuecomment-60441477" rel="nofollow noreferrer">this thread on npm issue</a>, I saw that npm (which presumably bower is using in VS) uses the <code>git@</code> syntax. Even though this isn't what I saw in the output, I figured I'd give it a shot.</p>
<p>I ran:</p>
<pre><code>git config --global url."https://github.com/".insteadOf [email protected]:
</code></pre>
<p>I then restarted Visual Studio, but the issue still persists. The fix I'd read about was likely never applicable.</p>
<p>Any ideas on how to fix?</p> | 31,538,406 | 12 | 4 | null | 2015-02-25 17:31:24.213 UTC | 14 | 2016-06-13 08:56:22.267 UTC | 2017-05-23 12:02:26.617 UTC | null | -1 | null | 316,847 | null | 1 | 33 | git|bower|firewall|visual-studio-2015|git-config | 15,022 | <p>Same problem using VS 2015, my workaround :</p>
<ol>
<li><p>Install Git </p>
<p><a href="http://git-scm.com/">http://git-scm.com/</a></p></li>
<li><p>Configure Git to use http instead of git:// with Git Bash</p>
<p>git config --global url."http://".insteadOf git://</p>
<p><strong>Edit (as pointed by g.pickardou) you can use https to be more secure:</strong> </p>
<p>git config --global url."<strong>https</strong>://".insteadOf git://</p></li>
<li><p>Configure VS to use the new installed Git over VS Git</p>
<p>Right click on Bower folder (under Dependencies), then select "Configure external tools"</p>
<p>Uncheck "$(DevEnvDir)\Extensions\Microsoft\Web Tools\External\git"</p>
<p>Add a new node with "C:\Program Files (x86)\Git\bin"</p></li>
</ol>
<p>Hope this will help someone,</p>
<p>Rogerio</p> |
26,218,954 | Crop image in CSS | <p>I've created a two-column grid of images, which works fine with all-landscape images: <a href="http://www.mtscollective.com/2014/03/gallery-wonder-years-real-friends-and.html" rel="nofollow noreferrer">Link</a>. However, I've added a portrait image that throws off the layout, so I'd like to be able to "crop" the image so that the height matches the others'. <a href="http://cssglobe.com/3-easy-and-fast-css-techniques-for-faux-image/" rel="nofollow noreferrer">I tried using a negative margin</a>, but it had no effect:</p>
<pre class="lang-css prettyprint-override"><code>.portrait-crop
{
overflow: hidden;
}
img.portrait-crop
{
margin-bottom: -30px;
}
</code></pre>
<p>I'm not sure what I'm doing wrong. Any help would be appreciated.</p>
<p>For reference, <a href="http://jsfiddle.net/91z2wxfy/" rel="nofollow noreferrer">this is my code</a>.</p> | 26,219,379 | 9 | 1 | null | 2014-10-06 14:55:23.843 UTC | 2 | 2022-06-30 14:25:18.35 UTC | 2022-06-30 14:25:18.35 UTC | null | 5,941,620 | null | 2,086,597 | null | 1 | 12 | html|css|image|crop | 50,523 | <p>You need to put some height to the container also, if not, it doesn't know how much it should show of what it is inside.</p>
<p>You can try something like this.</p>
<pre><code>.portrait-crop{
display: inline-block;
height: 215px;
width: 50%;
overflow: hidden;
}
.portrait-crop img{
width: 100%;
}
</code></pre> |
7,540,801 | Core Data and threads / Grand Central Dispatch | <p>I'm a beginner with Grand Central Dispatch (GCD) and Core Data, and I need your help to use Core Data with CGD, so that the UI is not locked while I add 40.000 records to Core Data.</p>
<p>I know that CD is not thread safe, so I have to use another context, and then save the data and merge contexts, as far as I was able to understand from some articles.</p>
<p>What I couldn't do yet, is put the pieces together.</p>
<p>So, in my code, I need your help on how to to that.</p>
<p>I have:</p>
<pre><code>/*some other code*/
for (NSDictionary *memberData in arrayWithResult) {
//get the Activities for this member
NSArray *arrayWithMemberActivities = [activitiesDict objectForKey:[memberData objectForKey:@"MemberID"]];
//create the Member, with the NSSet of Activities
[Members createMemberWithDataFromServer:memberData
andActivitiesArray:arrayWithMemberActivities
andStaffArray:nil
andContactsArray:nil
inManagedObjectContext:self.managedObjectContext];
}
</code></pre>
<p>How can I transform this to work on the background, and then, when done saving, save the data and update the UI, without blocking the UI while saving the 40.000 objects?</p> | 7,545,514 | 6 | 0 | null | 2011-09-24 17:55:00.793 UTC | 46 | 2013-09-13 07:38:19.637 UTC | 2012-02-15 17:48:32.813 UTC | null | 644,348 | null | 473,230 | null | 1 | 42 | iphone|ios|multithreading|core-data|grand-central-dispatch | 14,591 | <p>Here's a good example for you to try. Feel free to come back if you have any questions:</p>
<pre><code>self.mainThreadContext... // This is a reference to your main thread context
NSPersistentStoreCoordinator *mainThreadContextStoreCoordinator = [self.mainThreadContext persistentStoreCoordinator];
dispatch_queue_t request_queue = dispatch_queue_create("com.yourapp.DescriptionOfMethod", NULL);
dispatch_async(request_queue, ^{
// Create a new managed object context
// Set its persistent store coordinator
NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
[newMoc setPersistentStoreCoordinator:mainThreadContextStoreCoordinator]];
// Register for context save changes notification
NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
[notify addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:newMoc];
// Do the work
// Your method here
// Call save on context (this will send a save notification and call the method below)
BOOL success = [newMoc save:&error];
if (!success)
// Deal with error
[newMoc release];
});
dispatch_release(request_queue);
</code></pre>
<p>And in response to the context save notification:</p>
<pre><code>- (void)mergeChanges:(NSNotification*)notification
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.mainThreadContext mergeChangesFromContextDidSaveNotification:notification waitUntilDone:YES];
});
}
</code></pre>
<p>And don't forget to remove the observer from the notification center once you are done with the background thread context.</p>
<pre><code>[[NSNotificationCenter defaultCenter] removeObserver:self];
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.