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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,194,439 | Sending commands to server via JSch shell channel | <p>I can't figure it out how I can send commands via JSch shell channel.</p>
<p>I do this, but it doesn't work:</p>
<pre><code>JSch shell = new JSch();
String command = "cd home/s/src";
Session session = shell.getSession(username, host, port);
MyUserInfo ui = new MyUserInfo();
ui.setPassword(password);
session.setUserInfo(ui);
session.connect();
channel = session.openChannel("shell");
fromServer = new BufferedReader(new InputStreamReader(channel.getInputStream()));
toServer = channel.getOutputStream();
channel.connect();
toServer.write((command + "\r\n").getBytes());
toServer.flush();
</code></pre>
<p>and then I read input like this:</p>
<pre><code>StringBuilder builder = new StringBuilder();
int count = 0;
String line = "";
while(line != null) {
line = fromServer.readLine();
builder.append(line).append("\n");
if (line.endsWith(".") || line.endsWith(">")){
break;
}
}
String result = builder.toString();
ConsoleOut.println(result);
</code></pre> | 7,503,273 | 10 | 5 | null | 2010-11-16 13:09:00.997 UTC | 11 | 2021-10-27 22:19:27.093 UTC | 2014-11-14 07:51:25.633 UTC | null | 850,848 | null | 493,575 | null | 1 | 27 | java|ssh|jsch | 82,019 | <p>If it hangs at <code>readLine()</code> that means either your "while" is never ending (might be unlikely considering your code), or, <code>readLine()</code> is waiting for its source, namely the <code>IOstream</code> blocks the thread cause <code>available()!=true</code>. </p>
<p>I can't quite troubleshoot your code without seeing your debug info. But as an advice, have you tried <code>PipedIntputStream</code>? The idea is to pipe your console input to "your" output so that you can "write" it. To implement this, you need to initialize the in/out-put.</p>
<pre><code>InputStream in = new PipedInputStream();
PipedOutputStream pin = new PipedOutputStream((PipedInputStream) in);
/**...*/
channel.setInputStream(in);
channel.connect();
/** ...*/
pin.write(myScript.getBytes());
</code></pre>
<p>The same goes to your question, how to read console output. </p>
<pre><code>PipedInputStream pout = new PipedInputStream((PipedOutputStream) out);
/**
* ...
*/
BufferedReader consoleOutput = new BufferedReader(new InputStreamReader(pout));
consoleOutput.readLine();
</code></pre>
<p>And again, if you are not sure how many lines to read and thus want to use "while", make sure you do something inside while to prevent 1) busy-waiting 2) ending-condition. Example:</p>
<pre><code>while(!end)
{
consoleOutput.mark(32);
if (consoleOutput.read()==0x03) end = true;//End of Text
else
{
consoleOutput.reset();
consoleOutput.readLine();
end = false;
}
}
</code></pre> |
4,099,975 | Difference between a module, library and a framework | <p>In popular programming speak, what is the difference between these terms and what are the overlaps?</p>
<p>Any related terms I'm missing out?</p> | 4,101,270 | 11 | 4 | null | 2010-11-04 18:32:09.72 UTC | 84 | 2021-12-28 18:02:22.277 UTC | null | null | null | null | 103,955 | null | 1 | 90 | frameworks|module | 55,258 | <p>All three of those provide functionality.</p>
<p>However, there are important differences.</p>
<p>A <strong>library</strong> is <em>just</em> a collection of related functionality. Nothing more, but also nothing less. The defining characteristic of a library is that <em>you</em> are in control, <em>you</em> call the library.</p>
<p>The defining characteristic of a <strong>framework</strong> is <em>Inversion of Control</em>. The framework calls <em>you</em>, not the other way round. (This is known as the <em>Hollywood Principle</em>: "Don't call us, we'll call you.") The framework is in control. The flow of control and the flow of data is managed by the framework.</p>
<p>You can think of it this way: in both cases, you have an application, and this application has holes in it, where code has been left out, and these holes need to be filled in. The difference between a library and a framework is</p>
<ul>
<li>who writes the application,</li>
<li>what are the holes and</li>
<li>who fills in the holes.</li>
</ul>
<p>With a library, <em>you</em> write the application, and you leave out the <em>boring</em> details, which gets filled in by a <em>library</em>.</p>
<p>With a framework, the <em>framework writer</em> writes the application, and leaves out the <em>interesting</em> details, which <em>you</em> fill in.</p>
<p>This can be a little confusing at times, because the framework itself might also contain boring details, that the framework author filled in with libraries, the parts that you write might contain boring details, that you fill in with libraries, and the framework might provide a set of bundled libraries that either work well with the framework or that are often needed in conjunction with the framework. For example, you might use an XML generator library when writing a web application using a web framework, and that XML library might have been provided by the framework or even be an integral part of it.</p>
<p>That doesn't mean, however, that there is no distinction between a library and a framework. The distinction is very clear: Inversion of Control is what it's all about.</p>
<p>The defining characteristic of a <strong>module</strong> is <em>information hiding</em>. A module has an <em>interface</em>, which explicitly, but abstractly specifies both the functionality it provides as well as the functionality it depends on. (Often called the <em>exported</em> and <em>imported</em> functionality.) This interface has an <em>implementation</em> (or multiple implementations, actually), which, from the user of a module are a black box.</p>
<p>Also, a library is a <em>collection</em> of related functionality, whereas a module only provides a <em>single piece</em> of functionality. Which means that, if you have a system with both modules and libraries, a library will typically contain multiple modules. For example, you might have a collections library which contains a <code>List</code> module, a <code>Set</code> module and a <code>Map</code> module.</p>
<p>While you can certainly write modules without a module system, ideally you want your modules to be separately compilable (for languages and execution environments where that notion even makes sense), separately deployable, and you want module composition to be safe (i.e. composing modules should either work or trigger an error before runtime, but never lead to an runtime error or unexpected behavior). For this, you need a module system, like Racket's units, Standard ML's modules and functors or Newspeak's top-level classes.</p>
<p>So, let's recap:</p>
<ul>
<li><strong>library</strong>: collection of related functionality</li>
<li><strong>framework</strong>: Inversion of Control</li>
<li><strong>module</strong>: abstract interface with explicit exports and imports, implementation and interface are separate, there may be multiple implementations and the implementation is hidden</li>
</ul> |
14,628,927 | Writing a highly scalable TCP/IP server in C# 5 with the async/await pattern? | <p>I'm tasked with designing a fairly simple TCP/IP server that must accept connections from multiple clients. It needs to be written in C#, and I'm using .NET 4.5. That said, I'm not sure what is the current "state of the art" for TCP/IP server/client scalability in .NET 4.5.</p>
<p>I did see this post: <a href="https://stackoverflow.com/questions/869744/how-to-write-a-scalable-tcp-ip-based-server">How to write a scalable Tcp/Ip based server</a>. But that relates to .NET 2.0 and 3.5 and makes no mention of the async/await pattern.</p>
<p>I am capable of writing a server the "old way"... but I want to know what the "new way" is.</p>
<ul>
<li>What is the best way to use the new Async methods on Socket, TcpClient or TcpListener to create a scalable server in C#?</li>
<li>Do the new Async methods leverage I/O Completion Ports?</li>
<li>Is rolling your own Socket listener more efficient, or are the TcpListener/TcpClient classes pretty good now?</li>
</ul>
<p>EDIT: Additional questions.</p> | 14,629,612 | 1 | 12 | null | 2013-01-31 15:09:59.323 UTC | 16 | 2020-04-06 03:05:10.873 UTC | 2017-05-23 12:09:52.997 UTC | null | -1 | null | 135,786 | null | 1 | 27 | c#|.net|sockets|async-await | 21,377 | <blockquote>
<p>What is the best way to use the new Async methods on Socket, TcpClient or TcpListener to create a scalable server in C#?</p>
</blockquote>
<p>There aren't any new <code>async</code> methods on <code>Socket</code>; the methods named <code>*Async</code> on <code>Socket</code> are a special set of APIs to reduce memory usage. <code>TcpClient</code> and <code>TcpListener</code> did get some new <code>async</code> methods.</p>
<p>If you want the best scalability, you're probably best using <a href="https://devblogs.microsoft.com/pfxteam/awaiting-socket-operations/" rel="nofollow noreferrer">Stephen Toub's custom awaiters for <code>Socket</code></a>. If you want the easiest to code, you're probably better off using <code>TcpClient</code> and <code>TcpListener</code>.</p>
<blockquote>
<p>Do the new Async methods leverage I/O Completion Ports?</p>
</blockquote>
<p>Yes, just like most of the other asynchronous APIs in the BCL. AFAIK, the <code>Stream</code> class is the only one that may possibly not use the IOCP; all other <code>*Begin</code>/<code>*End</code>/<code>*Async</code> methods use the IOCP.</p>
<blockquote>
<p>Is rolling your own Socket listener more efficient, or are the TcpListener/TcpClient classes pretty good now?</p>
</blockquote>
<p>The classes are pretty good as they are. Stephen Toub has a <a href="https://devblogs.microsoft.com/pfxteam/awaiting-socket-operations/" rel="nofollow noreferrer">blog post</a> that is a bit more efficient in terms of memory use.</p> |
14,628,576 | Passing an JSON array to MVC Web API via GET | <p>I know there are tons of answers for this topic, but couldn't find the solution to my issue.
I have an ASP.NET MVC Web API that looks like this:</p>
<pre><code> [HttpGet]
public IList<Country> GetCountryList(List<long> idList)
</code></pre>
<p>And I've tried calling it like this:</p>
<pre><code> $.ajax({
dataType: "json",
data: JSON.stringify({idList: listOfIds}),
type: "GET",
url: "api/v1/util/CountryList",
success: function (result) {
alert(result);
}
});
</code></pre>
<p>The URL then looks like this:</p>
<pre><code>https://localhost/supertext/api/v1/util/CountryList?{%22idList%22:[46,14,62,83,120]}
</code></pre>
<p>Alternative:</p>
<pre><code> $.ajax({
dataType: "json",
data: {
idList: JSON.stringify(listOfIds),
}
type: "GET",
url: "api/v1/util/CountryList",
success: function (result) {
alert(result);
}
});
</code></pre>
<p>URL:</p>
<pre><code>https://localhost/supertext/api/v1/util/CountryList?idList=%5B46%2C14%2C62%2C83%2C120%5D
</code></pre>
<p>Both methods don't work.</p>
<p>Do I really have to send and receive it as a string or use POST?</p> | 14,628,736 | 2 | 0 | null | 2013-01-31 14:51:28.09 UTC | 10 | 2018-04-27 12:26:59.447 UTC | null | null | null | null | 375,192 | null | 1 | 28 | jquery|asp.net-mvc|json|asp.net-web-api | 46,417 | <p>No, don't try to be sending JSON in a GET request. Use JSON with other verbs which have body, such as POST and PUT. </p>
<p>Do it the standard way, by decorating your action parameter with the <code>[FromUri]</code> attribute:</p>
<pre><code>public IList<Country> GetCountryList([FromUri] List<long> idList)
{
...
}
</code></pre>
<p>and then just trigger the AJAX request:</p>
<pre><code>$.ajax({
url: 'api/v1/util/CountryList',
type: 'GET',
data: { idList: [1, 2, 3] },
traditional: true,
success: function (result) {
console.log(JSON.stringify(result));
}
});
</code></pre>
<p>Further recommended reading for you about how the model binding in the Web API works:</p>
<p><a href="http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1" rel="noreferrer">http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1</a></p> |
14,359,926 | Send HTTP request from PHP without waiting for response? | <p>I want to have an HTTP GET request sent from PHP. Example:</p>
<pre><code>http://tracker.example.com?product_number=5230&price=123.52
</code></pre>
<p>The idea is to do server-side web-analytics: Instead of sending tracking
information from JavaScript to a server, the server sends tracking
information directly to another server.</p>
<p>Requirements:</p>
<ul>
<li><p>The request should take as little time as possible, in order to not
noticeably delay processing of the PHP page.</p></li>
<li><p>The response from the <code>tracker.example.com</code> does not need to be
checked. As examples, some possible responses from
<code>tracker.example.com</code>:</p>
<ul>
<li><p><em>200:</em> That's fine, but no need to check that.</p></li>
<li><p><em>404:</em> Bad luck, but - again - no need to check that.</p></li>
<li><p><em>301:</em> Although a redirect would be appropriate, it would delay
processing of the PHP page, so don't do that.</p></li>
</ul>
<p>In short: <em>All</em> responses can be discarded.</p></li>
</ul>
<p>Ideas for solutions:</p>
<ul>
<li><p>In a now deleted answer, someone suggested calling command line
<a href="http://en.wikipedia.org/wiki/CURL">curl</a> from PHP in a shell process. This seems like a good idea,
only that I don't know if forking a lot of shell processes under
heavy load is a wise thing to do.</p></li>
<li><p>I found <a href="http://code.google.com/p/php-ga/">php-ga</a>, a package for doing server-side Google
Analytics from PHP. On the project's page, it is
mentioned: <em>"Can be configured to [...] use non-blocking requests."</em>
So far I haven't found the time to investigate what method php-ga
uses internally, but this method could be it!</p></li>
</ul>
<p>In a nutshell: What is the best solution to do generic server-side
tracking/analytics from PHP.</p> | 14,668,762 | 10 | 14 | null | 2013-01-16 13:48:53.39 UTC | 15 | 2020-07-15 16:27:36.94 UTC | 2013-01-30 20:07:26.993 UTC | null | 282,729 | null | 282,729 | null | 1 | 49 | php|http|curl|server-side|web-analytics | 58,168 | <p>Unfortunately PHP by definition is <strong>blocking</strong>. While this holds true for the majority of functions and operations you will normally be handling, the current scenario is different.</p>
<p>The process which I like to call <a href="http://www.coretechnologies.com/products/http-ping/">HTTP-Ping</a>, requires that you only <em>touch</em> a specific URI, forcing the specific server to boot-strap it's internal logic. Some functions allow you to achieve something very similar to this <em>HTTP-ping</em>, by not waiting for a response.</p>
<p>Take note that the process of <em>pinging</em> an url, is a two step process:</p>
<ol>
<li>Resolve the DNS</li>
<li>Making the request</li>
</ol>
<p>While making the request should be rather fast once the DNS is resolved and the connection is made, there aren't many ways of making the DNS resolve faster.</p>
<p>Some ways of doing an http-ping are:</p>
<ol>
<li><a href="http://www.php.net/manual/en/ref.curl.php">cURL</a>, by setting CONNECTION_TIMEOUT to a low value</li>
<li><a href="http://php.net/manual/en/function.fsockopen.php">fsockopen</a> by closing immediately after writing</li>
<li><a href="http://php.net/manual/en/function.stream-socket-client.php">stream_socket_client</a> (same as fsockopen) and also adding <code>STREAM_CLIENT_ASYNC_CONNECT</code></li>
</ol>
<p>While both <code>cURL</code> and <code>fsockopen</code> are both blocking while the DNS is being resolved. I have noticed that <em>fsockopen</em> is significantly faster, even in worst case scenarios.</p>
<p><code>stream_socket_client</code> on the other hand should fix the problem regarding DNS resolving and should be the optimal solution in this scenario, but I have not managed to get it to work.</p>
<p>One final solution is to start another thread/process that does this for you. Making a system call for this should work, but also <a href="http://php.net/manual/en/function.pcntl-fork.php">forking</a> the current process should do that also. Unfortunately both are not really safe in applications where you can't control the environment on which PHP is running.</p>
<p>System calls are more often than not blocked and pcntl is not enabled by default.</p> |
23,070,822 | Angular $scope.$apply vs $timeout as a safe $apply | <p>I'm trying to better understand the nuances of using the $timeout service in Angular as a sort of "safe $apply" method. Basically in scenarios where a piece of code could run in response to either an Angular event or a non-angular event such as jQuery or some standard DOM event.</p>
<p>As I understand things:</p>
<ol>
<li>Wrapping code in $scope.$apply works fine for scenarios where you
aren't already in a digest loop (aka. jQuery event) but will raise an error if a digest is in progress</li>
<li>Wrapping code in a $timeout() call with no delay parameter works whether already in a digest cycle or not</li>
</ol>
<p>Looking at Angular source code, it looks like $timeout makes a call to $rootScope.$apply().</p>
<ol>
<li>Why doesn't $timeout() also raise an error if a digest cycle is already in progress?</li>
<li>Is the best practice to use $scope.$apply() when you know for sure that a digest won't already be in progress and $timeout() when needing it to be safe either way?</li>
<li>Is $timeout() really an acceptable "safe apply", or are there gotchas?</li>
</ol>
<p>Thanks for any insight.</p> | 23,073,968 | 3 | 0 | null | 2014-04-14 21:30:53.537 UTC | 22 | 2015-07-27 10:44:53.207 UTC | null | null | null | null | 20,489 | null | 1 | 70 | angularjs|scope | 30,826 | <blockquote>
<p>Looking at Angular source code, it looks like $timeout makes a call to
$rootScope.$apply().</p>
<ul>
<li>Why doesn't $timeout() also raise an error if a digest cycle is already in progress?</li>
</ul>
</blockquote>
<p><code>$timeout</code> makes use of an undocumented Angular service <code>$browser</code>. Specifically it uses <code>$browser.defer()</code> that defers execution of your function asynchronously via <code>window.setTimeout(fn, delay)</code>, which will always run outside of Angular life-cycle. Only once <code>window.setTimeout</code> has fired your function will <code>$timeout</code> call <code>$rootScope.$apply()</code>.</p>
<blockquote>
<ul>
<li>Is the best practice to use $scope.$apply() when you know for sure that a digest won't already be in progress and $timeout() when needing it to be safe either way?</li>
</ul>
</blockquote>
<p>I would say so. Another use case is that sometimes you need to access a $scope variable that you know will only be initialized after digest. Simple example would be if you want to set a form's state to dirty inside your controller constructor (for whatever reason). Without $timeout the <code>FormController</code> has not been initialized and published onto $scope, so wrapping <code>$scope.yourform.setDirty()</code> inside $timeout ensures that <code>FormController</code> has been initialized. Sure you can do all this with a directive without $timeout, just giving another use case example.</p>
<blockquote>
<ul>
<li>Is $timeout() really an acceptable "safe apply", or are there gotchas?</li>
</ul>
</blockquote>
<p>It should always be safe, but your go to method should always aim for $apply() in my opinion. The current Angular app I'm working on is fairly large and we've only had to rely on $timeout once instead of $apply().</p> |
47,174,686 | pyspark Window.partitionBy vs groupBy | <p>Lets say I have a dataset with around 2.1 billion records.</p>
<p>It's a dataset with customer information and I want to know how many times they did something. So I should group on the ID and sum one column (It has 0 and 1 values where the 1 indicates an action). </p>
<p>Now, I can use a simple <code>groupBy</code> and <code>agg(sum)</code> it, but to my understanding this is not really efficient. The <code>groupBy</code> will move around a lot of data between partitions.</p>
<p>Alternatively, I can also use a Window function with a <code>partitionBy</code> clause and then sum the data. One of the disadvantage is that I'll then have to apply an extra filter cause it keeps all the data. And I want one record per ID.</p>
<p>But I don't see how this Window handles the data. Is it better than this groupBy and sum. Or is it the same?</p> | 47,177,002 | 1 | 0 | null | 2017-11-08 08:20:18.68 UTC | 8 | 2017-11-08 10:17:37.383 UTC | 2017-11-08 08:38:08.287 UTC | null | 7,224,597 | null | 3,170,699 | null | 1 | 13 | python|apache-spark|pyspark|apache-spark-sql | 9,339 | <p>As far as I know, when working with spark DataFrames, the <code>groupBy</code> operation is optimized via <a href="https://databricks.com/blog/2015/04/13/deep-dive-into-spark-sqls-catalyst-optimizer.html" rel="noreferrer">Catalyst</a>. The <code>groupBy</code> on DataFrames is unlike the <code>groupBy</code> on RDDs. </p>
<p>For instance, the <code>groupBy</code> on DataFrames performs the aggregation on partitions first, and then shuffles the aggregated results for the final aggregation stage. Hence, only the reduced, aggregated results get shuffled, not the entire data. This is similar to <code>reduceByKey</code> or <code>aggregateByKey</code> on RDDs. See this related <a href="https://stackoverflow.com/questions/32902982/dataframe-groupby-behaviour-optimization">SO-article</a> with a nice example.</p>
<p>In addition, see slide 5 in this <a href="https://de.slideshare.net/databricks/a-deep-dive-into-spark-sqls-catalyst-optimizer-with-yin-huai" rel="noreferrer">presentation</a> by Yin Huai which covers the benefits of using DataFrames in conjunction with Catalyst.</p>
<p>Concluding, I think you're fine employing <code>groupBy</code> when using spark DataFrames. Using <code>Window</code> does not seem appropriate to me for your requirement.</p> |
42,902,130 | Azure Keyvault - "Operation "list" is not allowed by vault policy" but all permissions are checked | <p>I am accessing KeyVault with .NET client with an AAD application. Although all permissions under secrets are enabled for this AAD app (screenshot below) I am getting "The operation "List" is not enabled in this key vault's access policy" if I navigate to the Secret panel.</p>
<p>I would like to be able to set the permissions via the AAD application and so using Powershell wouldn't be an option.</p>
<p>If I set the permissions via Powershell - it does work.</p>
<p>How I'm creating my access policies:</p>
<pre><code> var accessPolicy = new AccessPolicyEntry
{
ApplicationId = app,
ObjectId = Obid,
PermissionsRawJsonString = "{ \"keys\": [ \"all\" ], \"secrets\": [ \"all\" ], \"certificates\": [ \"all\" ] }",
TenantId = ten,
};
return accessPolicy;
</code></pre>
<p>which gives me
<a href="https://i.stack.imgur.com/F9nsU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F9nsU.png" alt="enter image description here"></a></p>
<p>Then the list error appears and so I have to use</p>
<pre><code>Set-AzureRmKeyVaultAccessPolicy -VaultName vaultname -ResourceGroupName location -ObjectId obid -PermissionsToKeys all -PermissionsToSecrets all
</code></pre>
<p>That will get rid of the error but I would much prefer a solution so I can work with the .NET SDK to resolve. </p> | 42,948,221 | 3 | 0 | null | 2017-03-20 11:13:16.363 UTC | null | 2020-07-15 13:49:41.373 UTC | null | null | null | null | 4,352,619 | null | 1 | 26 | c#|.net|powershell|azure|azure-keyvault | 44,228 | <p>After ages of trying to sort this issue - the problem was in the access policies code. When a user is registered in the code - it associates itself with the app ID. The app ID is the problem as it thinks that the user is an application AND a user. </p>
<p>The tell-tale sign of this is if you go into the portal, then "Access Policy" on a Keyvault and it'll say Application + User underneath. If you try and add a user (that is already on the list) - it will add the second user - so you'll have 2 of the same.</p>
<p>So all that's needed is to:</p>
<pre><code> var accessPolicy = new AccessPolicyEntry
{
ApplicationId = app, // Delete this line
ObjectId = Obid,
PermissionsRawJsonString = "{ \"keys\": [ \"all\" ], \"secrets\": [ \"all\" ], \"certificates\": [ \"all\" ] }",
TenantId = ten,
};
return accessPolicy;
</code></pre>
<p>The Microsoft documentation can be vague at times and I believe this is one of them.</p> |
56,336,234 | Build Fail Sphinx Error contents.rst not found | <p>I follow the instructions on read the docs but I get this error:</p>
<blockquote>
<p>bash Sphinx error: master file
/home/docs/checkouts/readthedocs.org/user_builds/mybinders/checkouts/latest/docs/source/contents.rst
not found</p>
</blockquote>
<p>Do have to you the read the docs yaml file?</p> | 56,448,499 | 2 | 0 | null | 2019-05-28 06:32:56.457 UTC | 7 | 2020-10-07 07:55:59.753 UTC | 2019-05-28 10:45:46.423 UTC | null | 6,592,881 | null | 8,535,721 | null | 1 | 51 | read-the-docs | 9,649 | <p>If you have your own <code>conf.py</code> file, it overrides Read the Doc's default <code>conf.py</code>. By default, Sphinx expects the master doc to be <code>contents</code>. Read the Docs will set master doc to <code>index</code> instead (or whatever it is you have specified in your settings). Try adding this to your <code>conf.py</code>:</p>
<pre><code>master_doc = 'index'
</code></pre>
<p>For more information, check out this issue: <a href="https://github.com/rtfd/readthedocs.org/issues/2569" rel="noreferrer">https://github.com/rtfd/readthedocs.org/issues/2569</a></p> |
41,723,018 | JetBrains Rider EAP on Linux - Solution load failed: MsBuild not found | <p>Just installed the latest version of Rider EAP (163.12057) and tried to create a new solution.</p>
<p>In my Solution Explorer its shows my Solution and <em>(load failed)</em>.
In the Event Log window I get the error message: </p>
<blockquote>
<p>Solution 'FirstSolution' load failed: MsBuild not found on this machine</p>
</blockquote>
<p>Any ideas on how I can solve this loading problem?
Thanks in advance!</p> | 41,724,349 | 3 | 1 | null | 2017-01-18 15:17:20.373 UTC | 2 | 2022-02-19 06:55:31.667 UTC | 2017-01-18 19:07:25.92 UTC | null | 783,119 | null | 4,520,219 | null | 1 | 28 | msbuild|jetbrains-ide|rider|failed-to-load-viewstate | 14,662 | <p>I managed to solve the loading error.</p>
<p>I was missing Mono and found out through this thread <a href="https://rider-support.jetbrains.com/hc/en-us/community/posts/207243685-Unity3D-support?page=2#comments" rel="noreferrer">here</a> that Rider currently needs Mono 4.6.2.</p>
<p>I followed <a href="http://www.mono-project.com/docs/getting-started/install/linux/#usage" rel="noreferrer">this</a> guide to install Mono.</p>
<pre><code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
sudo apt-get install mono-devel
sudo apt-get install mono-complete
</code></pre>
<p>I hope this will help someone else.</p>
<p>UPDATE: Asp.Net Core</p>
<p>if you'll be using Asp.Net Core, and encounter error about missing <code>xsp.exe</code> you might need to install <code>mono-xsp4</code> with this command</p>
<p><code>sudo apt-get install mono-xsp4</code></p> |
3,099,234 | jstl foreach omit an element in last record | <p>trying to use this jstl to formulate a json string, how can i make the segment not to put a comma in the end of the last record? note the comma in the end</p>
<pre><code><c:forEach items="${fileList}" var="current">
{ id:1001,data:["<c:out value="${current.fileName}" />" , "<c:out value="${current.path}" />" , "<c:out value="${current.size}" />" , "<c:out value="${current.type}" />"] },
</c:forEach>
</code></pre> | 3,101,346 | 3 | 1 | null | 2010-06-23 05:56:14.787 UTC | 13 | 2013-09-19 19:19:23.203 UTC | 2013-09-19 19:18:17.31 UTC | null | 4,311 | null | 355,974 | null | 1 | 68 | jsp|jstl | 68,191 | <p>Just use <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html#isLast()" rel="noreferrer"><code>LoopTagStatus#isLast()</code></a>.</p>
<pre><code><c:forEach items="${fileList}" var="current" varStatus="loop">
{ id: 1001,
data: [
"<c:out value="${current.fileName}" />",
"<c:out value="${current.path}" />",
"<c:out value="${current.size}" />",
"<c:out value="${current.type}" />"
]
}<c:if test="${!loop.last}">,</c:if>
</c:forEach>
</code></pre>
<p>You can also use the conditional operator in EL instead of <code><c:if></code>:</p>
<pre><code> ${!loop.last ? ',' : ''}
</code></pre> |
3,028,899 | What is the difference between remote procedure call and web service? | <p>Is there any clear definition of RPC and Web Service? A quick wikipedia search shows:</p>
<blockquote>
<p>RPC: Remote procedure call (RPC) is an
Inter-process communication technology
that allows a computer program to
cause a subroutine or procedure to
execute in another address space
(commonly on another computer on a
shared network) without the programmer
explicitly coding the details for this
remote interaction. </p>
<p>Web Service: Web services are
typically application programming
interfaces (API) or web APIs that are
accessed via Hypertext Transfer
Protocol and executed on a remote
system hosting the requested services.
Web services tend to fall into one of
two camps: Big Web Services[1] and
RESTful Web Services.</p>
</blockquote>
<p>I am not quite clear what the real difference between the two things. It seems that one thing could belong to RPC and is kind of web service at the same time.</p>
<p>Is Web Service a higher level representation of RPC? </p> | 3,028,917 | 4 | 0 | 2010-06-12 13:57:08.527 UTC | 2010-06-12 13:54:01.417 UTC | 22 | 2020-04-23 06:26:38.603 UTC | 2020-02-14 18:51:41.98 UTC | null | 2,094,956 | null | 166,482 | null | 1 | 86 | web-services|rpc | 54,691 | <blockquote>
<p>Is Web Service a higher level
representation of RPC?</p>
</blockquote>
<p>Yes, it is. A web service is a specific implementation of RPC. At its lowest level, Web Service connects to the Socket, using the HTTP protocol, to negotiate sending a payload that is executed in a remote space (remote space can be the same computer). All these remote call abstractions, at its core, are RPCs.</p> |
3,078,081 | Setting global styles for Views in Android | <p>Let's say I want all the <code>TextView</code> instances in my app to have <code>textColor="#ffffff"</code>. Is there a way to set that in one place instead of setting it for each <code>TextView</code>?</p> | 3,166,865 | 4 | 2 | null | 2010-06-20 03:07:55.35 UTC | 48 | 2019-05-12 08:05:49.713 UTC | 2016-04-12 20:16:10.86 UTC | null | 1,176,870 | null | 200,145 | null | 1 | 139 | android | 100,194 | <p>Actually, you can set a default style for TextViews (and most other built-in widgets) without needing to do a custom java class or setting the style individually.</p>
<p>If you take a look in <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml" rel="noreferrer"><code>themes.xml</code></a> in the Android source, you will see a bunch of attributes for the default style for various widgets. The key is the <code>textViewStyle</code> (or <code>editTextStyle</code>, etc.) attribute which you override in your custom theme. You can override these in the following way:</p>
<p>Create a <code>styles.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="android:Theme">
<item name="android:textViewStyle">@style/MyTextViewStyle</item>
</style>
<style name="MyTextViewStyle" parent="android:Widget.TextView">
<item name="android:textColor">#F00</item>
<item name="android:textStyle">bold</item>
</style>
</resources>
</code></pre>
<p>Then just apply that theme to your application in <code>AndroidManifest.xml</code>:</p>
<pre><code><application […] android:theme="@style/MyTheme">…
</code></pre>
<p>And all your text views will default to the style defined in <code>MyTextViewStyle</code> (in this instance, bold and red)!</p>
<p>This was tested on devices from API level 4 onward and seems to work great.</p> |
38,722,202 | How do I change the number of decimal places on axis labels in ggplot2? | <p>Specifically, this is in a facet_grid. Have googled extensively for similar questions but not clear on the syntax or where it goes. What I want is for every number on the y-axes to have two digits after the decimal, even if the trailing one is 0. Is this a parameter in scale_y_continuous or element_text or...?</p>
<pre><code>row1 <- ggplot(sector_data[sector_data$sector %in% pages[[x]],], aes(date,price)) + geom_line() +
geom_hline(yintercept=0,size=0.3,color="gray50") +
facet_grid( ~ sector) +
scale_x_date( breaks='1 year', minor_breaks = '1 month') +
scale_y_continuous( labels = ???) +
theme(panel.grid.major.x = element_line(size=1.5),
axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_text(size=8),
axis.ticks=element_blank()
)
</code></pre> | 38,722,547 | 4 | 0 | null | 2016-08-02 13:43:40.673 UTC | 25 | 2022-03-24 14:13:10.267 UTC | null | null | null | null | 1,586,901 | null | 1 | 75 | r|ggplot2 | 97,883 | <p>From the help for <code>?scale_y_continuous</code>, the argument 'labels' can be a function:</p>
<blockquote>
<p>labels One of:</p>
<ul>
<li><p>NULL for no labels</p></li>
<li><p>waiver() for the default labels computed by the transformation object</p></li>
<li><p>A character vector giving labels (must be same length as breaks)</p></li>
<li><p>A function that takes the breaks as input and returns labels as output</p></li>
</ul>
</blockquote>
<p>We will use the last option, a function that takes <code>breaks</code> as an argument and returns a number with 2 decimal places.</p>
<pre><code>#Our transformation function
scaleFUN <- function(x) sprintf("%.2f", x)
#Plot
library(ggplot2)
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p + scale_y_continuous(labels=scaleFUN)
</code></pre>
<p><a href="https://i.stack.imgur.com/1205q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1205q.png" alt="enter image description here"></a></p> |
40,554,106 | Read excel sheet with multiple header using Pandas | <p>I have an excel sheet with multiple header like:</p>
<pre><code>_________________________________________________________________________
____|_____| Header1 | Header2 | Header3 |
ColX|ColY |ColA|ColB|ColC|ColD||ColD|ColE|ColF|ColG||ColH|ColI|ColJ|ColDK|
1 | ds | 5 | 6 |9 |10 | .......................................
2 | dh | ..........................................................
3 | ge | ..........................................................
4 | ew | ..........................................................
5 | er | ..........................................................
</code></pre>
<p>Now here you can see that first two columns do not have headers they are blank but other columns have headers like Header1, Header2 and Header3. So I want to read this sheet and merge it with other sheet with similar structure.</p>
<p>I want to merge it on first column 'ColX'. Right now I am doing this:</p>
<pre><code>import pandas as pd
totalMergedSheet = pd.DataFrame([1,2,3,4,5], columns=['ColX'])
file = pd.ExcelFile('ExcelFile.xlsx')
for i in range (1, len(file.sheet_names)):
df1 = file.parse(file.sheet_names[i-1])
df2 = file.parse(file.sheet_names[i])
newMergedSheet = pd.merge(df1, df2, on='ColX')
totalMergedSheet = pd.merge(totalMergedSheet, newMergedSheet, on='ColX')
</code></pre>
<p>But I don't know its neither reading columns correctly and I think will not return the results in the way I want. So, I want the resulting frame should be like:</p>
<pre><code>________________________________________________________________________________________________________
____|_____| Header1 | Header2 | Header3 | Header4 | Header5 |
ColX|ColY |ColA|ColB|ColC|ColD||ColD|ColE|ColF|ColG||ColH|ColI|ColJ|ColK| ColL|ColM|ColN|ColO||ColP|ColQ|ColR|ColS|
1 | ds | 5 | 6 |9 |10 | ..................................................................................
2 | dh | ...................................................................................
3 | ge | ....................................................................................
4 | ew | ...................................................................................
5 | er | ......................................................................................
</code></pre>
<p>Any suggestions please. Thanks.</p> | 40,555,989 | 1 | 0 | null | 2016-11-11 18:33:34.12 UTC | 15 | 2021-05-28 07:54:40.17 UTC | null | null | null | null | 5,453,723 | null | 1 | 38 | python|excel|pandas|dataframe | 69,555 | <p>[See comments for updates and corrections]</p>
<p>Pandas already has a function that will read in an entire Excel spreadsheet for you, so you don't need to manually parse/merge each sheet. Take a look <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="noreferrer">pandas.read_excel()</a>. It not only lets you read in an Excel file in a single line, it also provides options to help solve the problem you're having.</p>
<p>Since you have subcolumns, what you're looking for is <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="noreferrer">MultiIndexing</a>. By default, pandas will read in the top row as the sole header row. You can pass a <code>header</code> argument into <code>pandas.read_excel()</code> that indicates how many rows are to be used as headers. In your particular case, you'd want <code>header=[0, 1]</code>, indicating the first two rows. You might also have multiple sheets, so you can pass <code>sheetname=None</code> as well (this tells it to go through all sheets). The command would be:</p>
<pre><code>df_dict = pandas.read_excel('ExcelFile.xlsx', header=[0, 1], sheetname=None)
</code></pre>
<p>This returns a dictionary where the keys are the sheet names, and the values are the DataFrames for each sheet. If you want to collapse it all into one DataFrame, you can simply use pandas.concat:</p>
<pre><code>df = pandas.concat(df_dict.values(), axis=0)
</code></pre> |
40,360,936 | graphql-go : Use an Object as Input Argument to a Query | <p>I'm attempting to pass an object as an argument to a query (rather than a scalar). From the docs it seems that this should be possible, but I can't figure out how to make it work.</p>
<p>I'm using graphql-go, here is the test schema:</p>
<pre><code>var fileDocumentType = graphql.NewObject(graphql.ObjectConfig{
Name: "FileDocument",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
if fileDoc, ok := p.Source.(data_format.FileDocument); ok {
return fileDoc.Id, nil
}
return "", nil
},
},
"tags": &graphql.Field{
Type: graphql.NewList(tagsDataType),
Args: graphql.FieldConfigArgument{
"tags": &graphql.ArgumentConfig{
Type: tagsInputType,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Println(p.Source)
fmt.Println(p.Args)
if fileDoc, ok := p.Source.(data_format.FileDocument); ok {
return fileDoc.Tags, nil
}
return nil, nil
},
},
},
})
</code></pre>
<p>And the inputtype I'm attempting to use (I've tried both an InputObject and a standard Object)</p>
<pre><code>var tagsInputType = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "tagsInput",
Fields: graphql.Fields{
"keyt": &graphql.Field{
Type: graphql.String,
},
"valuet": &graphql.Field{
Type: graphql.String,
},
},
})
</code></pre>
<p>And here is the graphql query I'm using to test:</p>
<pre><code>{
list(location:"blah",rule:"blah")
{
id,tags(tags:{keyt:"test",valuet:"test"})
{
key,
value
},
{
datacentre,
handlerData
{
key,
value
}
}
}
}
</code></pre>
<p>I'm getting the following error:</p>
<pre><code>wrong result, unexpected errors: [Argument "tags" has invalid value {keyt: "test", valuet: "test"}.
In field "keyt": Unknown field.
In field "valuet": Unknown field.]
</code></pre>
<p>The thing is, when I change the type to a string, it works fine. How do I use an object as an input arg?</p>
<p>Thanks!</p> | 41,230,015 | 1 | 0 | null | 2016-11-01 13:21:11.153 UTC | 11 | 2016-12-19 19:51:55.54 UTC | 2016-12-19 18:57:55.893 UTC | null | 4,263,818 | null | 2,851,943 | null | 1 | 15 | go|graphql | 5,832 | <p>Had the same issue. Here is what I found from going through the graphql-go source. </p>
<p>The <code>Fields</code> of an <code>InputObject</code> have to be of type <code>InputObjectConfigFieldMap</code> or <code>InputObjectConfigFieldMapThunk</code> for the pkg to work.</p>
<p>So an <code>InputObject</code> would look like this :</p>
<pre><code>var inputType = graphql.NewInputObject(
graphql.InputObjectConfig{
Name: "MyInputType",
Fields: graphql.InputObjectConfigFieldMap{
"key": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
},
},
)
</code></pre>
<hr>
<p>Modified the Hello World example to take an <code>Input Object</code> :</p>
<pre><code>package main
import (
"encoding/json"
"fmt"
"log"
"github.com/graphql-go/graphql"
)
func main() {
// Schema
var inputType = graphql.NewInputObject(
graphql.InputObjectConfig{
Name: "MyInputType",
Fields: graphql.InputObjectConfigFieldMap{
"key": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
},
},
)
args := graphql.FieldConfigArgument{
"foo": &graphql.ArgumentConfig{
Type: inputType,
},
}
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Args: args,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Println(p.Args)
return "world", nil
},
},
}
rootQuery := graphql.ObjectConfig{
Name: "RootQuery",
Fields: fields,
}
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
log.Fatalf("failed to create new schema, error: %v", err)
}
// Query
query := `
{
hello(foo:{key:"blah"})
}
`
params := graphql.Params{Schema: schema, RequestString: query}
r := graphql.Do(params)
if len(r.Errors) > 0 {
log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
}
rJSON, _ := json.Marshal(r)
fmt.Printf("%s \n", rJSON) // {“data”:{“hello”:”world”}}
}
</code></pre> |
38,731,271 | Clear an input field with Reactjs? | <p>I am using a variable below. </p>
<pre><code>var newInput = {
title: this.inputTitle.value,
entry: this.inputEntry.value
};
</code></pre>
<p>This is used by my input fields.</p>
<pre><code><input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
<textarea id="inputage" ref={el => this.inputEntry = el} className="form-control" />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
</code></pre>
<p>Once I activate <code>{this.sendthru}</code> I want to clear my input fields. However, I am uncertain how to do so. </p>
<p>Also, as shown in this example, it was pointed out to me that I should use the <code>ref</code> property for input values. What I am unclear of is what exactly does it mean to have <code>{el => this.inputEntry = el}</code>. What is the significance of <code>el</code> in this situation? </p> | 60,087,701 | 11 | 0 | null | 2016-08-02 22:09:24.943 UTC | 18 | 2022-06-27 18:16:06.833 UTC | 2019-06-17 09:46:40.373 UTC | null | 9,395,140 | null | 2,934,664 | null | 1 | 63 | javascript|reactjs | 249,308 | <p>You can use input type="reset" </p>
<pre><code><form action="/action_page.php">
text: <input type="text" name="email" /><br />
<input type="reset" defaultValue="Reset" />
</form>
</code></pre> |
27,632,217 | Warning: Assignment from Incompatible Pointer Type [enabled by default] while assigning Function Address to Function Pointer | <p>I am trying to implement a simple swap function using function pointer but when I assign the function's address to a function pointer:</p>
<p>`pointersTofunctionB.c:14:6:warning: assignment from incompatible pointer type [enabled by default]. </p>
<p>This is my code: </p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
void intSwap(int *a,int *b);
void charSwap(char *a,char *b);
void (*swap)(void*,void*);
int main(int argc, char const *argv[])
{
int a=20,b=15;
char c='j',d='H';
swap=&intSwap;// warning here
swap(&a,&b);
printf("%d %d\n",a,b);
swap=&charSwap;// warning here also
swap(&c,&d);
printf("%c %c\n",c,d );
return 0;
}
void intSwap(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
void charSwap(char *a,char *b)
{
char temp;
temp=*a;
*a=*b;
*b=temp;
}
</code></pre>
<p>How can I solve this warning?</p> | 27,632,640 | 4 | 0 | null | 2014-12-24 05:58:58.567 UTC | null | 2020-03-24 13:12:29.337 UTC | 2020-03-24 13:12:29.337 UTC | null | 3,118,401 | null | 2,833,303 | null | 1 | 6 | c|function|pointers|function-pointers | 52,244 | <p>The warnings appear due to the following quote from the C Standard</p>
<p>6.3.2.3 Pointers</p>
<blockquote>
<p>8 A pointer to a function of one type may be converted to a pointer to
a function of another type and back again; the result shall compare
equal to the original pointer. <strong>If a converted pointer is used to
call a function whose type is not compatible with the referenced type,
the behavior is undefined.</strong></p>
</blockquote>
<p>That two functions would be compatible their parameters shall have compatible types</p>
<p>6.7.6.3 Function declarators (including prototypes)</p>
<blockquote>
<p>15 For two function types to be compatible, both shall specify
compatible return types.146) Moreover, the parameter type lists, if
both are present, shall agree in the number of parameters and in use
of the ellipsis terminator; <strong>corresponding parameters shall have
compatible types.</strong></p>
</blockquote>
<p>In your functions parameters are declared as pointers. So that they (pointers) would be compatible they shall be pointers to compatible types</p>
<p>6.7.6.1 Pointer declarators</p>
<p>2 For two pointer types to be compatible, both shall be identically qualified and both <strong>shall be pointers to compatible types.</strong></p>
<p>However types int or char on the one hand and type void on the other hand are not compatible types.</p>
<p>You could define your functions the following way</p>
<pre><code>void intSwap( void *a, void *b )
{
int *x = a;
int *y = b;
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
}
void charSwap( void *a, void *b )
{
char *c1 = a;
char *c2 = b;
char temp = *c1;
*c1 = *c2;
*c2 = temp;
}
</code></pre> |
54,232,530 | Merge values in map kotlin | <p>I need merge maps <code>mapA</code> and<code>mapB</code> with pairs of "name" - "phone number" into the final map, sticking together the values for duplicate keys, separated by commas. Duplicate values should be added only once.
I need the most idiomatic and correct in terms of language approach.</p>
<p>For example:</p>
<pre><code>val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
val mapB = mapOf("Emergency" to "911", "Police" to "102")
</code></pre>
<p>The final result should look like this:</p>
<pre><code>{"Emergency" to "112, 911", "Fire department" to "101", "Police" to "102"}
</code></pre>
<p>This is my function:</p>
<pre><code>fun mergePhoneBooks(mapA: Map<String, String>, mapB: Map<String, String>): Map<String, String> {
val unionList: MutableMap <String, String> = mapA.toMutableMap()
unionList.forEach { (key, value) -> TODO() } // here's I can't come on with a beatiful solution
return unionList
}
</code></pre> | 54,232,917 | 13 | 0 | null | 2019-01-17 09:16:52.543 UTC | 7 | 2022-08-15 15:09:29.157 UTC | null | null | null | null | 10,907,345 | null | 1 | 25 | java|kotlin | 38,856 | <p>How about:</p>
<pre><code>val unionList = (mapA.asSequence() + mapB.asSequence())
.distinct()
.groupBy({ it.key }, { it.value })
.mapValues { (_, values) -> values.joinToString(",") }
</code></pre>
<p>Result:</p>
<pre><code>{Emergency=112,911, Fire department=101, Police=102}
</code></pre>
<p>This will:</p>
<ul>
<li>produce a lazy <code>Sequence</code> of both maps' key-value pairs</li>
<li>group them by key (result: <code>Map<String, List<String></code>)</li>
<li>map their values to comma-joined strings (result: <code>Map<String, String></code>)</li>
</ul> |
29,949,757 | Creating Pandas Dataframe between two Numpy arrays, then draw scatter plot | <p>I'm relatively new with numpy and pandas (I'm an experimental physicist so I've been using ROOT for years...).
A common plot in ROOT is a 2D scatter plot where, given a list of x- and y- values, makes a "heatmap" type scatter plot of one variable versus the other.</p>
<p>How is this best accomplished with numpy and Pandas? I'm trying to use the <code>Dataframe.plot()</code> function, but I'm struggling to even create the Dataframe.</p>
<pre><code>import numpy as np
import pandas as pd
x = np.random.randn(1,5)
y = np.sin(x)
df = pd.DataFrame(d)
</code></pre>
<p>First off, this dataframe has shape (1,2), but I would like it to have shape (5,2).
If I can get the dataframe the right shape, I'm sure I can figure out the <code>DataFrame.plot()</code> function to draw what I want.</p> | 29,951,109 | 3 | 0 | null | 2015-04-29 16:43:29.47 UTC | 10 | 2017-07-25 14:15:19.277 UTC | 2015-04-29 18:50:16.98 UTC | null | 4,230,591 | null | 3,886,071 | null | 1 | 48 | python|numpy|pandas|scatter | 127,559 | <p>There are a number of ways to create DataFrames. Given 1-dimensional column vectors, you can create a DataFrame by passing it a dict whose keys are column names and whose values are the 1-dimensional column vectors:</p>
<pre><code>import numpy as np
import pandas as pd
x = np.random.randn(5)
y = np.sin(x)
df = pd.DataFrame({'x':x, 'y':y})
df.plot('x', 'y', kind='scatter')
</code></pre> |
34,599,888 | Google Cloud Platform: How do I rename a Google Cloud Platform project? | <p>Is it possible to rename a Google Cloud Platform project? If so, how?</p>
<p>I don't need to change the project ID or number. But I do want to change the project <em>name</em> (the name used by/for humans to identify a cloud platform project).</p>
<p>Thanks for any tips!</p> | 34,601,514 | 6 | 0 | null | 2016-01-04 21:09:56 UTC | 9 | 2022-02-26 20:59:16.457 UTC | 2020-09-01 14:28:13.35 UTC | null | 10,907,864 | null | 123,471 | null | 1 | 102 | google-cloud-platform | 35,608 | <ol>
<li>Use the hamburger menu in the top left to switch to the "IAM & Admin" section</li>
<li>Click Settings</li>
<li>Type the new name</li>
<li>Press Save</li>
<li>Reload the page</li>
</ol>
<p>For those wondering how to change the project ID, <a href="https://support.google.com/googleapi/answer/7014113?hl=en" rel="nofollow noreferrer">the official documentation says</a>:</p>
<blockquote>
<p>A project ID cannot be changed after the project is created, so if you are creating a new project, be sure to choose an ID that you'll be comfortable using for the lifetime of the project.</p>
</blockquote> |
45,981,964 | How to get a random element from a list with stream api? | <p>What is the most effective way to get a random element from a list with Java8 stream api?</p>
<pre><code>Arrays.asList(new Obj1(), new Obj2(), new Obj3());
</code></pre>
<p>Thanks.</p> | 45,982,130 | 9 | 0 | null | 2017-08-31 12:54:35.983 UTC | 4 | 2022-09-13 15:13:28.427 UTC | 2017-08-31 13:18:09.1 UTC | null | 7,294,647 | null | 1,348,364 | null | 1 | 28 | java|java-8 | 30,244 | <p>Why with streams? You just have to get a random number from 0 to the size of the list and then call <code>get</code> on this index:</p>
<pre><code>Random r = new Random();
ElementType e = list.get(r.nextInt(list.size()));
</code></pre>
<p>Stream will give you nothing interesting here, but you can try with:</p>
<pre><code>Random r = new Random();
ElementType e = list.stream().skip(r.nextInt(list.size())).findFirst().get();
</code></pre>
<p>Idea is to skip an arbitrary number of elements (but not the last one!), then get the first element if it exists. As a result you will have an <code>Optional<ElementType></code> which will be non empty and then extract its value with <code>get</code>. You have a lot of options here after having skip.</p>
<p>Using streams here is highly inefficient...</p>
<p>Note: that none of these solutions take in account empty lists, but the problem is defined on non-empty lists.</p> |
31,920,286 | Effectively debugging Shiny apps | <p>I have a complex Shiny app spread across multiple files that uses code from several packages. The app works when run locally in R Studio, but on my server it throws a generic error: </p>
<blockquote>
<p>Error: do not know how to convert 'x' to class "Date"</p>
</blockquote>
<p>This is probably a simple programming mistake, but figuring out exactly <em>where</em> that mistake is in the code is proving difficult. </p>
<p>How can I hunt down and fix the source of errors in Shiny apps? And what tools are available to do this in a systematic way? </p>
<hr>
<p>There has been some discussion of similar problems on <a href="https://groups.google.com/forum/#!topic/shiny-discuss/M4yy0pZMx_s" rel="noreferrer">Google Groups</a>. </p> | 31,945,359 | 4 | 0 | null | 2015-08-10 13:00:37.217 UTC | 24 | 2021-12-22 10:25:50.607 UTC | 2018-01-11 12:51:24.59 UTC | null | 1,256,041 | null | 1,256,041 | null | 1 | 44 | r|debugging|shiny | 19,201 | <p>You can achieve logging on the server using a combination of <code>logging</code> and <code>shinyjs</code>. </p>
<pre><code>install.packages("logging")
install.packages("shinyjs")
</code></pre>
<p>In your ui.R, bind <code>shinyjs</code> using <code>shinyjs::useShinyjs</code>: </p>
<pre><code>library(shinyjs)
shinyUI(
fluidPage(
useShinyjs(),
# etc...
</code></pre>
<p>In your server.R, add <code>logjs</code> to the list of log handlers: </p>
<pre><code>library(magrittr)
library(shinyjs)
library(logging)
basicConfig()
options(shiny.error = function() {
logging::logerror(sys.calls() %>% as.character %>% paste(collapse = ", ")) })
shinyServer(function(input, output, session) {
printLogJs <- function(x, ...) {
logjs(x)
T
}
addHandler(printLogJs)
# etc...
</code></pre>
<p>Then to print something, use <code>loginfo</code>. </p>
<p><strong>Other Tips</strong></p>
<ol>
<li><p>When running your app locally, such as from RStudio, use <code>options(shiny.error = browser)</code> or <code>options(shiny.error = recover)</code> to identify the source of errors. </p></li>
<li><p>Put as much business logic into packages and external scripts as possible. Unit-test these whenever you suspect they are causing issues. The <code>testthat</code> package can help here. </p></li>
<li><p>If you expect a variable to meet certain constraints, add an assertion. For example, if <code>x</code> should be a <code>zoo</code>, put <code>assert_that(is.zoo(x))</code> near the top of your reactive. </p></li>
<li><p>Beware of the default <code>drop</code> behaviour. Get into the habit of specifying <code>drop = F</code> whenever you want your result to be a <code>data.frame</code>. </p></li>
<li><p>Try to minimize the number of variables (options, environment, caching, UI state, etc.) that a unit of code depends on. Weakly typed languages are hard enough to debug already! </p></li>
<li><p>Use proper S4 and S3 classes instead of raw R structures where possible. </p></li>
<li><p><code>dput</code> will allow you to examine the internal structure of objects, and is very useful when trying to reproduce errors outside of an app. </p></li>
<li><p>Try to do your debugging in an interactive console, not using <code>print</code> inside an app. This will allow you to iterate more quickly. When debugging outside of an app is not possible, try putting a <code>browser()</code> call just before the problem code. </p></li>
<li><p><em>Never</em> use <code>sapply</code> in non-interactive code. With an empty output, it will be unable to infer the type that you want and return an empty <code>list</code>. If your result should be a <code>vector</code>, use <code>vapply</code>. If your result should be a <code>list</code>, use <code>lapply</code>. </p></li>
</ol>
<p>You should also look at <a href="https://shiny.rstudio.com/articles/debugging.html" rel="noreferrer">Debugging Shiny Applications</a> from the RStudio team. </p> |
2,888,621 | autofac's Func<T> to resolve named service | <p>Given registered services:</p>
<pre><code>builder.RegisterType<Foo1>().Named<IFoo>("one").As<IFoo>();
builder.RegisterType<Foo2>().Named<IFoo>("two").As<IFoo>();
builder.RegisterType<Foo3>().Named<IFoo>("three").As<IFoo>();
</code></pre>
<p>Can I retrieve named implementations of <code>IFoo</code> interface by injecting something like <code>Func<string, IFoo></code> ?</p>
<pre><code>public class SomeClass(Func<string, IFoo> foo) {
var f = foo("one");
Debug.Assert(f is Foo1);
var g = foo("two");
Debug.Assert(g is Foo2);
var h = foo("three");
Debug.Assert(h is Foo3);
}
</code></pre>
<p>I know I can do it with <code>Meta<></code>, but I don't want to use it.</p> | 2,888,939 | 1 | 0 | null | 2010-05-22 15:17:47.077 UTC | 9 | 2016-08-05 23:26:46.87 UTC | 2014-09-19 14:23:36.03 UTC | null | 542,190 | null | 71,965 | null | 1 | 15 | c#|.net|dependency-injection|ioc-container|autofac | 8,075 | <p>You could register your own resolving delegate like this:</p>
<pre><code>builder.Register<Func<string, IFoo>>(c =>
{
var cc = c.Resolve<IComponentContext>();
return named => cc.ResolveNamed<IFoo>(named);
});
</code></pre> |
2,931,953 | Getting rid of the gradient at the top of an Activity (Android) | <p>How can I get rid of the gradient at the top of my screen (the very top of the blue in the screenshot below... below the notification bar)?</p>
<p><a href="http://dl.dropbox.com/u/299320/device.png">simple screenshot http://dl.dropbox.com/u/299320/device.png</a></p> | 2,932,177 | 1 | 1 | null | 2010-05-28 19:36:49.053 UTC | 15 | 2011-08-13 20:12:26.863 UTC | 2010-05-28 20:01:33.83 UTC | null | 76,835 | null | 76,835 | null | 1 | 22 | android|user-interface | 7,008 | <p>This is themable; look at the <code>windowContentOverlay</code> attribute. In particular, you can create a new <a href="http://developer.android.com/guide/topics/ui/themes.html" rel="noreferrer">theme</a>:</p>
<pre><code><style name="Theme.Foo" parent="android:style/Theme.Light">
<item name="android:windowContentOverlay">@null</item>
</style>
</code></pre>
<p>And then declare that your activity should use this theme:</p>
<pre><code><activity android:name=".FooActivity"
android:theme="@style/Theme.Foo"> ...
</code></pre>
<p>Although a better option is to set this theme for all activities in the application, for consistency:</p>
<pre><code><application android:theme="@style/Theme.Foo"> ...
</code></pre> |
34,316,047 | Difference between 'image' and 'build' within docker compose | <p>Please help me understand the difference between 'image' and 'build' within docker compose</p> | 34,316,224 | 2 | 0 | null | 2015-12-16 15:35:54.707 UTC | 11 | 2019-08-15 03:34:45.743 UTC | null | null | null | null | 5,632,400 | null | 1 | 61 | docker|dockerfile|docker-compose|docker-registry | 19,778 | <ul>
<li><a href="https://docs.docker.com/compose/compose-file/#image" rel="noreferrer"><code>image</code></a> means <code>docker compose</code> will run a container based on that image</li>
<li><a href="https://docs.docker.com/compose/compose-file/#build" rel="noreferrer">build</a> means <code>docker compose</code> will first build an image based on the Dockerfile found in the path associated with build (and then run a container based on that image).</li>
</ul>
<p><a href="https://github.com/docker/compose/pull/2458" rel="noreferrer">PR 2458</a> was eventually merged to allow both (and use <code>image</code> as the image name when building, if it exists).</p>
<p><a href="https://stackoverflow.com/users/227926/therobyouknow"><code>therobyouknow</code></a> mentions <a href="https://stackoverflow.com/questions/34316047/difference-between-image-and-build-within-docker-compose/34316224#comment88754834_34316224">in the comments</a>:</p>
<blockquote>
<p><code>dockerfile:</code> as a sub-statement beneath <code>build:</code> can be used to specify the filename/path of the Dockerfile.</p>
</blockquote>
<pre><code>version: '3'
services:
webapp:
build:
context: ./dir
dockerfile: Dockerfile-alternate
args:
buildno: 1
</code></pre> |
21,335,832 | Laravel whereHas on multiple relationships | <p>Does anyone know if this <a href="http://laravel.com/docs/eloquent#querying-relations" rel="noreferrer">new feature</a> can be performed on multiple relationships?</p>
<p>For example, I have a query where I want to filter on not only the club name (<a href="https://stackoverflow.com/questions/21116742/wherehas-orwherehas-not-constraining-the-query-as-expected">related question</a>) but also the territory name. </p>
<p>In this example, I'd like query results where the club (club relationship) name is Arsenal and the the region is Australia (territory relationship)</p>
<pre><code>$ret->with('territory')->with('homeClub')->with('awayClub');
$ret->whereHas('territory',function( $query ){
$query->where('region','Australia');
})->whereHas('homeClub', function ( $query ) {
$query->where('name', 'Arsenal' );
})->orWhereHas('awayClub', function ( $query ) {
$query->where('name', 'Arsenal' );
});
</code></pre>
<p>When executing this query - the result isn't constraining the territory <code>whereHas</code> just the clubs one.</p>
<p>Can whereHas be chained to filter the results on previous relationship's whereHas? Any suggestions if not? </p>
<p>thanks</p>
<p>jon</p> | 21,356,760 | 4 | 0 | null | 2014-01-24 15:01:41.07 UTC | 8 | 2022-02-08 11:24:34.603 UTC | 2017-05-23 11:33:14.057 UTC | null | -1 | null | 1,194,469 | null | 1 | 19 | laravel-4 | 35,843 | <p>Yes that's possible.</p>
<p>The generated SQL will probably be:</p>
<pre><code>SELECT * FROM ... WHERE (territory constraint) AND (homeClub constratint) OR (awayClub constraint)
</code></pre>
<p>This means that if <code>awayClub constraint</code> is satisfied, the line will be retrieved. I think you want to add a parenthesis to the generated sql:</p>
<pre><code>SELECT * FROM ... WHERE (territory constraint) AND ((homeClub constratint) OR (awayClub constraint))
</code></pre>
<p>to do that, you need to nest both queries inside a where:</p>
<pre><code>$ret->with('territory')->with('homeClub')->with('awayClub');
$ret->whereHas('territory',function( $query ){
$query->where('region','Australia');
})
->where(function($subQuery)
{
$subQuery->whereHas('homeClub', function ( $query ) {
$query->where('name', 'Arsenal' );
})
->orWhereHas('awayClub', function ( $query ) {
$query->where('name', 'Arsenal' );
});
});
</code></pre> |
35,518,759 | How to wait for N seconds between statements in Scala? | <p>I have two statements like this:</p>
<pre><code>val a = 1
val b = 2
</code></pre>
<p>In between the 2 statements, I want to pause for N seconds like I can in <code>bash</code> with <code>sleep</code> command. </p> | 35,519,226 | 2 | 0 | null | 2016-02-20 03:27:35.477 UTC | 1 | 2017-06-26 14:18:22.837 UTC | 2017-06-26 14:18:22.837 UTC | null | 470,341 | null | 5,691,932 | null | 1 | 55 | scala|sleep | 83,980 | <p>You can try:</p>
<pre><code>val a = 1
Thread.sleep(1000) // wait for 1000 millisecond
val b = 2
</code></pre>
<p>You can change 1000 to other values to accommodate to your needs.</p> |
51,384,175 | Sqlite in flutter, how database assets work | <p>I am looking at this (<a href="https://github.com/tekartik/sqflite/blob/master/doc/opening_asset_db.md" rel="nofollow noreferrer">https://github.com/tekartik/sqflite/blob/master/doc/opening_asset_db.md</a>) for populating data that is already formatted and need for the app, for read functionality only.</p>
<p>So my understanding of creating an SQLite database when we already have all the information in an outside CSV file is to, create the class models in a .dart file in my app, such as</p>
<pre><code>class User {
int id;
String _firstName;
String _lastName;
String _dob;
User(this._firstName, this._lastName, this._dob);
User.map(dynamic obj) {
this._firstName = obj["firstname"];
this._lastName = obj["lastname"];
this._dob = obj["dob"];
}
String get firstName => _firstName;
String get lastName => _lastName;
String get dob => _dob;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["firstname"] = _firstName;
map["lastname"] = _lastName;
map["dob"] = _dob;
return map;
}
void setUserId(int id) {
this.id = id;
}
}
</code></pre>
<p>then if I have a CSV file with all the user information inside of it (with values that correspond to the user class), could I be using the database asset to have that fill out the information and then call to it inside of the flutter app? I realize there are probably many ways to go about this, but What exactly is the .db file storing, and how is it formatted? Can i implement a .csv file into this .db file?</p> | 51,387,985 | 4 | 0 | null | 2018-07-17 14:38:41.463 UTC | 11 | 2022-01-05 10:36:50.003 UTC | 2020-12-11 04:16:14.19 UTC | user10563627 | null | null | 9,989,514 | null | 1 | 11 | database|sqlite|flutter|dart|sqflite | 20,244 | <p>First off, you will need to construct a sqlite database from your csv. This can be done in the following way:</p>
<ol>
<li><p>Create the necessary table (users.sql)</p>
<pre><code>CREATE TABLE users(
firstname TEXT NOT NULL,
lastname TEXT NOT NULL,
dob TEXT NOT NULL
);
</code></pre></li>
<li><p>Create the sqlite database</p>
<pre><code>sqlite3 database.db < users.sql
</code></pre></li>
<li><p>Insert the csv data</p>
<pre><code>sqlite3 database.db
.mode csv
.import data.csv users
</code></pre></li>
<li><p>Put database.db into your assets and add that in pubspec.yaml.</p>
<pre><code>flutter:
# ...
assets:
- assets/database.db
</code></pre></li>
<li><p>In your app, you'll have to copy the asset file into "documents". This is slightly complicated.</p>
<pre><code>// Construct a file path to copy database to
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "asset_database.db");
// Only copy if the database doesn't exist
if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){
// Load database from asset and copy
ByteData data = await rootBundle.load(join('assets', 'database.db'));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Save copied asset to documents
await new File(path).writeAsBytes(bytes);
}
</code></pre></li>
<li><p>Lastly, you can access the database like so.</p>
<pre><code>Directory appDocDir = await getApplicationDocumentsDirectory();
String databasePath = join(appDocDir.path, 'asset_database.db');
this.db = await openDatabase(databasePath);
initialized = true;
</code></pre></li>
<li><p>Example query (this._initialize() is step 6)</p>
<pre><code>Future<List<Page>> search(String word, int parentId) async {
if (!initialized) await this._initialize();
String query = '''
SELECT * FROM users
LIMIT 25''';
return await this.db.rawQuery(query);
}
</code></pre></li>
</ol> |
43,159,849 | Trick to loop/autorefresh docker ps view like top/htop in bash | <p>Is it possible - and if yes, how - to have a self-refreshing view of current Docker containers printed by "docker ps" alike top/htop utilities?</p> | 43,160,290 | 3 | 0 | null | 2017-04-01 17:20:05.597 UTC | 5 | 2017-04-01 23:15:28.087 UTC | null | null | null | null | 4,422,958 | null | 1 | 46 | bash|docker|htop | 12,613 | <p>Use <code>watch</code>:</p>
<pre><code>watch docker ps
</code></pre>
<p>See <a href="https://linux.die.net/man/1/watch" rel="noreferrer"><code>man watch</code></a></p> |
38,369,855 | how to put exact number of decimal places on label ggplot bar chart | <p>How can I specify the exact number of decimal places on <code>ggplot</code> bar chart labels?</p>
<p>The data:</p>
<pre><code>strefa <- c(1:13)
a <- c(3.453782,3.295082,3.137755,3.333333,3.500000,3.351351,3.458824,3.318681,3.694175,3.241379,3.138298,3.309524,3.380000)
srednie <- data.frame(strefa,a)
</code></pre>
<p>The code is:</p>
<pre><code>ggplot(srednie, aes(x=factor(strefa), y=a, label=round(a, digits = 2))) +
geom_bar(position=position_dodge(), stat="identity", colour="darkgrey", width = 0.5) +
theme(legend.position="none",axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
geom_text(size = 4, hjust = 1.2) +
coord_flip(ylim = c(1,6))+
xlab("") +
ylab("")
</code></pre>
<p>As you can see, on bars entitled 5 and 2 the labels are limited to the 1st decimal place. How to show 2 decimal places even if there is i.e. 3.000000 or 5.999999? In such a cases I would like to show 3.00 and 6.00.</p>
<p>I tried to use as a <code>aes</code> parameter <code>label=round(a, digits = 2)</code> but it doesn't work.</p> | 38,370,083 | 1 | 0 | null | 2016-07-14 09:00:32.57 UTC | 7 | 2018-12-10 11:43:49.71 UTC | 2016-07-14 12:04:07.19 UTC | null | 4,411,559 | null | 6,449,064 | null | 1 | 26 | r|ggplot2|bar-chart | 71,125 | <p>You could try the following as it rounds to two digits and prints two digits after the decimal.</p>
<pre><code>ggplot(srednie, aes(x=factor(strefa), y=a, label=sprintf("%0.2f", round(a, digits = 2)))) +
geom_bar(position=position_dodge(), stat="identity", colour="darkgrey", width = 0.5) +
theme(legend.position="none",axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
geom_text(size = 4, hjust = 1.2) +
coord_flip(ylim = c(1,6))+
xlab("") +
ylab("")
</code></pre>
<p>The only modification was changing your code from</p>
<pre><code>round(a, digits = 2)
</code></pre>
<p>to </p>
<pre><code>sprintf("%0.2f", round(a, digits = 2))
</code></pre>
<p><a href="https://i.stack.imgur.com/zr8NK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zr8NK.png" alt="enter image description here"></a></p> |
3,198,765 | How to write Russian characters in file? | <p>In console when I'm trying output Russian characters It gives me ???????????????</p>
<p>Who know why?</p>
<p>I tried write to file - in this case the same situation.</p>
<p>for example</p>
<pre><code>f=open('tets.txt','w')
f.write('some russian text')
f.close
</code></pre>
<p>inside file is - ?????????????????????????/</p>
<p>or </p>
<pre><code>p="some russian text"
print p
?????????????
</code></pre>
<p>In additional Notepad don't allow me to save file with Russian letters. I give this:</p>
<blockquote>
<p>This file contains characters in
Unicode format which will be lost if
you save this file as an ANSI encoded
text file. To keep the Unicode
information, click Cancel below and
then select one of the Unicode options
from the Encoding drop down list.
Continue?</p>
</blockquote>
<p>How to adjust my system, so I will don't have this problems.</p> | 3,204,861 | 5 | 8 | null | 2010-07-07 20:59:44.31 UTC | 2 | 2016-03-25 19:00:12.717 UTC | 2016-03-25 19:00:12.717 UTC | null | 2,306,173 | null | 375,373 | null | 1 | 11 | python|windows|unicode|python-2.x|python-unicode | 53,639 | <p>Here is a worked-out example, please read the comments:</p>
<pre><code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
from __future__ import with_statement # Not required in Python 2.6 any more
import codecs
p = u"абвгдежзийкл" # note the 'u' prefix
print p # probably won't work on Windows due to a complex issue
with codecs.open("tets.txt", "w", "utf-16") as stream: # or utf-8
stream.write(p + u"\n")
# Now you should have a file called "tets.txt" that can be opened with Notepad or any other editor
</code></pre> |
2,523,284 | Java string replace and the NUL (NULL, ASCII 0) character? | <p>Testing out someone elses code, I noticed a few JSP pages printing funky non-ASCII characters. Taking a dip into the source I found this tidbit:</p>
<pre><code>// remove any periods from first name e.g. Mr. John --> Mr John
firstName = firstName.trim().replace('.','\0');
</code></pre>
<p>Does replacing a character in a String with a null character even work in Java? I know that <code>'\0'</code> will terminate a C-string. Would this be the culprit to the funky characters?</p> | 2,523,618 | 5 | 1 | null | 2010-03-26 12:48:02.527 UTC | 8 | 2012-03-17 20:58:36.59 UTC | 2012-03-17 20:58:36.59 UTC | user166390 | null | null | 229,109 | null | 1 | 35 | java|string|replace|nul | 117,345 | <blockquote>
<p>Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.</p>
</blockquote>
<p>That depends on how you define what is working. Does it replace all occurrences of the target character with <code>'\0'</code>? Absolutely!</p>
<pre><code>String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"
</code></pre>
<p>Everything seems to work fine to me! <code>indexOf</code> can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.</p>
<p>It <em>DOESN'T</em> work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!</p>
<pre><code>String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;
</code></pre>
<p>It also <em>DOESN'T</em> work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (<a href="http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.9" rel="noreferrer">10.9. An Array of Characters is Not a String</a>):</p>
<blockquote>
<p>In the Java programming language, unlike C, an array of <code>char</code> is not a <code>String</code>, and neither a <code>String</code> nor an array of <code>char</code> is terminated by '\u0000' (the NUL character).</p>
</blockquote>
<hr>
<blockquote>
<p>Would this be the culprit to the funky characters?</p>
</blockquote>
<p>Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.</p>
<p>That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.</p>
<hr>
<p>Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the <code>replace(CharSequence, CharSequence)</code> overload.</p>
<pre><code>System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU
</code></pre>
<p>The <code>replaceAll</code> solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.</p> |
3,109,473 | Moving default AVD configuration folder (.android) | <p>After installation of Android SDK, the folder <code>.android</code> was created on the <code>E:\</code> drive. As far as I know, this is the default folder of Android Virtual Devices for configuration files.</p>
<p>How can I move <code>.android</code> folder to a different location?</p>
<p>(eg. from <code>E:\.android</code> to <code>E:\Android\.android</code>)</p> | 3,110,562 | 8 | 1 | null | 2010-06-24 11:24:51.203 UTC | 32 | 2022-08-03 06:08:06.723 UTC | 2022-08-03 06:08:06.723 UTC | null | 361,832 | null | 361,832 | null | 1 | 118 | windows|android|android-emulator|avd | 94,706 | <p><strong>I've found the answer.</strong></p>
<ul>
<li>Move <code>.android</code> folder to <code>E:\Android</code></li>
<li>Create environment variable called
<strong>ANDROID_SDK_HOME</strong> and set its value to
<code>E:\Android</code></li>
</ul>
<p>Setting the environment variable on Windows XP or Windows 7:</p>
<ol>
<li>Right-click on My Computer and choose "Properties"</li>
<li>Click the "Advanced" tab</li>
<li>Click the button "Environment Variables".</li>
<li>Add New variable</li>
</ol> |
2,838,490 | A table name as a variable | <p>I am trying to execute this query:</p>
<pre><code>declare @tablename varchar(50)
set @tablename = 'test'
select * from @tablename
</code></pre>
<p>This produces the following error:</p>
<blockquote>
<p>Msg 1087, Level 16, State 1, Line 5</p>
<p>Must declare the table variable "@tablename".</p>
</blockquote>
<p>What's the right way to have the table name populated dynamically?</p> | 2,838,507 | 10 | 0 | null | 2010-05-15 01:07:17.497 UTC | 58 | 2022-05-20 13:10:28.8 UTC | 2021-01-20 07:46:57.14 UTC | null | 63,550 | null | 168,882 | null | 1 | 211 | sql|sql-server|tsql|variable-names|tablename | 516,354 | <p>For static queries, like the one in your question, table names and column names need to be static.</p>
<p>For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.</p>
<p>Here is an example of a script used to compare data between the same tables of different databases:</p>
<p>Static query:</p>
<pre><code>SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
</code></pre>
<p>Since I want to easily change the name of <code>table</code> and <code>schema</code>, I have created this dynamic query:</p>
<pre><code>declare @schema sysname;
declare @table sysname;
declare @query nvarchar(max);
set @schema = 'dbo'
set @table = 'ACTY'
set @query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(@schema) + '.' + QUOTENAME(@table);
EXEC sp_executesql @query
</code></pre>
<p>Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: <a href="http://www.sommarskog.se/dynamic_sql.html" rel="noreferrer">The curse and blessings of dynamic SQL</a></p> |
2,939,820 | How can I enable cURL for an installed Ubuntu LAMP stack? | <p>I have installed the Ubuntu LAMP stack. But cURL is not enabled, and neither can I can find the extension listed in the INI file. I added it manually, but it didn't work either.</p>
<p>How should I enable cURL then?</p> | 2,939,827 | 10 | 3 | null | 2010-05-30 18:33:48.157 UTC | 50 | 2022-04-03 01:25:25.333 UTC | 2021-02-13 02:03:36.227 UTC | null | 63,550 | null | 349,297 | null | 1 | 223 | php|ubuntu|curl|lamp | 305,955 | <p>From <em><a href="http://buzznol.blogspot.com/2008/12/install-curl-extension-for-php-in.html" rel="noreferrer">Install Curl Extension for PHP in Ubuntu</a></em>:</p>
<pre><code>sudo apt-get install php5-curl
</code></pre>
<p>After installing libcurl, you should restart the web server with one of the following commands,</p>
<pre><code>sudo /etc/init.d/apache2 restart
</code></pre>
<p><em>or</em></p>
<pre><code>sudo service apache2 restart
</code></pre> |
2,806,420 | Visual Studio Formatting -- Change Method Color | <p>The default appearance of a method for example, ".ToString()" is by default the color black. I want to make it a different color to stand out but I do not see any options that reference this option specifically.</p>
<p>I remember one of former collegues showing me his VS IDE years ago and he had it setup this way but I cannot recall what he did.</p>
<p>Does anyone have any ideas on how to do this?</p> | 2,806,975 | 11 | 0 | null | 2010-05-10 20:59:18.077 UTC | 3 | 2020-05-25 07:29:51.973 UTC | 2010-05-10 21:12:24.067 UTC | user319799 | null | null | 337,684 | null | 1 | 23 | visual-studio|formatting|methods|colors | 42,197 | <p>The built-in syntax highlighters use <em>lexical analysis</em>. A lexer can classify identifiers, comments, literals, numbers, keywords. The parts you find back in the Tools > Options > Environment > Fonts and Colors dialog. </p>
<p>Recognizing that an identifier is a method, property, field requires <em>parsing</em>. Parsing generally only works well when you've got a well-formed program, you rarely have one while you are typing code. So wasn't favored by Microsoft. You can find alternatives in the <a href="https://marketplace.visualstudio.com/search?term=syntax%20highlighting&target=VS&sortBy=Relevance" rel="noreferrer">Visual Studio gallery</a>.</p> |
3,110,154 | Why is the explicit management of threads a bad thing? | <p>In <a href="https://stackoverflow.com/questions/3109647/which-c-assembly-contains-invoke">a previous question</a>, I made a bit of a faux pas. You see, I'd been reading about threads and had got the impression that they were the tastiest things since kiwi jello.</p>
<p>Imagine my confusion then, when I read stuff like this:</p>
<blockquote>
<p>[T]hreads are A Very Bad Thing. Or, at least, explicit management of threads is a bad thing</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Updating the UI across threads is usually a sign that you are abusing threads.</p>
</blockquote>
<p>Since I kill a puppy every time something confuses me, consider this your chance get your karma back in the black...</p>
<p>How should I be using thread?</p> | 3,111,104 | 12 | 11 | null | 2010-06-24 13:04:49.883 UTC | 32 | 2010-10-03 17:19:00.463 UTC | 2017-05-23 12:08:53.243 UTC | null | -1 | null | 50,151 | null | 1 | 47 | c#|multithreading | 5,013 | <p>Enthusiam for learning about threading is great; don't get me wrong. Enthusiasm for <em>using lots of threads</em>, by contrast, is symptomatic of what I call Thread Happiness Disease. </p>
<p>Developers who have just learned about the power of threads start asking questions like "how many threads can I possible create in one program?" This is rather like an English major asking "how many words can I use in a sentence?" Typical advice for writers is to keep your sentences short and to the point, rather than trying to cram as many words and ideas into one sentence as possible. Threads are the same way; the right question is not "how many can I get away with creating?" but rather "how can I write this program so that the number of threads is the <em>minimum</em> necessary to get the job done?" </p>
<p>Threads solve a lot of problems, it's true, but they also introduce huge problems:</p>
<ul>
<li>Performance analysis of multi-threaded programs is often extremely difficult and deeply counterintuitive. I've seen real-world examples in heavily multi-threaded programs in which making a function faster <em>without slowing down any other function or using more memory</em> makes the total throughput of the system <em>smaller</em>. Why? Because threads are often like streets downtown. Imagine taking every street and magically making it shorter <em>without re-timing the traffic lights</em>. Would traffic jams get better, or worse? Writing faster functions in multi-threaded programs <em>drives the processors towards congestion faster</em>. </li>
</ul>
<p>What you want is for threads to be like interstate highways: no traffic lights, highly parallel, intersecting at a small number of very well-defined, carefully engineered points. <em>That is very hard to do.</em> Most heavily multi-threaded programs are more like dense urban cores with stoplights everywhere.</p>
<ul>
<li>Writing your own custom management of threads is insanely difficult to get right. The reason is because when you are writing a regular single-threaded program in a well-designed program, the amount of "global state" you have to reason about is typically small. Ideally you write objects that have well-defined boundaries, and that do not care about the control flow that invokes their members. You want to invoke an object in a loop, or a switch, or whatever, you go right ahead.</li>
</ul>
<p>Multi-threaded programs with custom thread management require <em>global</em> understanding of <em>everything</em> that a thread is going to do that could <em>possibly</em> affect data that is visible from another thread. You pretty much have to have the entire program in your head, and understand <em>all</em> the possible ways that two threads could be interacting in order to get it right and prevent deadlocks or data corruption. That is a large cost to pay, and highly prone to bugs.</p>
<ul>
<li><p>Essentially, threads make your methods <em>lie</em>. Let me give you an example. Suppose you have:</p>
<p>if (!queue.IsEmpty) queue.RemoveWorkItem().Execute();</p></li>
</ul>
<p>Is that code correct? If it is single threaded, probably. If it is multi-threaded, what is stopping another thread from removing the last remaining item <em>after</em> the call to IsEmpty is executed? Nothing, that's what. This code, which locally looks just fine, is a bomb waiting to go off in a multi-threaded program. Basically that code is actually:</p>
<pre><code> if (queue.WasNotEmptyAtSomePointInThePast) ...
</code></pre>
<p>which obviously is pretty useless. </p>
<p>So suppose you decide to fix the problem by locking the queue. Is this right?</p>
<pre><code>lock(queue) {if (!queue.IsEmpty) queue.RemoveWorkItem().Execute(); }
</code></pre>
<p>That's not right either, necessarily. Suppose the execution causes code to run which waits on a resource currently locked by another thread, but that thread is waiting on the lock for queue - what happens? Both threads wait forever. Putting a lock around a hunk of code requires you to know <em>everything</em> that code could <em>possibly</em> do with <em>any</em> shared resource, so that you can work out whether there will be any deadlocks. Again, that is an extremely heavy burden to put on someone writing what ought to be very simple code. (The right thing to do here is probably to extract the work item in the lock and then execute it outside the lock. But... what if the items are in a queue because they have to be executed in a particular order? Now that code is wrong too because other threads can then execute later jobs first.)</p>
<ul>
<li>It gets worse. The C# language spec guarantees that a single-threaded program will have observable behaviour that is exactly as the program is specified. That is, if you have something like "if (M(ref x)) b = 10;" then you know that the code generated will behave as though x is accessed by M <em>before</em> b is written. Now, the compiler, jitter and CPU are all free to optimize that. If one of them can determine that M is going to be true and if we know that on this thread, the value of b is not read after the call to M, then b can be assigned before x is accessed. All that is guaranteed is that the single-threaded program <em>seems to work like it was written</em>. </li>
</ul>
<p>Multi-threaded programs do <em>not</em> make that guarantee. If you are examining b and x on a different thread while this one is running then you <em>can</em> see b change before x is accessed, if that optimization is performed. <em>Reads and writes can logically be moved forwards and backwards in time with respect to each other in single threaded programs, and those moves can be observed in multi-threaded programs.</em></p>
<p>This means that in order to write multi-threaded programs where there is a dependency in the logic on things being observed to happen in the same order as the code is actually written, you have to have a <em>detailed</em> understanding of the "memory model" of the language and the runtime. You have to know precisely what guarantees are made about how accesses can move around in time. And you cannot simply test on your x86 box and hope for the best; the x86 chips have pretty conservative optimizations compared to some other chips out there.</p>
<p>That's just a brief overview of just a few of the problems you run into when writing your own multithreaded logic. There are plenty more. So, some advice:</p>
<ul>
<li>Do learn about threading.</li>
<li>Do not attempt to write your own thread management in production code.</li>
<li>Use higher-level libraries written by experts to solve problems with threads. If you have a bunch of work that needs to be done in the background and want to farm it out to worker threads, use a thread pool rather than writing your own thread creation logic. If you have a problem that is amenable to solution by multiple processors at once, use the Task Parallel Library. If you want to lazily initialize a resource, use the lazy initialization class rather than trying to write lock free code yourself.</li>
<li>Avoid shared state.</li>
<li>If you can't avoid shared state, share immutable state.</li>
<li>If you have to share mutable state, prefer using locks to lock-free techniques.</li>
</ul> |
2,596,805 | How do I make git use the editor of my choice for editing commit messages? | <p>How do I globally configure git to use a particular editor (e.g. <code>vim</code>) for commit messages?</p> | 2,596,835 | 30 | 3 | null | 2010-04-08 00:28:46.9 UTC | 576 | 2022-08-27 15:56:50.64 UTC | 2022-07-11 06:25:00.4 UTC | null | 365,102 | null | 6,340 | null | 1 | 3,110 | git|vim|emacs|editor|commit-message | 1,218,209 | <h4>Setting the default editor for Git</h4>
<p>Pick one:</p>
<ul>
<li><p>Set <a href="http://git-scm.com/book/en/Customizing-Git-Git-Configuration#Basic-Client-Configuration" rel="noreferrer"><code>core.editor</code></a> in your Git config:</p>
<pre><code>git config --global core.editor "vim"
</code></pre>
</li>
<li><p>Set the <a href="http://git-scm.com/docs/git-var#_variables" rel="noreferrer"><code>GIT_EDITOR</code></a> environment variable:</p>
<pre><code>export GIT_EDITOR=vim
</code></pre>
</li>
</ul>
<hr />
<h4>Setting the default editor for all programs</h4>
<p>Set the standardized <code>VISUAL</code> and <code>EDITOR</code> environment variables*:</p>
<pre><code>export VISUAL=vim
export EDITOR="$VISUAL"
</code></pre>
<p><strong>NOTE:</strong> Setting both is not necessarily needed, but some programs may not use the more-correct <code>VISUAL</code>. See <a href="https://unix.stackexchange.com/questions/4859/visual-vs-editor-whats-the-difference"><code>VISUAL</code> vs. <code>EDITOR</code></a>.</p>
<hr />
<h4>Fixing compatibility issues</h4>
<p>Some editors require a <code>--wait</code> flag, or they will open a blank page. For example:</p>
<ul>
<li><p><strong>Sublime Text</strong> (if <a href="https://stackoverflow.com/questions/25152711/subl-command-not-working-command-not-found/25154529">correctly set up</a>; or use the full path to the executable in place of <code>subl</code>):</p>
<pre><code>export VISUAL="subl --wait"
</code></pre>
</li>
<li><p><strong>VS Code</strong> (after adding the <a href="https://stackoverflow.com/questions/29955500/code-not-working-in-command-line-for-visual-studio-code-on-osx-mac">shell command</a>):</p>
<pre><code>export VISUAL="code --wait"
</code></pre>
</li>
</ul> |
10,825,849 | MVC3 Action File Size Limit | <p>I'm implementing a jquery based file upload plugin <a href="http://blueimp.github.com/jQuery-File-Upload/" rel="nofollow noreferrer">http://blueimp.github.com/jQuery-File-Upload/</a>. There is a sample MVC3 app that you can download <a href="https://github.com/maxpavlov/jQuery-File-Upload.MVC3" rel="nofollow noreferrer">https://github.com/maxpavlov/jQuery-File-Upload.MVC3</a>.</p>
<p>The author of the sample has a comment in the Home View:
</p>
<blockquote>
<p>@*IN ORDER TO USE MVC ACTIONS AS HANDLERS OF AJAX CALLS, USE THE FORM DECLARATION BELOW. (THE ONE COMMENTED OUT)
IT IS NOT ADVISED SINCE WHEN USING MVC CONTROLLER TO HANDLE REQUESTS ONE CAN'T CONTROL THE maxMessageLength OF THE POST REQUEST
THIS CASTS THE FUNCTIONALITY OF UPLOADING LARGE FILES USELESS, UNLESS YOU SUCRIFICE THE SECURITY AND ALLOW LARGE
POST MESSAGE SIZES SITE-WIDE.</p>
<p>IT IS BETTER TO USE HTTP HANDLER TO PROCESS UPLOAD REQUESTS UNTIL MVC FRAMEWORK PROVIDES WAYS TO SET maxMessageLength ON
PER ACTION BASIS *@</p>
</blockquote>
<p>Is this still the case?</p>
<p>I've found out I can set the <code><httpRuntime maxRequestLength="x" /></code> in the web.config, but my understanding is that this is a security vulnerability. Is the case also?</p>
<p>I would prefer to handle my upload in the controller instead of using an HttpHandler but don't want to be limited by file size and don't want to introduce any security vulnerabilities if I don't have to.</p>
<p><strong>Update:</strong></p>
<p>According to this post <a href="https://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc3-0">File Upload ASP.NET MVC 3.0</a> the default file size limit is 4mb. I've confirmed this limit <a href="http://msdn.microsoft.com/en-us/library/e1f13641.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/e1f13641.aspx</a> and understand the vulnerability. </p>
<p><strong>Is this the only way to upload a file thru a controller action beyond 4mb?</strong></p> | 10,834,379 | 1 | 0 | null | 2012-05-30 23:59:08.9 UTC | 10 | 2014-07-11 07:51:53.333 UTC | 2017-05-23 12:25:34.227 UTC | null | -1 | null | 718,073 | null | 1 | 26 | asp.net-mvc-3 | 15,923 | <p>You could set upload size limit in <em>web.config</em> for concrete controller action using <a href="http://msdn.microsoft.com/en-us/library/b6x6shw7(v=vs.100).aspx" rel="noreferrer">location</a> element:</p>
<pre class="lang-xml prettyprint-override"><code><configuration>
<location path="Home/UploadFiles">
<system.web>
<httpRuntime maxRequestLength="40960"/>
</system.web>
</location>
</configuration>
</code></pre>
<p>Where <em>Home</em> is a controller name and <em>UploadFiles</em> is an action name. Size limit is 40MB here.</p>
<p>Still, using Http Handler to process file uploads is not a bad solution if you ask me.</p> |
10,548,744 | Django lazy QuerySet and pagination | <p>I read <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy">here</a> that Django querysets are lazy, it won't be evaluated until it is actually printed. I have made a simple pagination using the django's built-in pagination. I didn't realize there were apps already such as "django-pagination", and "django-endless" which does that job for.</p>
<p>Anyway I wonder whether the QuerySet is still lazy when I for example do this</p>
<pre><code>entries = Entry.objects.filter(...)
paginator = Paginator(entries, 10)
output = paginator.page(page)
return HttpResponse(output)
</code></pre>
<p>And this part is called every time I want to get whatever page I currently I want to view.</p>
<p>I need to know since I don't want unnecessary load to the database.</p> | 10,549,382 | 2 | 0 | null | 2012-05-11 09:22:23.883 UTC | 16 | 2015-07-15 11:13:43.86 UTC | null | null | null | null | 445,600 | null | 1 | 27 | django|lazy-loading|django-queryset | 23,162 | <p>If you want to see where are occurring, import <code>django.db.connection</code> and inspect <code>queries</code></p>
<pre><code>>>> from django.db import connection
>>> from django.core.paginator import Paginator
>>> queryset = Entry.objects.all()
</code></pre>
<p>Lets create the paginator, and see if any queries occur:</p>
<pre><code>>>> paginator = Paginator(queryset, 10)
>>> print connection.queries
[]
</code></pre>
<p>None yet.</p>
<pre><code>>>> page = paginator.page(4)
>>> page
<Page 4 of 788>
>>> print connection.queries
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}]
</code></pre>
<p>Creating the page has produced one query, to count how many entries are in the queryset. The entries have not been fetched yet.</p>
<p>Assign the page's objects to the variable 'objects':</p>
<pre><code>>>> objects = page.object_list
>>> print connection.queries
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}]
</code></pre>
<p>This still hasn't caused the entries to be fetched.</p>
<p>Generate the <code>HttpResponse</code> from the object list</p>
<pre><code>>>> response = HttpResponse(page.object_list)
>>> print connection.queries
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}, {'time': '0.011', 'sql': 'SELECT `entry`.`id`, <snip> FROM `entry` LIMIT 10 OFFSET 30'}]
</code></pre>
<p>Finally, the entries have been fetched.</p> |
10,487,011 | Creating a DateTime object with a specific UTC DateTime in PowerShell | <p>I'm trying to create a <code>DateTime</code> object with a specific UTC timestamp in PowerShell. What's the simplest way to do this?</p>
<p>I tried:</p>
<pre><code>Get-Date
-Format (Get-Culture).DateTimeFormat.UniversalSortableDateTimePattern
-Date "1970-01-01 00:00:00Z"
</code></pre>
<p>but I get this output:</p>
<pre><code>1969-12-31 19:00:00Z
</code></pre>
<p>It's a few hours off. Where's my lapse in understanding?</p> | 10,487,050 | 6 | 0 | null | 2012-05-07 18:17:02.89 UTC | 7 | 2018-07-19 15:39:38.383 UTC | null | null | null | null | 111,327 | null | 1 | 42 | datetime|powershell|utc | 108,097 | <p>The <code>DateTime</code> object itself is being created with the proper UTC time. But when PowerShell prints it out it converts it to my local culture and time zone, thus the difference.</p>
<p>Proof:</p>
<pre><code>$UtcTime = Get-Date -Date "1970-01-01 00:00:00Z"
$UtcTime.ToUniversalTime()
</code></pre> |
10,843,572 | How to create Javascript constants as properties of objects using const keyword? | <p>How come constants cannot be set as properties of objects which are variables themselves?</p>
<pre><code>const a = 'constant' // all is well
// set constant property of variable object
const window.b = 'constant' // throws Exception
// OR
var App = {}; // want to be able to extend
const App.goldenRatio= 1.6180339887 // throws Exception
</code></pre>
<p>And how come constants passed by reference suddenly become variable?
EDIT: I know App won't (or rather... SHOULDN'T) be mutable; this is just an observation...</p>
<pre><code>(function() {
const App;
// bunch of code
window.com_namespace = App;
}());
window.com_namespace; // App
window.com_namespace = 'something else';
window.com_namespace; // 'something else'
</code></pre>
<p>How can a nicely organized, extensible, object-oriented, singly namespaced library containing constants be made with these limitations?</p>
<p>EDIT: I believe zi42, but I just have to ask <a href="https://stackoverflow.com/questions/10843809/why-is-it-impossible-to-assign-constant-properties-of-javascript-objects-using-t">why</a></p> | 10,843,598 | 6 | 0 | null | 2012-06-01 02:09:44.403 UTC | 14 | 2022-08-19 22:34:32.69 UTC | 2017-05-23 12:18:03.733 UTC | null | -1 | null | 712,558 | null | 1 | 54 | javascript|object|properties|constants | 61,190 | <p>You cannot do it with constants. The only possible way to do something that behaves like you want, but is not using constants, is to define a non-writable property:</p>
<pre><code>var obj = {};
Object.defineProperty( obj, "MY_FAKE_CONSTANT", {
value: "MY_FAKE_CONSTANT_VALUE",
writable: false,
enumerable: true,
configurable: true
});
</code></pre>
<p>Regarding your question as to why a <code>const</code> passed to a function becomes variable, the answer is because it's passed by value and not by reference. The function is getting a new variable that has the same value as your constant.</p>
<p><strong>edit</strong>: thanks to @pst for noting that objects literals in javascript are not actually "passed by reference", but using <a href="https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing" rel="noreferrer">call-by-sharing</a>:</p>
<blockquote>
<p>Although this term has widespread usage in the Python community, identical semantics in other languages such as Java and Visual Basic are often described as call-by-value, where the value is implied to be a reference to the object.</p>
</blockquote> |
5,705,981 | How to embed a swf file into html code? | <p>I need to embed a swf file into html code. How can I do it? </p> | 5,705,992 | 3 | 2 | null | 2011-04-18 16:32:43.367 UTC | 2 | 2018-02-08 15:26:45.197 UTC | 2015-09-08 14:21:53.367 UTC | null | 445,131 | null | 602,202 | null | 1 | 1 | html|flash | 50,504 | <p>Use SWFObject:</p>
<p><a href="http://code.google.com/p/swfobject/wiki/documentation" rel="noreferrer">http://code.google.com/p/swfobject/wiki/documentation</a></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 3</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
</script>
</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>
</code></pre> |
33,271,928 | Move HTML element upwards on hover | <p>I am trying to move an HTML element up about 10px whenever a user hovers their mouse over it. I did some research on w3schools, but I could not find any information that helped me. Most of their animation examples were using keyframes and I'm pretty sure that's not what I need because I'm trying to trigger an animation when somebody hovers over the element. I could be wrong though and that's why I'm posting here.</p>
<p>Here's the element I'm trying to move:</p>
<pre><code><div id="arrow">
<a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>
</code></pre>
<p>For my CSS:</p>
<pre><code>#arrow {
padding-top: 310px;
color: #5C6B7E;
position: relative;
/* some kind of animation property here? */
}
#arrow:hover {
/* new properties once user hovers */
}
</code></pre>
<p>I'm not sure what I need to add to make the element animate up, the examples on w3schools weren't of much help. If anybody could point me in the right direction I would be extremely appreciative. Thank you Stack Overflow.</p> | 33,272,031 | 3 | 1 | null | 2015-10-22 01:21:20.803 UTC | 10 | 2022-07-13 18:28:34.263 UTC | 2022-07-13 18:28:34.263 UTC | null | 18,206,501 | user3635683 | null | null | 1 | 35 | html|css|css-animations | 81,979 | <p>You need not use keyframes for this simple animation. Just CSS transition is enough.</p>
<p>Set the <code>transition</code> property in the initial state style rules with the duration.</p>
<p><strong>Edit:</strong> I just noticed that there is a flicker at the bottom, it can be removed by setting the styles on the icon and hover on the parent.</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-css lang-css prettyprint-override"><code>#arrow i {
position: relative;
top: 0;
transition: top ease 0.5s;
}
#arrow:hover i {
top: -10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="arrow">
<a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div></code></pre>
</div>
</div>
</p> |
40,958,613 | How to copy URL on button click? | <p>I am trying to copy the current page URL in the text area on button click. Somehow I have tried but is not working.
<a href="http://www.w3schools.com/code/tryit.asp?filename=FAF25LWITXR5" rel="noreferrer">http://www.w3schools.com/code/tryit.asp?filename=FAF25LWITXR5</a></p>
<pre class="lang-js prettyprint-override"><code>
function Copy()
{
var Url = document.createElement("textarea");
Url.innerHTML = window.location.href;
Copied = Url.createTextRange();
Copied.execCommand("Copy");
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br />
Paste: <textarea rows="1" cols="30"></textarea>
</div>
</code></pre> | 40,958,674 | 7 | 0 | null | 2016-12-04 12:28:09.84 UTC | 8 | 2022-01-10 20:26:07.37 UTC | 2020-06-18 21:51:17.403 UTC | null | 2,437,521 | null | 5,751,745 | null | 1 | 13 | javascript|php|jquery|html|web | 72,446 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title></title>
</head>
<script type="text/javascript">
function Copy()
{
//var Url = document.createElement("textarea");
urlCopied.innerHTML = window.location.href;
//Copied = Url.createTextRange();
//Copied.execCommand("Copy");
}
</script>
<body>
<div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br />
Paste: <textarea id="urlCopied" rows="1" cols="30"></textarea>
</div>
</body>
</html></code></pre>
</div>
</div>
</p> |
32,392,937 | How Kafka distributes the topic partitions among the brokers | <p>I have 3 Kafka brokers in 3 different VMs, with one additionally running a Zookeeper. I now create a topic with 8 partitions. The Producer pushes messages to these group of brokers on the created "topic". </p>
<ul>
<li>How does the Kafka distribute a topic and its partitions among the brokers? </li>
<li>Does the Kafka redistribute the topic when a new Kafka Broker joins a cluster?</li>
<li>Can the topic partition be increased after the topic was created?</li>
</ul> | 32,405,720 | 1 | 0 | null | 2015-09-04 07:56:40.707 UTC | 10 | 2021-05-24 19:50:59.22 UTC | null | null | null | null | 1,353,364 | null | 1 | 18 | apache-kafka|kafka-consumer-api | 5,059 | <ul>
<li><p>When you create a new topic, Kafka places the partitions and replicas in a way that the brokers with least number of existing partitions are used first, and replicas for same partition are on different brokers.</p></li>
<li><p>When you add a new broker, it is used for new partitions (since it has lowest number of existing partitions), but there is no automatic balancing of existing partitions to the new broker. You can use the replica-reassignment tool to move partitions and replicas to the new broker.</p></li>
<li><p>Yes, you can add partitions to an existing topic.</p></li>
</ul> |
17,874,489 | Disambiguate overloaded member function pointer being passed as template parameter | <p>I am attempting to recreate the <strong>Observer pattern</strong> where I can perfectly forward parameters to a given member function of the observers.</p>
<p>If I attempt to pass the address of a <strong>member function</strong> which has <strong>multiple overrides</strong>, it cannot deduce the correct member function based on the arguments.</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
template<typename Class>
struct observer_list
{
template<typename Ret, typename... Args, typename... UArgs>
void call(Ret (Class::*func)(Args...), UArgs&&... args)
{
for (auto obj : _observers)
{
(obj->*func)(std::forward<UArgs>(args)...);
}
}
std::vector<Class*> _observers;
};
struct foo
{
void func(const std::string& s)
{
std::cout << this << ": " << s << std::endl;
}
void func(const double d)
{
std::cout << this << ": " << d << std::endl;
}
};
int main()
{
observer_list<foo> l;
foo f1, f2;
l._observers = { &f1, &f2 };
l.call(&foo::func, "hello");
l.call(&foo::func, 0.5);
return 0;
}
</code></pre>
<p>This fails to compile with <code>template argument deduction/substitution failed</code>.</p>
<p>Note that I had <code>Args...</code> and <code>UArgs...</code> because I need to be able to pass parameters which are not necessarily the same type asthe type of the function signature, but are convertible to said type.</p>
<p>I was thinking I could use a <code>std::enable_if<std::is_convertible<Args, UArgs>></code> call to disambiguate, but I don't believe I can do this with a variadic template parameter pack?</p>
<p><strong>How can I get the template argument deduction to work here?</strong></p> | 17,875,252 | 1 | 1 | null | 2013-07-26 06:35:18.193 UTC | 10 | 2014-10-24 22:06:38.097 UTC | 2013-07-26 07:18:12.977 UTC | null | 500,104 | null | 955,273 | null | 1 | 47 | c++|templates|c++11|typetraits | 19,559 | <p>The issue is here:</p>
<pre><code>l.call(&foo::func, "hello");
l.call(&foo::func, 0.5);
</code></pre>
<p>For both lines, the compiler doesn't know which <code>foo::func</code> you are referring to. Hence, you have to disambiguate yourself by providing the type information that is missing (i.e., the type of <code>foo:func</code>) through casts:</p>
<pre><code>l.call(static_cast<void (foo::*)(const std::string&)>(&foo::func), "hello");
l.call(static_cast<void (foo::*)(const double )>(&foo::func), 0.5);
</code></pre>
<p>Alternatively, you can provide the template arguments that the compiler cannot deduce and that define the type of <code>func</code>:</p>
<pre><code>l.call<void, const std::string&>(&foo::func, "hello");
l.call<void, double >(&foo::func, 0.5);
</code></pre>
<p>Notice that you have to use <code>double</code> and not <code>const double</code> above. The reason is that generally <code>double</code> and <code>const double</code> are two different types. However, there's one situation where <code>double</code> and <code>const double</code> are considered as if they were the same type: as function arguments. For instance,</p>
<pre><code>void bar(const double);
void bar(double);
</code></pre>
<p>are not two different overloads but are actually the same function.</p> |
52,272,533 | Does every stateful intermediate Stream API operation guarantee a new source collection? | <p>Is the following statement true?</p>
<blockquote>
<p>The <code>sorted()</code> operation is a “stateful intermediate operation”, which means that subsequent operations no longer operate on the backing collection, but on an internal state.</p>
</blockquote>
<p><sup>(<a href="https://www.toptal.com/java/top-10-most-common-java-development-mistakes" rel="nofollow noreferrer">Source</a> and <a href="https://dzone.com/articles/java-8-friday-10-subtle" rel="nofollow noreferrer">source</a> - they seem to copy from each other or come from the same source.)</sup></p>
<p><strong>Disclaimer:</strong> I am aware the following snippets are not legit usages of Java Stream API. Don't use in the production code.</p>
<p>I have tested <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> as a snippet from sources above:</p>
<pre><code>final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.sorted()
.forEach(list::remove);
System.out.println(list); // Prints [0, 1, 2, 3, 4, 5]
</code></pre>
<p>It works. I replaced <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> with <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--" rel="nofollow noreferrer"><code>Stream::distinct</code></a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#limit-long-" rel="nofollow noreferrer"><code>Stream::limit</code></a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-" rel="nofollow noreferrer"><code>Stream::skip</code></a>:</p>
<pre><code>final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.distinct()
.forEach(list::remove); // Throws NullPointerException
</code></pre>
<p>To my surprise, the <code>NullPointerException</code> is thrown.</p>
<p>All the tested methods follow the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps" rel="nofollow noreferrer">stateful intermediate operation</a> characteristics. Yet, this unique behavior of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--" rel="nofollow noreferrer"><code>Stream::sorted</code></a> is not documented nor the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps" rel="nofollow noreferrer">Stream operations and pipelines</a> part explains whether the <em>stateful intermediate operations</em> really guarantee a new source collection.</p>
<p>Where my confusion comes from and what is the explanation of the behavior above?</p> | 52,272,725 | 3 | 1 | null | 2018-09-11 09:11:38.697 UTC | 6 | 2022-01-02 13:36:21.563 UTC | 2022-01-02 13:36:21.563 UTC | null | 3,764,965 | null | 3,764,965 | null | 1 | 33 | java|java-8|java-stream | 1,821 | <p>The API documentation makes no such guarantee “that subsequent operations no longer operate on the backing collection”, hence, you should never rely on such a behavior of a particular implementation.</p>
<p>Your example happens to do the desired thing by accident; there’s not even a guarantee that the <code>List</code> created by <code>collect(Collectors.toList())</code> supports the <code>remove</code> operation.</p>
<p>To show a counter-example</p>
<pre><code>Set<Integer> set = IntStream.range(0, 10).boxed()
.collect(Collectors.toCollection(TreeSet::new));
set.stream()
.filter(i -> i > 5)
.sorted()
.forEach(set::remove);
</code></pre>
<p>throws a <code>ConcurrentModificationException</code>. The reason is that the implementation optimizes this scenario, as the source is already sorted. In principle, it could do the same optimization to your original example, as <code>forEach</code> is explicitly performing the action in no specified order, hence, the sorting is unnecessary.</p>
<p>There are other optimizations imaginable, e.g. <code>sorted().findFirst()</code> could get converted to a “find the minimum” operation, without the need to copy the element into a new storage for sorting.</p>
<p>So the bottom line is, when relying on unspecified behavior, what may happen to work today, may break tomorrow, when new optimizations are added.</p> |
21,065,616 | Multiple "could not be resolved" problems using Eclipse with minGW | <p>I have recently installed (the latest builds of) 'Eclipse IDE for C/C++ Developers' and minGW (4.8.1) to help me to get back into C++ after a long time away.</p>
<p>I have added <code>-std=c++11</code> to <code>Other flags</code> at <code>C/C++ Build/Settings/Tool Settings/GCC C++ Compiler/Miscellaneous</code></p>
<p>I have a small program utilizing a number of C++11 features (e.g. using the <code>chrono</code> library, <code>.emplace_back</code>).</p>
<p>After Run I get multiple unresolved issues in the Problems window, as Pasted below).</p>
<p>Interestingly, the program does compile and run ok. </p>
<ol>
<li><p>With this, is there something I'm not setting up in Eclipse to resolve these issues?</p></li>
<li><p>Does anyone know if there still an issue with the <code>to_string()</code> function in minGW (4.8.1) e.g. the following does not compile: </p>
<pre><code>window.setTitle("Bullets on screen: " + to_string(bullets.size()) + " currentSlice: " + to_string(currentSlice) + " FT: " + to_string(ft) + " FPS: " + to_string(fps) );
</code></pre>
<p>It does compile using Visual Studio Express 2013 (though it has an issue with the accuracy of the <code>chrono</code> library, hence the switch to minGW).</p>
<p>Thanks.</p></li>
</ol>
<p>Eclipse 'Problem' window output:</p>
<pre><code>Description Resource Path Location Type
Symbol 'duration' could not be resolved chronotest.cpp /chronotest/src line 19 Semantic Error
Function 'now' could not be resolved Test2.cpp /Test2/src line 143 Semantic Error
Function 'duration_cast' could not be resolved Test2.cpp /Test2/src line 160 Semantic Error
Function 'now' could not be resolved Test2.cpp /Test2/src line 158 Semantic Error
Symbol 'chrono' could not be resolved Test2.cpp /Test2/src line 8 Semantic Error
Type 'std::centi' could not be resolved chronotest.cpp /chronotest/src line 20 Semantic Error
Type 'std::chrono::seconds' could not be resolved chronotest.cpp /chronotest/src line 24 Semantic Error
Type 'std::time_t' could not be resolved chronotest.cpp /chronotest/src line 48 Semantic Error
Symbol 'duration' could not be resolved chronotest.cpp /chronotest/src line 47 Semantic Error
Function 'now' could not be resolved chronotest.cpp /chronotest/src line 44 Semantic Error
Function 'now' could not be resolved chronotest.cpp /chronotest/src line 39 Semantic Error
Type 'std::chrono::system_clock' could not be resolved chronotest.cpp /chronotest/src line 38 Semantic Error
Function 'end' could not be resolved Test2.cpp /Test2/src line 214 Semantic Error
Symbol 'time_point' could not be resolved chronotest.cpp /chronotest/src line 38 Semantic Error
Function 'end' could not be resolved Test2.cpp /Test2/src line 212 Semantic Error
Type 'milli' could not be resolved Test2.cpp /Test2/src line 161 Semantic Error
Method 'count' could not be resolved Test2.cpp /Test2/src line 161 Semantic Error
Symbol 'duration_cast' could not be resolved Test2.cpp /Test2/src line 160 Semantic Error
Symbol 'duration' could not be resolved Test2.cpp /Test2/src line 161 Semantic Error
Method 'count' could not be resolved chronotest.cpp /chronotest/src line 51 Semantic Error
Symbol 'duration_cast' could not be resolved chronotest.cpp /chronotest/src line 30 Semantic Error
Method 'count' could not be resolved chronotest.cpp /chronotest/src line 30 Semantic Error
Function 'to_time_t' could not be resolved chronotest.cpp /chronotest/src line 48 Semantic Error
Method 'count' could not be resolved chronotest.cpp /chronotest/src line 32 Semantic Error
Function 'ctime' could not be resolved chronotest.cpp /chronotest/src line 50 Semantic Error
Method 'count' could not be resolved chronotest.cpp /chronotest/src line 33 Semantic Error
Symbol 'duration' could not be resolved chronotest.cpp /chronotest/src line 22 Semantic Error
Invalid arguments '
Candidates are:
__gnu_cxx::__normal_iterator<Bullet *,std::vector<Bullet,std::allocator<Bullet>>> erase(__gnu_cxx::__normal_iterator<Bullet *,std::vector<Bullet,std::allocator<Bullet>>>)
__gnu_cxx::__normal_iterator<Bullet *,std::vector<Bullet,std::allocator<Bullet>>> erase(__gnu_cxx::__normal_iterator<Bullet *,std::vector<Bullet,std::allocator<Bullet>>>, __gnu_cxx::__normal_iterator<Bullet *,std::vector<Bullet,std::allocator<Bullet>>>)
' Test2.cpp /Test2/src line 212 Semantic Error
Symbol 'ratio' could not be resolved chronotest.cpp /chronotest/src line 22 Semantic Error
Invalid arguments '
Candidates are:
#0 remove_if(#0, #0, #1)
' Test2.cpp /Test2/src line 212 Semantic Error
Symbol 'duration_cast' could not be resolved chronotest.cpp /chronotest/src line 28 Semantic Error
Method 'count' could not be resolved chronotest.cpp /chronotest/src line 28 Semantic Error
Method 'emplace_back' could not be resolved Test2.cpp /Test2/src line 191 Semantic Error
Symbol 'ratio' could not be resolved chronotest.cpp /chronotest/src line 19 Semantic Error
Symbol 'duration' could not be resolved chronotest.cpp /chronotest/src line 20 Semantic Error
Symbol 'duration' could not be resolved chronotest.cpp /chronotest/src line 21 Semantic Error
Function 'begin' could not be resolved Test2.cpp /Test2/src line 212 Semantic Error
Symbol 'ratio' could not be resolved chronotest.cpp /chronotest/src line 21 Semantic Error
</code></pre>
<hr>
<p>[Edit]: Apologies for not including error details for the remaining "to_string". The Eclipse 'Problem' window output has the following:</p>
<pre><code> Description Resource Path Location Type
'to_string' was not declared in this scope Test2.cpp /Test2/src line 170 C/C++ Problem
Function 'to_string' could not be resolved Test2.cpp /Test2/src line 170 Semantic Error
Function 'to_string' could not be resolved Test2.cpp /Test2/src line 170 Semantic Error
unused variable 'currentSlice' [-Wunused-variable] Test2.cpp /Test2/src line 125 C/C++ Problem
Function 'to_string' could not be resolved Test2.cpp /Test2/src line 170 Semantic Error
Invalid arguments '
Candidates are:
void setTitle(const sf::String &)
' Test2.cpp /Test2/src line 170 Semantic Error
Function 'to_string' could not be resolved Test2.cpp /Test2/src line 170 Semantic Error
</code></pre> | 21,065,897 | 3 | 1 | null | 2014-01-11 17:41:34.743 UTC | 6 | 2018-05-30 11:52:00.743 UTC | 2014-01-11 18:37:56.79 UTC | null | 2,521,883 | null | 2,521,883 | null | 1 | 20 | c++|eclipse|gcc|c++11|mingw32 | 71,150 | <p>Go to <code>Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers -> CDT GCC built-in compiler settings</code>, deactivate <code>Use global provider shared between projects</code> and add the command line argument <code>-std=c++11</code>.</p>
<p>The eclipse live code analysis does not share the same settings with the build compiler. You can also change the setting globally (not just for the project) in <code>Window -> Preferences -> C/C++ -> Build -> Settings -> CDT GCC Built-in Compiler Settings</code>.</p>
<p>Edit: You need to <code>#include <string></code> to use <code>std::to_string</code>.</p> |
54,598,322 | How to make Typescript infer the keys of an object but define type of its value? | <p>I want to define the type of an object but let typescript infer the keys and don't have as much overhead to make and maintain a UnionType of all keys.</p>
<p>Typing an object will allow all strings as keys:</p>
<pre><code>const elementsTyped: {
[key: string]: { nodes: number, symmetric?: boolean }
} = {
square: { nodes: 4, symmetric: true },
triangle: { nodes: 3 }
}
function isSymmetric(elementType: keyof typeof elementsTyped): boolean {
return elementsTyped[elementType].symmetric;
}
isSymmetric('asdf'); // works but shouldn't
</code></pre>
<p>Inferring the whole object will show an error and allows all kind of values:</p>
<pre><code>const elementsInferred = {
square: { nodes: 4, symmetric: true },
triangle: { nodes: 3 },
line: { nodes: 2, notSymmetric: false /* don't want that to be possible */ }
}
function isSymmetric(elementType: keyof typeof elementsInferred): boolean {
return elementsInferred[elementType].symmetric;
// Property 'symmetric' does not exist on type '{ nodes: number; }'.
}
</code></pre>
<p>The closest I got was this, but it don't want to maintain the set of keys like that:</p>
<pre><code>type ElementTypes = 'square' | 'triangle'; // don't want to maintain that :(
const elementsTyped: {
[key in ElementTypes]: { nodes: number, symmetric?: boolean }
} = {
square: { nodes: 4, symmetric: true },
triangle: { nodes: 3 },
lines: { nodes: 2, notSymmetric: false } // 'lines' does not exist in type ...
// if I add lines to the ElementTypes as expected => 'notSymmetric' does not exist in type { nodes: number, symmetric?: boolean }
}
function isSymmetric(elementType: keyof typeof elementsTyped): boolean {
return elementsTyped[elementType].symmetric;
}
isSymmetric('asdf'); // Error: Argument of type '"asdf"' is not assignable to parameter of type '"square" | "triangle"'.
</code></pre>
<p>Is there a better way to define the object without maintaining the set of keys?</p> | 54,598,743 | 1 | 1 | null | 2019-02-08 18:31:38.197 UTC | 17 | 2019-02-08 19:05:43.163 UTC | null | null | null | null | 7,557,340 | null | 1 | 52 | typescript | 13,617 | <p>So you want something that infers keys but restricts the value types and uses <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks" rel="noreferrer">excess property checking</a> to disallow extra properties. I think the easiest way to get that behavior is to introduce a helper function:</p>
<pre><code>// Let's give a name to this type
interface ElementType {
nodes: number,
symmetric?: boolean
}
// helper function which infers keys and restricts values to ElementType
const asElementTypes = <T>(et: { [K in keyof T]: ElementType }) => et;
</code></pre>
<p>This helper function <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#inference-from-mapped-types" rel="noreferrer">infers</a> the type <code>T</code> from the mapped type of <code>et</code>. Now you can use it like this:</p>
<pre><code>const elementsTyped = asElementTypes({
square: { nodes: 4, symmetric: true },
triangle: { nodes: 3 },
line: { nodes: 2, notSymmetric: false /* error where you want it */}
});
</code></pre>
<p>The type of the resulting <code>elementsTyped</code> will (once you fix the error) have inferred keys <code>square</code>, <code>triangle</code>, and <code>line</code>, with values <code>ElementType</code>. </p>
<p>Hope that works for you. Good luck!</p> |
35,620,318 | Allocate or Limit resource for pods in Kubernetes? | <p>The resource limit of Pod has been set as:</p>
<pre><code>resource
limit
cpu: 500m
memory: 5Gi
</code></pre>
<p>and there's <code>10G</code> mem left on the node.</p>
<p>I've created <code>5</code> pods in a short time successfully, and the node maybe still have some mem left, e.g. <code>8G</code>.</p>
<p>The mem usage is growing as the time goes on, and reach the limit (<code>5G x 5 = 25G > 10G</code>), then the node will be out of response.</p>
<p>In order to ensure the usability, is there a way to set the resource limit on the node? </p>
<h2>Update</h2>
<p>The core problem is that pod memory usage does not always equal to the limit, especially in the time when it just starts. So there can be unlimited pods created as soon as possible, then make all nodes full load. That's not good. There might be something to allocate resources rather than setting the limit.</p>
<h2>Update 2</h2>
<p>I've tested again for the limits and resources:</p>
<pre><code>resources:
limits:
cpu: 500m
memory: 5Gi
requests:
cpu: 500m
memory: 5Gi
</code></pre>
<p>The total mem is 15G and left 14G, but 3 pods are scheduled and running successfully:</p>
<pre><code>> free -mh
total used free shared buff/cache available
Mem: 15G 1.1G 8.3G 3.4M 6.2G 14G
Swap: 0B 0B 0B
> docker stats
CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
44eaa3e2d68c 0.63% 1.939 GB / 5.369 GB 36.11% 0 B / 0 B 47.84 MB / 0 B
87099000037c 0.58% 2.187 GB / 5.369 GB 40.74% 0 B / 0 B 48.01 MB / 0 B
d5954ab37642 0.58% 1.936 GB / 5.369 GB 36.07% 0 B / 0 B 47.81 MB / 0 B
</code></pre>
<p>It seems that the node will be crushed soon XD</p>
<h2>Update 3</h2>
<p>Now I change the resources limits, request <code>5G</code> and limit <code>8G</code>:</p>
<pre><code>resources:
limits:
cpu: 500m
memory: 5Gi
requests:
cpu: 500m
memory: 8Gi
</code></pre>
<p>The results are:
<a href="https://i.stack.imgur.com/rhpEB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rhpEB.jpg" alt="enter image description here"></a></p>
<p>According to the <a href="https://github.com/kubernetes/kubernetes/blob/8c60068b368f8ec1cd21fdf25d44c7b165aa9d27/plugin/pkg/scheduler/algorithm/predicates/predicates.go#L393" rel="nofollow noreferrer">k8s source code about the resource check</a>:</p>
<p><a href="https://i.stack.imgur.com/auyM2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/auyM2.jpg" alt="enter image description here"></a></p>
<p>The total memory is only <code>15G</code>, and all the pods needs <code>24G</code>, so all the pods may be killed. (my single one container will cost more than <code>16G</code> usually if not limited.)</p>
<p>It means that you'd better keep the <code>requests</code> <strong>exactly equals</strong> to the <code>limits</code> in order to avoid pod killed or node crush. As if the <code>requests</code> value is not specified, it will be <a href="http://kubernetes.io/v1.1/docs/user-guide/compute-resources.html" rel="nofollow noreferrer">set to the <code>limit</code> as default</a>, so what exactly <code>requests</code> used for? I think only <code>limits</code> is totally enough, or IMO, on the contrary of what K8s claimed, I rather like to <strong>set the resource request greater than the limit</strong>, in order to ensure the usability of nodes.</p>
<h2>Update 4</h2>
<p>Kubernetes <a href="https://github.com/kubernetes/kubernetes/blob/1ef28633870d66fba6883bf1d667dbcfd83f200b/plugin/pkg/scheduler/algorithm/predicates/predicates.go#L120" rel="nofollow noreferrer">1.1 schedule the pods mem requests</a> via the formula:</p>
<p><code>(capacity - memoryRequested) >= podRequest.memory</code></p>
<p>It seems that kubernetes is not caring about memory usage as <a href="https://stackoverflow.com/users/5289649/vishnu-kannan">Vishnu Kannan</a> said. So the node will be crushed if the mem used much by other apps.</p>
<p>Fortunately, from the commit <a href="https://github.com/kubernetes/kubernetes/commit/e64fe82245303f08f32b0fb9a2fa9efe4a08f91f" rel="nofollow noreferrer">e64fe822</a>, the formula has been changed as:</p>
<p><code>(allocatable - memoryRequested) >= podRequest.memory</code></p>
<p>waiting for the k8s v1.2!</p> | 35,634,337 | 2 | 0 | null | 2016-02-25 06:51:25.877 UTC | 9 | 2020-03-13 06:35:04.343 UTC | 2020-03-13 06:35:04.343 UTC | null | 8,123,139 | null | 5,658,049 | null | 1 | 12 | docker|kubernetes|cgroups | 7,414 | <p>Kubernetes resource specifications have two fields, <code>request</code> and <code>limit</code>.</p>
<p><code>limits</code> place a cap on how much of a resource a container can use. For memory, if a container goes above its limits, it will be OOM killed. For CPU, its usage may be throttled.</p>
<p><code>requests</code> are different in that they ensure the node that the pod is put on has at least that much capacity available for it. If you want to make sure that your pods will be able to grow to a particular size without the node running out of resources, specify a request of that size. This will limit how many pods you can schedule, though -- a 10G node will only be able to fit 2 pods with a 5G memory request.</p> |
18,814,806 | Can bower automatically write <script> tags into index.html? | <p>I'm using yeoman's backbone generator, and I ran this:</p>
<pre><code>bower install backbone.localStorage -S
</code></pre>
<p>And I manually had to insert this into index.html:</p>
<pre><code><script src="bower_components/backbone.localStorage/backbone.localStorage.js"></script>
</code></pre>
<p>Is there some way for bower to automatically insert <code><script></code> tags? I thought part of the benefit of bower was not having to figure out in which order to include your scripts?</p> | 21,320,207 | 4 | 0 | null | 2013-09-15 16:38:29.677 UTC | 18 | 2015-10-24 12:17:09.227 UTC | null | null | null | null | 685,125 | null | 1 | 62 | yeoman|bower | 37,016 | <p>Just run </p>
<pre><code>grunt bowerInstall
</code></pre>
<p>after bower install</p> |
8,886,367 | Running Chrome with extension in kiosk mode | <p>I really need to run Chrome in kiosk mode with an extension. If I start chrome with <code>--app-id=xxxx</code> it runs the app, but <code>--kiosk</code> is ignored. If I start it with <code>--kiosk</code> the app-id is ignored.</p>
<p>Is there any way to do both? Starting in full screen (F11 mode) is not going to work because of the bubble window at the top and the user can exit.</p> | 8,889,306 | 6 | 0 | null | 2012-01-16 21:16:12.843 UTC | 2 | 2017-06-08 19:30:56.877 UTC | 2012-01-17 13:05:09.967 UTC | null | 1,143,495 | null | 1,152,692 | null | 1 | 10 | google-chrome | 49,886 | <p>Go to options and for "Home Page" pick "Open this page" and enter the url for your web app and then add --kiosk to your command line.<br>
To get the url for your app I usually just open the app in a tab, right click and pick view source and then youll get something like view-source:chrome-extension://hiddpjhppcbepfekmomnlopbjjjhilhk/popup.html for its url, copy everything after view-source: and put that as your homepage.</p> |
55,497,072 | Execute async method on button click in blazor | <p>I created a "Razor Components" project. I am trying to execute an asynchronous method when pressing a button, but could not figure out the syntax yet.</p>
<p>This is my <strong>Index.razor</strong>:</p>
<pre><code>@page "/"
@inject GenericRepository<Person> PersonRepository
@foreach (var person in persons)
{
<button onclick="@(() => Delete(person.Id))">❌</button>
}
@functions
{
async void Delete(Guid personId)
{
await this.PersonRepository.Delete(personId);
}
}
</code></pre>
<p>When I click the button, nothing happens. I tried various return types (e.g. <code>Task</code>) and stuff, but cannot figure out how to make it work. Please let me know if I need to provide more information.</p>
<p>Every documentation / tutorial only just works with non-async void calls on button click.</p>
<p>Thanks in advance.</p> | 55,497,287 | 2 | 0 | null | 2019-04-03 14:03:30.44 UTC | 1 | 2021-11-08 11:03:24.26 UTC | 2021-11-08 11:03:24.26 UTC | null | 1,865,613 | null | 1,865,613 | null | 1 | 36 | c#|razor|blazor|blazor-server-side|razor-components | 41,469 | <p>You need to call the <code>Delete</code> method properly and make it return <code>Task</code> instead of <code>void</code>:</p>
<pre><code><button onclick="@(async () => await Delete(person.Id))">❌</button>
@functions {
// ...
async Task Delete(Guid personId)
{
await this.PersonRepository.Delete(personId);
}
}
</code></pre> |
448,204 | Creating a custom authentication with Acegi/Spring Security | <p>I'm having trouble discovering exactly what I need to implement in order to use a custom authentication method with my web application using Spring Security. I have a Grails application with the Spring Security plugin that currently uses the standard user/password authentication with a browser form. This is working correctly. </p>
<p>I need to implement a mechanism alongside of this that implements a type of <a href="http://en.wikipedia.org/wiki/Message_authentication_code" rel="noreferrer">MAC</a> authentication. If the HTTP request contains several parameters (e.g. a user identifier, timestamp, signature, etc.) I need to take those parameters, perform some hashing and signature/timestamp comparisons, and then authenticate the user.</p>
<p>I'm not 100% sure where to start with this. What Spring Security classes do I need to extend/implement? I have read the <a href="http://www.acegisecurity.org/guide/springsecurity.html" rel="noreferrer">Reference Documentation</a> and have an okay understanding of the concepts, but am not really sure if I need a Filter or Provider or Manager, or where/how exactly to create <a href="http://static.springframework.org/spring-security/site/apidocs/org/springframework/security/Authentication.html" rel="noreferrer">Authentication</a> objects. I've messed around trying to extend <a href="http://static.springframework.org/spring-security/site/apidocs/org/springframework/security/ui/AbstractProcessingFilter.html" rel="noreferrer">AbstractProcessingFilter</a> and/or implement <a href="http://static.springframework.org/spring-security/site/apidocs/org/springframework/security/providers/AuthenticationProvider.html" rel="noreferrer">AuthenticationProvider</a>, but I just get caught up understanding how I make them all play nicely.</p> | 737,382 | 3 | 0 | null | 2009-01-15 19:51:47.527 UTC | 10 | 2013-03-21 13:57:38.783 UTC | 2010-08-17 22:16:17.73 UTC | null | 29,995 | robhruska | 29,995 | null | 1 | 21 | spring-security | 25,060 | <ol>
<li><p>Implement a custom <code>AuthenticationProvider</code> which gets all your authentication information from the <code>Authentication</code>: <code>getCredentials()</code>, <code>getDetails()</code>, and <code>getPrincipal()</code>.</p>
<p>Tie it into your Spring Security authentication mechanism using the following configuration snippet:</p></li>
</ol>
<pre class="lang-xml prettyprint-override"><code><bean id="myAuthenticationProvider" class="com.example.MyAuthenticationProvider">
<security:custom-authentication-provider />
</bean>
</code></pre>
<ol start="2">
<li><p>This step is optional, if you can find a suitable one from standard implementations. If not, implement a class extending the <code>Authentication</code> interface on which you can put your authentication parameters: </p>
<pre><code>(e.g. a user identifier, timestamp, signature, etc.)
</code></pre></li>
<li><p>Extend a custom <code>SpringSecurityFilter</code> which ties the above two classes together. For example, the Filter might get the <code>AuthenticationManager</code> and call <code>authenticate()</code> using your implementation of <code>Authentication</code> as input.</p>
<p>You can extend <a href="https://fisheye.springsource.org/browse/~tag=3.0.5.RELEASE/spring-security/web/src/main/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.java?r=6ac858814407cee65e3c30779cb271ecaf3abd19" rel="nofollow noreferrer">AbstractAuthenticationProcessingFilter</a> as a start.</p>
<p>You can reference <a href="https://fisheye.springsource.org/browse/~tag=3.0.5.RELEASE/spring-security/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java?hb=true" rel="nofollow noreferrer">UsernamePasswordAuthenticationFilter</a> which extends <code>AbstractAuthenticationProcessingFilter</code>. <code>UsernamePasswordAuthenticationFilter</code> implements the standard Username/Password Authentication.</p></li>
<li><p>Configure your Spring Security to add or replace the standard <code>AUTHENTICATION_PROCESSING_FILTER</code>. For Spring Security Filter orders, see <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#filter-stack" rel="nofollow noreferrer">http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#filter-stack</a></p>
<p>Here is a configuration snippet for how to replace it with your implementation:</p></li>
</ol>
<pre class="lang-xml prettyprint-override"><code><beans:bean id="myFilter" class="com.example.MyAuthenticationFilter">
<custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>
</beans:bean>
</code></pre> |
203,469 | How to use enums in Oracle? | <p>How do you use enums in Oracle using SQL only? (No PSQL)</p>
<p>In MySQL you can do:</p>
<pre><code>CREATE TABLE sizes (
name ENUM('small', 'medium', 'large')
);
</code></pre>
<p>What would be a similar way to do this in Oracle?</p> | 203,547 | 3 | 0 | null | 2008-10-15 01:48:37.78 UTC | 16 | 2018-08-15 13:34:35.92 UTC | 2008-10-15 02:43:58.073 UTC | Robert Gould | 15,124 | Robert Gould | 15,124 | null | 1 | 47 | database|oracle|enums | 80,241 | <p>Reading a bit about the <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="noreferrer">MySQL enum</a>, I'm guessing the closest equivalent would be a simple check constraint</p>
<pre><code>CREATE TABLE sizes (
name VARCHAR2(10) CHECK( name IN ('small','medium','large') )
);
</code></pre>
<p>but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible</p>
<pre><code>CREATE TABLE valid_names (
name_id NUMBER PRIMARY KEY,
name_str VARCHAR2(10)
);
INSERT INTO valid_sizes VALUES( 1, 'small' );
INSERT INTO valid_sizes VALUES( 2, 'medium' );
INSERT INTO valid_sizes VALUES( 3, 'large' );
CREATE TABLE sizes (
name_id NUMBER REFERENCES valid_names( name_id )
);
CREATE VIEW vw_sizes
AS
SELECT a.name_id name, <<other columns from the sizes table>>
FROM valid_sizes a,
sizes b
WHERE a.name_id = b.name_id
</code></pre>
<p>As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.</p>
<p>Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.</p> |
375,154 | How do I get the time a file was last modified in Python? | <p>Assuming the file exists (using <code>os.path.exists(filename)</code> to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.</p> | 375,168 | 3 | 0 | null | 2008-12-17 16:33:41.07 UTC | 10 | 2018-02-24 16:17:13.153 UTC | 2008-12-17 17:11:11.15 UTC | Bill the Lizard | 1,288 | Bill the Lizard | 1,288 | null | 1 | 66 | python|file|time | 79,023 | <p><a href="http://docs.python.org/library/os.html#os.stat" rel="noreferrer">os.stat()</a></p>
<pre><code>import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))
</code></pre>
<p>Linux does not record the creation time of a file (<a href="https://unix.stackexchange.com/q/24441/61642">for most fileystems</a>).</p> |
6,883,010 | If I'm already using Modernizr, will I then even need HTML5 Shiv? | <p>1) If I'm already using Modernizr, will I then even need HTML5 Shiv to enable HTML5 tag support for IE?</p>
<p>2) Is HTML5 Shiv only for IE, or for all browser who don't have native HTML 5 support? Like older versions of Firefox, Safari, Chrome, etc?</p> | 6,883,023 | 1 | 0 | null | 2011-07-30 12:09:42.083 UTC | 10 | 2012-08-14 06:50:54.237 UTC | 2012-08-14 06:50:54.237 UTC | null | 1,352,036 | null | 84,201 | null | 1 | 46 | javascript|html|css|cross-browser|modernizr | 18,354 | <blockquote>
<p>1) If I'm already using Modernizer then even will I need HTML5 Shiv to
enable HTML5 tag supports for IE.</p>
</blockquote>
<p>You don't need to separately include <a href="http://code.google.com/p/html5shiv/" rel="noreferrer">html5shiv</a>, because Modernizr includes it:</p>
<blockquote>
<p>As of Modernizr 1.5, this script is identical to what is used in the
popular html5shim/html5shiv library.</p>
</blockquote>
<p><a href="http://www.modernizr.com/docs/#html5inie" rel="noreferrer">http://www.modernizr.com/docs/#html5inie</a></p>
<hr>
<blockquote>
<p>2) and is HTML5 Shiv only for IE or for all browser who don't have
native HTML 5 support. like older version of Firefox, Safari, Chrome
etc.</p>
</blockquote>
<p>It's only for Internet Explorer.</p>
<p>Older versions of other browsers don't need it: <a href="http://caniuse.com/html5semantic" rel="noreferrer">http://caniuse.com/html5semantic</a></p>
<p>And the recommended snippet to include it is:</p>
<pre><code><!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</code></pre>
<p>Which will only ever run for IE less than 9.</p> |
6,427,128 | Why is Clojure named Clojure | <p>Why is the name of the language, "Clojure"? </p>
<p>I googled a bit, asked in #clojure. So far, no luck.</p> | 6,427,317 | 1 | 6 | null | 2011-06-21 14:39:25.857 UTC | 2 | 2012-11-03 00:44:52.41 UTC | 2011-10-02 23:38:49.407 UTC | null | 168,868 | null | 31,830 | null | 1 | 56 | clojure|jvm | 3,794 | <p>Rich Hickey's (He's the designer of Clojure) comment on that is the 1st reference link on wiki:</p>
<blockquote>
<p><em>Did you pick the name based on starting with the word "closure" and
replacing the "s" with "j" for Java?
It seems pretty likely, but it would
be nice to have that confirmed.</em> </p>
<p>The name was chosen to be unique. I
wanted to involve c (c#), l (lisp)
and j (java). Once I came up with
Clojure, given the pun on closure, the
available domains and vast emptiness
of the googlespace, it was an easy
decision.</p>
</blockquote>
<p><a href="http://groups.google.com/group/clojure/msg/766b75baa7987850" rel="noreferrer">http://groups.google.com/group/clojure/msg/766b75baa7987850</a></p> |
20,515,679 | RequireJS: To Bundle or Not to Bundle | <p>I'm using RequireJS for my web application. I'm using EmberJS for the application framework. I've come to a point where, I think, I should start bundling my application into a single js file. That is where I get a little confused:</p>
<p>If I finally bundle everything into one file for deployment, then my whole application loads in one shot, instead of on demand. Isn't bundling contradictory to AMD in general and RequireJS in particular?</p>
<p>What further confuses me, is what I found on the <a href="http://requirejs.org/docs/start.html#optimize" rel="nofollow noreferrer">RequireJS</a> website:</p>
<blockquote>
<p>Once you are finished doing development and want to deploy your code for your end users, you can use the optimizer to combine the JavaScript files together and minify it. In the example above, it can combine main.js and helper/util.js into one file and minify the result.</p>
</blockquote>
<p>I found this <a href="https://stackoverflow.com/questions/12232848/when-to-use-requirejs-and-when-to-use-bundled-javascript">similar thread</a> but it doesn't answer my question.</p> | 20,518,314 | 2 | 0 | null | 2013-12-11 09:45:05.297 UTC | 9 | 2014-02-02 20:42:27.327 UTC | 2017-05-23 10:31:12.597 UTC | null | -1 | null | 1,046,810 | null | 1 | 12 | requirejs | 2,696 | <blockquote>
<p>If I finally bundle everything into one file for deployment, then my whole application loads in one shot, instead of on demand. Isn't bundling contradictory to AMD in general and RequireJS in particular?</p>
</blockquote>
<p>It is not contradictory. Loading modules on demand is only <em>one</em> benefit of RequireJS. A greater benefit in my book is that modularization helps to use a divide-and-conquer approach. We can look at it in this way: even though all the functions and classes we put in a single file do not benefit from loading on demand, we still write multiple functions and multiple classes because it helps break down the problem in a structured way.</p>
<p>However, the multiplicity of modules we create in development do not necessarily make sense when running the application in a browser. The greatest cost of on-demand loading is sending multiple HTTP requests over the wire. Let's say your application has 10 modules and you send 10 requests to load it because you load these modules individually. Your total cost is going to be the cost you have to pay to load the bytes from the 10 files (let's call it Pc for payload cost), <em>plus</em> an overhead cost for each HTTP request (let's call it Oc, for overhead cost). The overhead has to do with the data and computations that have to occur to initiate and close these requests. They are not insignificant. So you are paying Pc + 10*Oc. If you send everything in one chunk you pay Pc + 1*Oc. You've saved 9*Oc. In fact the savings are probably greater because (since compression is often used at both ends to reduce the size of the data transmitted) compression is going to provide greater benefits if the entire data is compressed together than if it is compressed as 10 chunks. (Note: the above analysis omits details that are not useful to cover.)</p>
<p>Someone might object: "But you are comparing loading <em>all</em> the modules in separately versus loading <em>all</em> the modules in one chunk. If we load on demand then we won't load <em>all</em> the modules." As a matter of fact, most applications have a core of modules that will always be loaded, no matter what. These are the modules without which the application won't work <em>at all</em>. For some small applications this means all modules, so it make sense to bundle all of them together. For bigger applications, this means that a core set of modules will be used every single time the application runs, but a small set will be used only on occasion. In the latter case, the optimization should create <strong>multiple bundles</strong>. I have an <a href="https://github.com/mangalam-research/wed">application</a> like this. It is an editor with modes for various editing needs. A good 90% of the modules belong to the core. They are going to be loaded and used <em>anyway</em> so it makes sense to bundle them. The code for the modes themselves is not always going to be used but all the files for a given mode are going to be needed if the mode is loaded at all so each mode should be its own bundle. So in this case a model with one core bundle and a series of mode bundles makes sense to a) optimize the deployed application but b) keep some of the benefits of loading on demand. That's the beauty of RequireJS: it does not require to do one or the other exclusively.</p> |
20,454,115 | Where does Windows store the settings for Scheduled Tasks console? | <p>I would like to know where Windows stores information for Scheduled Tasks. I would like to be able to find the reference for the name, schedule, or command to run associated with a given task. This may not be practical or possible, but I would also like a means to edit the scheduled tasks and their attributes outside the Schedule Tasks console. I've assumed that the data would be in the Registry somewhere, since I doubt it would be stored in a normal file, but I'm uncertain where I should be looking.</p> | 20,454,183 | 3 | 0 | null | 2013-12-08 13:44:28.78 UTC | 8 | 2018-03-30 23:10:03.433 UTC | 2015-05-19 19:44:30.577 UTC | null | 868,354 | null | 3,078,605 | null | 1 | 27 | windows|scheduled-tasks | 99,211 | <p>Windows stores scheduled tasks as XML files, AND in the registry.</p>
<p>You can find them in a few places:</p>
<p><strong>Filesystem:</strong></p>
<blockquote>
<p>%systemroot%\System32\Tasks<br>
%systemroot%\Tasks</p>
</blockquote>
<p><strong>Registry:</strong></p>
<blockquote>
<p>HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks<br>
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree</p>
</blockquote>
<p>Note: You can't edit the XML files directly in \Tasks for security reasons. See here for more information: <a href="https://serverfault.com/questions/440496/ok-to-edit-tasks-xml-file-in-c-windows-system32-tasks">https://serverfault.com/questions/440496/ok-to-edit-tasks-xml-file-in-c-windows-system32-tasks</a> </p>
<p>To work with importing the XML files without going through the scheduled task UI you can look at these:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx" rel="noreferrer">Schtasks.exe</a><br>
<a href="http://technet.microsoft.com/en-us/library/jj649816.aspx" rel="noreferrer">Powershell Scheduled Task Cmdlets</a></p> |
20,425,724 | Python+OpenCV: cv2.imwrite | <p>I'm trying to detect a face and write down area with the face in a separate file.
How can I do it? I think that i must use "faces" (you can see this var in code). But how?</p>
<pre><code>from ffnet import mlgraph, ffnet, tmlgraph, imlgraph
import pylab
import sys
import cv,cv2
import numpy
cascade = cv.Load('C:\opencv\data\haarcascades\haarcascade_frontalface_alt.xml')
def detect(image):
bitmap = cv.fromarray(image)
faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
if faces:
for (x,y,w,h),n in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
return image
if __name__ == "__main__":
cam = cv2.VideoCapture(0)
while 1:
_,frame =cam.read()
frame = numpy.asarray(detect(frame))
cv2.imshow("features", frame)
if cv2.waitKey(1) == 0x1b: # ESC
print 'ESC pressed. Exiting ...'
break
</code></pre> | 20,426,395 | 3 | 0 | null | 2013-12-06 13:59:03.343 UTC | 18 | 2019-08-26 20:01:57.023 UTC | 2014-03-08 12:43:46.24 UTC | null | 2,255,305 | null | 3,074,695 | null | 1 | 29 | python|opencv|python-2.7|numpy | 164,293 | <p>This following code should extract face in images and save faces on disk</p>
<pre><code>def detect(image):
image_faces = []
bitmap = cv.fromarray(image)
faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
if faces:
for (x,y,w,h),n in faces:
image_faces.append(image[y:(y+h), x:(x+w)])
#cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
return image_faces
if __name__ == "__main__":
cam = cv2.VideoCapture(0)
while 1:
_,frame =cam.read()
image_faces = []
image_faces = detect(frame)
for i, face in enumerate(image_faces):
cv2.imwrite("face-" + str(i) + ".jpg", face)
#cv2.imshow("features", frame)
if cv2.waitKey(1) == 0x1b: # ESC
print 'ESC pressed. Exiting ...'
break
</code></pre> |
42,744,280 | GCC throws error upon compilation: error: unknown type name ‘FILE’ | <p>I am making a function which is just writes <code>"hello"</code> to a file. I have put it in a different file and included its header in the program. But gcc is giving an error namely:</p>
<blockquote>
<p><code>error: unknown type name ‘FILE’.</code></p>
</blockquote>
<p>The code is given below</p>
<p><code>app.c</code>:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "write_hello.h"
int main() {
FILE* fp;
fp = fopen("new_file.txt", "w");
write_hello(fp);
return 0;
}
</code></pre>
<p><code>write_hello.h</code>:</p>
<pre><code>void write_hello(FILE*);
</code></pre>
<p><code>write_hello.c</code>:</p>
<pre><code>void write_hello(FILE* fp) {
fprintf(fp, "hello");
printf("Done\n");
}
</code></pre>
<p>when compiling by gcc the following occurs:</p>
<pre><code>harsh@harsh-Inspiron-3558:~/c/bank_management/include/test$ sudo gcc app.c
write_hello.c -o app
write_hello.c:3:18: error: unknown type name ‘FILE’
void write_hello(FILE* fp) {
</code></pre> | 42,744,341 | 1 | 1 | null | 2017-03-12 05:56:43.603 UTC | 3 | 2021-07-22 19:10:12.26 UTC | 2021-07-22 19:10:12.26 UTC | null | 4,298,200 | null | 4,982,988 | null | 1 | 9 | c|gcc | 46,424 | <p>FILE is defined in stdio.h and you need to include it in each file that uses it. So write_hello.h and write_hello.c should both include it, and write_hello.c should also include write_hello.h (since it implements the function defined in write_hello.h).</p>
<p>Also note that it is standard practice for every header file is to define a macro of the same name (IN CAPS), and enclose the entire header between #ifndef, #endif. In C, this prevents a header from getting #included twice. This is known as the "internal include guard" (with thanks to Story Teller for pointing that out). All system headers such as stdio.h include an internal include guard. All user defined headers should also include an internal include guard as shown in the example below.</p>
<p><strong>write_hello.h</strong></p>
<pre><code>#ifndef WRITE_HELLO_H
#define WRITE_HELLO_H
#include <stdio.h>
void write_hello(FILE*);
#endif
</code></pre>
<p><strong>write_hello.c</strong></p>
<pre><code>#include <stdio.h>
#include "write_hello.h"
void write_hello(FILE* fp){
fprintf(fp,"hello");
printf("Done\n");
}
</code></pre>
<p>Note that when you include system files, the header name is placed within <code><></code>'s. This helps the compiler identify that these headers are system headers which are stored in a central place based on your development environment.</p>
<p>Your own custom headers are placed in quotes <code>""</code> are typically found in your current directory, but may be placed elsewhere by including the path, or adding the directory to your list of directories that the compiler searches. This is configurable within your project if you are using an IDE like NetBeans, or using the -I compiler option is building it directly or through a makefile.</p> |
42,843,441 | Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7 | <p>I installed the Kotlin plugin into my app (v. v1.1.1-release-Studio2.2-1) and then selected "Configure Kotlin in Project" I selected compiler and runtime version of 1.0.7. Kotlin updated my Gradle files. Now when I try to build in I get:</p>
<blockquote>
<p>Error: A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7.
Required by:</p>
<p>MyApplication:app:unspecified</p>
</blockquote>
<p>I'm not sure what I'm missing here.</p> | 53,358,817 | 18 | 2 | null | 2017-03-16 19:42:36.99 UTC | 11 | 2022-01-03 15:03:27.143 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 517,733 | null | 1 | 145 | android|kotlin|android-gradle-plugin | 210,971 | <p>replace</p>
<pre><code>implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
^
|
JRE = Java Runtime Environment
</code></pre>
<p>with</p>
<pre><code>implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
^
|
JDK = Java Development Kit
</code></pre>
<p>Since the version with jre is absolute , just replace and sync the project</p>
<p>Official Documentation <a href="http://kotlinlang.org/docs/reference/whatsnew12.html#kotlin-standard-library-artifacts-and-split-packages" rel="noreferrer">here</a> Thanks for the link @ <a href="https://stackoverflow.com/users/164966/r0manarmy">ROMANARMY</a></p> |
13,399,981 | .h264 sample file | <p>I'm currently using files <a href="http://support.apple.com/kb/HT1425" rel="nofollow">here</a>, but I get some errors while testing my program. I just want to see if it fails only with this one or with all other .h264 files. So, are there any other sources where I can download (standard) .h264 sample files for test ? </p>
<p>Thanks.</p> | 13,415,851 | 2 | 0 | null | 2012-11-15 14:50:37.013 UTC | 2 | 2016-09-27 02:05:56.247 UTC | 2015-03-12 15:14:23.283 UTC | null | 619,860 | null | 619,860 | null | 1 | 1 | video-streaming|h.264|video-encoding | 41,340 | <p>Option 1: make your own with x264. These are not standard sample files, but you can control which parts of H.264 they use, for example different profile/level/etc, make them I-frame-only, make them have only a particular macroblock type, etc. Also you can make them tiny, e.g. one or a few frames long.</p>
<p>Option 2: perhaps the JM software comes with some sample files? <a href="http://iphome.hhi.de/suehring/tml/" rel="nofollow">http://iphome.hhi.de/suehring/tml/</a></p>
<p>Option 3: if you want to test a large number of files, download some random trailers etc in mp4 formar and demux them to get raw .h264 (for example with ffmpeg -vcodec copy)</p> |
69,554,485 | ESLint - Error: Must use import to load ES Module | <p>I am currently setting up a boilerplate with React, TypeScript, styled components, <a href="https://en.wikipedia.org/wiki/Webpack" rel="nofollow noreferrer">Webpack</a>, etc., and I am getting an error when trying to run <a href="https://en.wikipedia.org/wiki/ESLint" rel="nofollow noreferrer">ESLint</a>:</p>
<blockquote>
<p>Error: Must use import to load ES Module</p>
</blockquote>
<p>Here is a more verbose version of the error:</p>
<pre class="lang-none prettyprint-override"><code>/Users/ben/Desktop/development projects/react-boilerplate-styled-context/src/api/api.ts
0:0 error Parsing error: Must use import to load ES Module: /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js
require() of ES modules is not supported.
require() of /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/babel-eslint/lib/require-from-eslint.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename definition.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/package.json
</code></pre>
<p>The error occurs in every single one of my .js and .ts/ .tsx files where I only use <code>import</code> or the file doesn't even have an import at all. I understand what the error is saying, but I don't have any idea why it is being thrown when in fact I only use imports or even no imports at all in some files.</p>
<p>Here is my <em>package.json</em> file where I trigger the linter from using <code>npm run lint:eslint:quiet</code>:</p>
<pre><code>{
"name": "my-react-boilerplate",
"version": "1.0.0",
"description": "",
"main": "index.tsx",
"directories": {
"test": "test"
},
"engines": {
"node": ">=14.0.0"
},
"type": "module",
"scripts": {
"build": "webpack --config webpack.prod.js",
"dev": "webpack serve --config webpack.dev.js",
"lint": "npm run typecheck && npm run lint:css && npm run lint:eslint:quiet",
"lint:css": "stylelint './src/**/*.{js,ts,tsx}'",
"lint:eslint:quiet": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern --quiet",
"lint:eslint": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern",
"lint:eslint:fix": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern --quiet --fix",
"test": "cross-env NODE_ENV=test jest --coverage",
"test:watch": "cross-env NODE_ENV=test jest --watchAll",
"typecheck": "tsc --noEmit",
"precommit": "npm run lint"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"npm run lint:eslint:fix",
"git add --force"
],
"*.{md,json}": [
"prettier --write",
"git add --force"
]
},
"husky": {
"hooks": {
"pre-commit": "npx lint-staged && npm run typecheck"
}
},
"resolutions": {
"styled-components": "^5"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.5.4",
"@babel/plugin-proposal-class-properties": "^7.5.0",
"@babel/preset-env": "^7.5.4",
"@babel/preset-react": "^7.0.0",
"@types/history": "^4.7.6",
"@types/react": "^17.0.29",
"@types/react-dom": "^17.0.9",
"@types/react-router": "^5.1.17",
"@types/react-router-dom": "^5.1.5",
"@types/styled-components": "^5.1.15",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"babel-cli": "^6.26.0",
"babel-eslint": "^10.0.2",
"babel-loader": "^8.0.0-beta.6",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"dotenv-webpack": "^7.0.3",
"error-overlay-webpack-plugin": "^1.0.0",
"eslint": "^8.0.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-prettier": "^8.3.0",
"eslint-config-with-prettier": "^6.0.0",
"eslint-plugin-compat": "^3.3.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-react-hooks": "^4.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"husky": "^7.0.2",
"prettier": "^2.4.1",
"raw-loader": "^4.0.2",
"style-loader": "^3.3.0",
"stylelint": "^13.13.1",
"stylelint-config-recommended": "^5.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.10.0",
"ts-loader": "^9.2.6",
"tslint": "^6.1.3",
"typescript": "^4.4.4",
"url-loader": "^4.1.1",
"webpack": "^5.58.2",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^4.3.1",
"webpack-merge": "^5.3.0"
},
"dependencies": {
"history": "^4.10.0",
"process": "^0.11.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"styled-components": "^5.2.1"
}
}
</code></pre>
<p>Here is my .eslintrc file:</p>
<pre><code>{
"extends": ["airbnb", "prettier"],
"parser": "babel-eslint",
"plugins": ["prettier", "@typescript-eslint"],
"parserOptions": {
"ecmaVersion": 8,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"impliedStrict": true,
"classes": true
}
},
"env": {
"browser": true,
"node": true,
"jest": true
},
"rules": {
"arrow-body-style": ["error", "as-needed"],
"class-methods-use-this": 0,
"react/jsx-filename-extension": 0,
"global-require": 0,
"react/destructuring-assignment": 0,
"import/named": 2,
"linebreak-style": 0,
"import/no-dynamic-require": 0,
"import/no-named-as-default": 0,
"import/no-unresolved": 2,
"import/prefer-default-export": 0,
"semi": [2, "always"],
"max-len": [
"error",
{
"code": 80,
"ignoreUrls": true,
"ignoreComments": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true
}
],
"new-cap": [
2,
{
"capIsNew": false,
"newIsCap": true
}
],
"no-param-reassign": 0,
"no-shadow": 0,
"no-tabs": 2,
"no-underscore-dangle": 0,
"react/forbid-prop-types": [
"error",
{
"forbid": ["any"]
}
],
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
"react/jsx-no-bind": [
"error",
{
"ignoreRefs": true,
"allowArrowFunctions": true,
"allowBind": false
}
],
"react/no-unknown-property": [
2,
{
"ignore": ["itemscope", "itemtype", "itemprop"]
}
]
}
}
</code></pre>
<p>And I’m not sure if it is relevant, but here is also my <em>tsconfig.eslint.json</em> file:</p>
<pre><code>{
"extends": "./tsconfig.json",
"include": ["./src/**/*.ts", "./src/**/*.tsx", "./src/**/*.js"],
"exclude": ["node_modules/**", "build/**", "coverage/**"]
}
</code></pre>
<p>How can I fix this?</p>
<p>Googling the error does not present any useful forums or raised bugs. Most of them just state not to use <code>require</code> in your files which I am not.</p> | 69,557,309 | 7 | 0 | null | 2021-10-13 11:14:45.797 UTC | 20 | 2022-09-22 13:42:13.977 UTC | 2022-08-21 22:38:48.797 UTC | null | 63,550 | null | 3,955,685 | null | 1 | 152 | javascript|node.js|reactjs|eslint | 86,746 | <p>I think the problem is that you are trying to use the deprecated <a href="https://github.com/babel/babel-eslint" rel="noreferrer">babel-eslint parser</a>, last updated a year ago, which looks like it doesn't support ES6 modules. Updating to the <a href="https://github.com/babel/babel/tree/main/eslint/babel-eslint-parser" rel="noreferrer">latest parser</a> seems to work, at least for simple linting.</p>
<p>So, do this:</p>
<ul>
<li>In package.json, update the line <code>"babel-eslint": "^10.0.2",</code> to <code>"@babel/eslint-parser": "^7.5.4",</code>. This works with the code above but it may be better to use the latest version, which at the time of writing is 7.16.3.</li>
<li>Run <code>npm i</code> from a terminal/command prompt in the folder</li>
<li>In .eslintrc, update the parser line <code>"parser": "babel-eslint",</code> to <code>"parser": "@babel/eslint-parser",</code></li>
<li>In .eslintrc, add <code>"requireConfigFile": false,</code> to the parserOptions section (underneath <code>"ecmaVersion": 8,</code>) (I needed this or babel was looking for config files I don't have)</li>
<li>Run the command to lint a file</li>
</ul>
<p>Then, for me with just your two configuration files, the error goes away and I get appropriate linting errors.</p> |
41,449,617 | Why is sum so much faster than inject(:+)? | <p>So I was running some benchmarks in Ruby 2.4.0 and realized that</p>
<pre><code>(1...1000000000000000000000000000000).sum
</code></pre>
<p>calculates immediately whereas</p>
<pre><code>(1...1000000000000000000000000000000).inject(:+)
</code></pre>
<p>takes so long that I just aborted the operation. I was under the impression that <code>Range#sum</code> was an alias for <code>Range#inject(:+)</code> but it seems like that is not true. So how does <code>sum</code> work, and why is it so much faster than <code>inject(:+)</code>?</p>
<p><strong>N.B.</strong> The documentation for <code>Enumerable#sum</code> (which is implemented by <code>Range</code>) does not say anything about lazy evaluation or anything along those lines. </p> | 41,449,844 | 1 | 0 | null | 2017-01-03 17:59:33.62 UTC | 25 | 2017-01-05 23:51:26.887 UTC | 2017-01-04 04:04:01.713 UTC | null | 5,021,321 | null | 5,021,321 | null | 1 | 132 | ruby | 9,109 | <h1>Short answer</h1>
<p>For an integer range :</p>
<ul>
<li><code>Enumerable#sum</code> returns <code>(range.max-range.min+1)*(range.max+range.min)/2</code></li>
<li><code>Enumerable#inject(:+)</code> iterates over every element.</li>
</ul>
<hr>
<h1>Theory</h1>
<p>The sum of integers between 1 and <code>n</code> is called a <a href="https://en.wikipedia.org/wiki/Triangular_number">triangular number</a>, and is equal to <code>n*(n+1)/2</code>.</p>
<p>The sum of integers between <code>n</code> and <code>m</code> is the triangular number of <code>m</code> minus the triangular number of <code>n-1</code>, which is equal to <code>m*(m+1)/2-n*(n-1)/2</code>, and can be written <code>(m-n+1)*(m+n)/2</code>.</p>
<h1>Enumerable#sum in Ruby 2.4</h1>
<p>This property in used in <a href="http://ruby-doc.org/core-2.4.0/Enumerable.html#method-i-sum"><code>Enumerable#sum</code></a> for integer ranges :</p>
<pre><code>if (RTEST(rb_range_values(obj, &beg, &end, &excl))) {
if (!memo.block_given && !memo.float_value &&
(FIXNUM_P(beg) || RB_TYPE_P(beg, T_BIGNUM)) &&
(FIXNUM_P(end) || RB_TYPE_P(end, T_BIGNUM))) {
return int_range_sum(beg, end, excl, memo.v);
}
}
</code></pre>
<p><code>int_range_sum</code> looks like this :</p>
<pre><code>VALUE a;
a = rb_int_plus(rb_int_minus(end, beg), LONG2FIX(1));
a = rb_int_mul(a, rb_int_plus(end, beg));
a = rb_int_idiv(a, LONG2FIX(2));
return rb_int_plus(init, a);
</code></pre>
<p>which is equivalent to:</p>
<pre><code>(range.max-range.min+1)*(range.max+range.min)/2
</code></pre>
<p>the aforementioned equality!</p>
<h1>Complexity</h1>
<p>Thanks a lot to @k_g and @Hynek-Pichi-Vychodil for this part!</p>
<h3>sum</h3>
<p><code>(1...1000000000000000000000000000000).sum</code>
requires three additions, a multiplication, a substraction and a division.</p>
<p>It's a constant number of operations, but multiplication is O((log n)²), so <code>Enumerable#sum</code> is O((log n)²) for an integer range.</p>
<h3>inject</h3>
<p><code>(1...1000000000000000000000000000000).inject(:+)</code></p>
<p>requires 999999999999999999999999999998 additions!</p>
<p>Addition is O(log n), so <code>Enumerable#inject</code> is O(n log n).</p>
<p>With <code>1E30</code> as input, <code>inject</code> with never return. The sun will explode long before!</p>
<h1>Test</h1>
<p>It's easy to check if Ruby Integers are being added :</p>
<pre><code>module AdditionInspector
def +(b)
puts "Calculating #{self}+#{b}"
super
end
end
class Integer
prepend AdditionInspector
end
puts (1..5).sum
#=> 15
puts (1..5).inject(:+)
# Calculating 1+2
# Calculating 3+3
# Calculating 6+4
# Calculating 10+5
#=> 15
</code></pre>
<p>Indeed, from <code>enum.c</code> comments :</p>
<blockquote>
<p><code>Enumerable#sum</code> method may not respect method redefinition of <code>"+"</code>
methods such as <code>Integer#+</code>.</p>
</blockquote> |
5,935,638 | Autocomplete Textbox Example in python + Google app engine | <p>For my google app engine application, I need to include a autocompleter Textbox which will show the name starting with the textbox value.And the name will retrieve from the google app engine datastore.</p>
<p>Any good tutorial or sample code please.</p>
<p><strong>Update: Please Answer for this</strong></p>
<p>I created a sample HTML code : <a href="http://dl.dropbox.com/u/7384181/autocomplete/autocomplete.html" rel="nofollow">dl.dropbox.com/u/7384181/autocomplete/autocomplete.html</a> .
In this html page i have creating the textbox dinamically.So currently i assign the autocomplete in the first textbox(txtProduct1) only. How do i assign the autocomplete in rest all the textbox which is going to create dynamically ? </p> | 5,936,103 | 3 | 1 | null | 2011-05-09 10:34:02.03 UTC | 9 | 2011-10-25 21:02:45.96 UTC | 2011-10-25 21:02:45.96 UTC | null | 59,470 | null | 783,657 | null | 1 | 6 | python|ajax|google-app-engine|autocomplete | 5,304 | <p>You can have a look at the jquery auto complete <a href="http://docs.jquery.com/Plugins/autocomplete" rel="noreferrer">here</a></p>
<p><strong>HTML :</strong></p>
<pre><code>$("#search_users").autocomplete(/search/search_manager);
</code></pre>
<p><strong>python-controller</strong>:</p>
<p>jquery autocomplete plugin by default uses variable q</p>
<pre><code>class search_user(webapp.RequestHandler):
q = (self.request.GET['q']).lower()
results=models.user.all().fetch(100)
for records in result:
print records+"|"+records+"\n"
application = webapp.WSGIApplication([
(r'/user_auth/search_manager',search_user)]
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
simple:
</code></pre>
<p>Apply the autocomplete to a class
$</p>
<pre><code>(".search_users").autocomplete(/search/search_manager);
</code></pre> |
6,003,648 | Preload a website | <p>I'm looking to preload a website. I only want a loading bar once on the site. When its loading I want every page to pre load. How would I do this?</p>
<p><a href="http://frankadvertisingus.com/fa_website/home.html" rel="nofollow">http://frankadvertisingus.com/fa_website/home.html</a></p> | 6,003,778 | 4 | 3 | null | 2011-05-14 17:38:31.09 UTC | null | 2016-08-27 19:11:14.69 UTC | 2011-05-14 17:55:08.733 UTC | null | 743,171 | null | 743,171 | null | 1 | 0 | javascript|jquery|html|web|dreamweaver | 44,325 | <p>A Right Click for Source code can be helpful</p>
<p>Here is the source where you can find the jQuery for it.
<a href="https://web.archive.org/web/20110511045013/http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/" rel="nofollow noreferrer">http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/</a></p> |
5,851,213 | Crawling with an authenticated session in Scrapy | <p>In my <a href="https://stackoverflow.com/q/5850755/445210">previous question</a>, I wasn't very specific over my problem (scraping with an authenticated session with Scrapy), in the hopes of being able to deduce the solution from a more general answer. I should probably rather have used the word <code>crawling</code>.</p>
<p>So, here is my code so far:</p>
<pre><code>class MySpider(CrawlSpider):
name = 'myspider'
allowed_domains = ['domain.com']
start_urls = ['http://www.domain.com/login/']
rules = (
Rule(SgmlLinkExtractor(allow=r'-\w+.html$'), callback='parse_item', follow=True),
)
def parse(self, response):
hxs = HtmlXPathSelector(response)
if not "Hi Herman" in response.body:
return self.login(response)
else:
return self.parse_item(response)
def login(self, response):
return [FormRequest.from_response(response,
formdata={'name': 'herman', 'password': 'password'},
callback=self.parse)]
def parse_item(self, response):
i['url'] = response.url
# ... do more things
return i
</code></pre>
<p>As you can see, the first page I visit is the login page. If I'm not authenticated yet (in the <code>parse</code> function), I call my custom <code>login</code> function, which posts to the login form. Then, if I <em>am</em> authenticated, I want to continue crawling.</p>
<p>The problem is that the <code>parse</code> function I tried to override in order to log in, now no longer makes the necessary calls to scrape any further pages (I'm assuming). And I'm not sure how to go about saving the Items that I create. </p>
<p>Anyone done something like this before? (Authenticate, then crawl, using a <code>CrawlSpider</code>) Any help would be appreciated.</p> | 5,857,202 | 4 | 4 | null | 2011-05-01 20:34:32.713 UTC | 42 | 2018-03-19 09:21:36.877 UTC | 2017-05-23 12:25:21.27 UTC | null | -1 | null | 445,210 | null | 1 | 33 | python|scrapy | 38,529 | <p><strong>Do not override the <code>parse</code> function in a <code>CrawlSpider</code>:</strong></p>
<p>When you are using a <code>CrawlSpider</code>, you shouldn't override the <code>parse</code> function. There's a warning in the <code>CrawlSpider</code> documentation here: <a href="http://doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule" rel="noreferrer">http://doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule</a></p>
<p>This is because with a <code>CrawlSpider</code>, <code>parse</code> (the default callback of any request) sends the response to be processed by the <code>Rule</code>s.</p>
<hr>
<p><strong>Logging in before crawling:</strong></p>
<p>In order to have some kind of initialisation before a spider starts crawling, you can use an <code>InitSpider</code> (which inherits from a <code>CrawlSpider</code>), and override the <code>init_request</code> function. This function will be called when the spider is initialising, and before it starts crawling.</p>
<p>In order for the Spider to begin crawling, you need to call <code>self.initialized</code>.</p>
<p>You can read the code that's responsible for this <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/spiders/init.py" rel="noreferrer"><strong>here</strong></a> (it has helpful docstrings).</p>
<hr>
<p><strong>An example:</strong></p>
<pre><code>from scrapy.contrib.spiders.init import InitSpider
from scrapy.http import Request, FormRequest
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import Rule
class MySpider(InitSpider):
name = 'myspider'
allowed_domains = ['example.com']
login_page = 'http://www.example.com/login'
start_urls = ['http://www.example.com/useful_page/',
'http://www.example.com/another_useful_page/']
rules = (
Rule(SgmlLinkExtractor(allow=r'-\w+.html$'),
callback='parse_item', follow=True),
)
def init_request(self):
"""This function is called before crawling starts."""
return Request(url=self.login_page, callback=self.login)
def login(self, response):
"""Generate a login request."""
return FormRequest.from_response(response,
formdata={'name': 'herman', 'password': 'password'},
callback=self.check_login_response)
def check_login_response(self, response):
"""Check the response returned by a login request to see if we are
successfully logged in.
"""
if "Hi Herman" in response.body:
self.log("Successfully logged in. Let's start crawling!")
# Now the crawling can begin..
return self.initialized()
else:
self.log("Bad times :(")
# Something went wrong, we couldn't log in, so nothing happens.
def parse_item(self, response):
# Scrape data from page
</code></pre>
<hr>
<p><strong>Saving items:</strong></p>
<p>Items your Spider returns are passed along to the Pipeline which is responsible for doing whatever you want done with the data. I recommend you read the documentation: <a href="http://doc.scrapy.org/en/0.14/topics/item-pipeline.html" rel="noreferrer">http://doc.scrapy.org/en/0.14/topics/item-pipeline.html</a></p>
<p>If you have any problems/questions in regards to <code>Item</code>s, don't hesitate to pop open a new question and I'll do my best to help.</p> |
34,575,732 | Setting space between some items in stack view | <p>In Interface Builder, I use a horizontal UIStackView and want to place the items as this :</p>
<pre><code> xx xx xx
</code></pre>
<p>every x symbolize an item. Item1 and item2 should be stuck one to the other, but item2 and item3 should be spaced and so on. That means I do not want constant spacing between all the items.</p>
<p>How can I do so ?<br>
(maybe an equivalent of flexible space of toolbars) </p>
<p>Thanks !</p> | 34,576,034 | 7 | 1 | null | 2016-01-03 10:57:07.2 UTC | 5 | 2021-05-26 09:19:57 UTC | 2016-01-03 11:14:04.923 UTC | null | 5,658,452 | null | 5,658,452 | null | 1 | 60 | ios|xcode | 54,894 | <p>Inside your horizontal stack view have three more horizontal stack views so that you can have control over spacing and distribution for each item. See screenshot below:</p>
<p><a href="https://i.stack.imgur.com/EpEhj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EpEhj.png" alt="enter image description here"></a></p> |
45,874,742 | Android Color Notification Icon | <p>I'm working on an app where I create a notification for the user. I want the icon to appear as white when it's in the status bar, but colored blue when it's being displayed in the drop down notification menu. Here's an example of the same thing being done by the Google Store app.</p>
<p>White notification in status bar:</p>
<p><a href="https://i.stack.imgur.com/fcIS1.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/fcIS1.jpg" alt="enter image description here"></a></p>
<p>Colored notification in drop down menu:</p>
<p><a href="https://i.stack.imgur.com/tYmdz.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/tYmdz.jpg" alt="enter image description here"></a></p>
<p>How can I replicate this? What properties do I have to set?</p>
<p><strong>Edit:</strong>
Here's my current code - I made the image all white with a transparent background, so it looks fine in the status bar, but in the notification drop, the image is still the same white color:</p>
<pre><code>private NotificationCompat.Builder getNotificationBuilder() {
return new NotificationCompat.Builder(mainActivity)
.setDeleteIntent(deletedPendingIntent)
.setContentIntent(startChatPendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.skylight_notification)
.setColor(ContextCompat.getColor(mainActivity, R.color.colorPrimary))
.setContentTitle(mainActivity.getString(R.string.notification_title))
.setContentText(mainActivity.getString(R.string.notification_prompt));
}
</code></pre> | 45,883,564 | 10 | 2 | null | 2017-08-25 05:07:24.26 UTC | 14 | 2021-07-08 07:19:40.833 UTC | 2017-08-25 05:20:36.657 UTC | null | 4,394,594 | null | 4,394,594 | null | 1 | 67 | java|android|colors|push-notification|android-notifications | 80,629 | <p>I found the answer to my question here: <a href="https://stackoverflow.com/a/44950197/4394594">https://stackoverflow.com/a/44950197/4394594</a></p>
<p>I don't know entirely what the problem was, but by putting the huge png that I was using for the icon into the this tool <a href="https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=image&source.space.trim=1&source.space.pad=0&name=ic_skylight_notification" rel="noreferrer">https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=image&source.space.trim=1&source.space.pad=0&name=ic_skylight_notification</a>
and by placing the generated icons it gave into my mipmap folder, I was able to get the <code>setColor(...)</code> property to work correctly.</p> |
28,994,316 | Can you add a custom message to AssertJ assertThat? | <p>We have a test suite that primarily uses JUnit assertions with Hamcrest matchers. One of our team started experimenting with <a href="http://joel-costigliola.github.io/assertj/">AssertJ</a> and impressed people with its syntax, flexibility and declarative-ness. There is one feature that JUnit provides that I can't find an equivalent for in AssertJ: adding a custom assert failure message.</p>
<p>We're often comparing objects that are not made for human readability and will have random-seeming Ids or UUIDs and it's impossible to tell what they're supposed to be by the data they contain. This is an unavoidable situation for our codebase, sadly, as part of the purpose it fulfills is mapping data between other services without necessarily understanding what it is.</p>
<p>In JUnit, the <a href="http://junit.org/apidocs/org/junit/Assert.html#assertThat(java.lang.String,%20T,%20org.hamcrest.Matcher)"><code>assertThat</code></a> method provides a version with a <code>String reason</code> parameter before the <code>Matcher<T></code> param. This makes it trivial to add a short debug string shedding some light on the problem, like what the comparison should mean to a human.</p>
<p>AssertJ, on the other hand, provides a jillion different <a href="http://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/Assertions.html#assertThat(org.assertj.core.api.AssertProvider)">genericized <code>static assertThat</code></a> methods which return some form of <a href="http://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/Assert.html">interface Assert</a> or one of its many implementing classes. This interface does not provide a standard way of setting a custom message to be included with failures.</p>
<p>Is there any way to get this functionality from the AssertJ API or one of its extensions without having to <a href="http://joel-costigliola.github.io/assertj/assertj-core-custom-assertions.html">create a custom assert class for every assert type</a> we want to add messages to?</p> | 28,994,810 | 4 | 1 | null | 2015-03-11 18:14:26.397 UTC | 13 | 2022-09-06 09:26:38.81 UTC | null | null | null | null | 1,146,608 | null | 1 | 130 | java|unit-testing|junit|assertj | 50,298 | <p>And in classic fashion, I found what I was looking for moments after posting the question. Hopefully this will make it easier for the next person to find without first having to know what it's called. The magic method is the deceptively short-named <a href="https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractAssert.html#as(java.lang.String,%20java.lang.Object...)" rel="noreferrer"><code>as</code></a>, which is part of another interface that <code>AbstractAssert</code> implements: <a href="https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/Descriptable.html" rel="noreferrer">Descriptable</a>, not the base Assert interface.</p>
<blockquote>
<p><code>public S as(String description, Object... args)</code></p>
<p>Sets the description of this object supporting <code>String.format(String, Object...)</code> syntax.<br>
Example :</p>
<pre><code>try {
// set a bad age to Mr Frodo which is really 33 years old.
frodo.setAge(50);
// you can specify a test description with as() method or describedAs(), it supports String format args
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);
} catch (AssertionError e) {
assertThat(e).hasMessage("[check Frodo's age] expected:<[33]> but was:<[50]>");
}
</code></pre>
</blockquote>
<p>Where that quoted string in the catch block <code>hasMessage</code> is what appears in your unit test output log if the assertion fails.</p>
<hr>
<p>I found this by noticing the <code>failWithMessage</code> helper in the <a href="https://joel-costigliola.github.io/assertj/assertj-core-custom-assertions.html" rel="noreferrer">custom assert page</a> linked in the question. The <a href="https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractAssert.html#failWithMessage(java.lang.String,%20java.lang.Object...)" rel="noreferrer">JavaDoc</a> for that method points out that it is protected, so it can't be used by callers to set a custom message. It does however mention the <code>as</code> helper: </p>
<blockquote>
<p>Moreover, this method honors any description set with <code>as(String, Object...)</code> or overridden error message defined by the user with <code>overridingErrorMessage(String, Object...)</code>.</p>
</blockquote>
<p>... and the <a href="https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractAssert.html#overridingErrorMessage(java.lang.String,%20java.lang.Object...)" rel="noreferrer">overridingErrorMessage</a> helper, which completely replaces the standard AssertJ <code>expected: ... but was:...</code> message with the new string provided.</p>
<p>The AssertJ homepage doesn't mention either helper until the features highlights page, which shows examples of the <code>as</code> helper in the <a href="https://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#soft-assertions" rel="noreferrer">Soft Assertions</a> section, but doesn't directly describe what it does.</p> |
29,172,558 | Why doesn't incrementing Nullable<int> throw an exception? | <p>Could you please explain, why does Console.WriteLine write empty line (<code>Console.WriteLine(null)</code> give me compilation error) and why there isn't NullReferenceException (even <code>a+=1</code> shouldn't raise it)?</p>
<pre><code>int? a = null;
a++; // Why there is not NullReferenceException?
Console.WriteLine(a); // Empty line
</code></pre> | 29,172,637 | 3 | 2 | null | 2015-03-20 17:33:26.06 UTC | 5 | 2015-04-14 13:15:19.73 UTC | 2015-03-20 23:06:23.463 UTC | null | 1,350,209 | null | 2,524,304 | null | 1 | 99 | c#|.net|nullable | 6,510 | <p>You're observing the effects of a <em>lifted operator</em>.</p>
<p>From section 7.3.7 of the C# 5 specification:</p>
<blockquote>
<p>Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:</p>
<ul>
<li>For the unary operators <code>+ ++ - -- ! ~</code>
a lifted form of an operator exists if the operand and result types are both non-nullable value types. The lifted form is constructed by adding a single <code>?</code> modifier to the operand and result types. The lifted operator produces a null value if the operand is null. Otherwise, the lifted operator unwraps the operand, applies the underlying operator, and wraps the result.</li>
</ul>
</blockquote>
<p>So basically, <code>a++</code> in this case is an expression with a result of <code>null</code> (as an <code>int?</code>) and the variable is left untouched.</p>
<p>When you call</p>
<pre><code>Console.WriteLine(a);
</code></pre>
<p>that's being boxed into <code>object</code>, which converts it to a null reference, which is printed as an empty line.</p> |
32,344,232 | Unable to Install Any Package in Visual Studio 2015 | <p>I've tried every package I could possibly find and none of them will install in my project. I've installed every update listed in the Extensions and Updates list that were available. When I attempt to install SendGrid for example, this is the result (as is the result with all other packages): </p>
<pre><code>Attempting to gather dependencies information for package 'Sendgrid.6.1.0' with respect to project 'UI\MyApplication.MVC', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'Sendgrid.6.1.0' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Sendgrid.6.1.0'
Resolved actions to install package 'Sendgrid.6.1.0'
For adding package 'SendGrid.SmtpApi.1.3.1' to project 'MyApplication.MVC' that targets 'net452'.
For adding package 'SendGrid.SmtpApi.1.3.1' to project 'MyApplication.MVC' that targets 'net452'.
Adding package 'SendGrid.SmtpApi.1.3.1' to folder 'C:\Users\Keith\Source\Workspaces\MyApplication\MyApplication.MVC\packages'
Install failed. Rolling back...
</code></pre>
<p>I can't be the only one on the planet having issue with Visual Studio 2015 and the new and "improved" NuGet Package Manager. </p>
<p><strong>UPDATE:</strong><br>
Well, must be something odd in my solution because I created a new project from the VS2015 template (web) and the packages install just fine. When I find out the issue, I'll post the resolution in the event others run into the same problem. </p>
<p><strong>UPDATE 2:</strong><br>
Ok, it's not our solution. We created a new solution from scratch again (this has wasted a lot of our development time might I add), added a couple of packages (Identity, EF, SendGrid) and after checking the solution in to VSO, another developer performs a fresh creation of the branch and build errors occur. When I go to the NuGet packages for an individual project, it acts as though none of the packages I have added are available. Anyone else experiencing this?</p> | 36,461,793 | 19 | 1 | null | 2015-09-02 03:32:52.917 UTC | 23 | 2020-02-24 09:31:19.473 UTC | 2015-09-03 02:15:12.527 UTC | null | 176,806 | null | 176,806 | null | 1 | 187 | package|nuget|visual-studio-2015 | 121,734 | <p>tl;dr - Delete this:</p>
<pre><code>%AppData%/Nuget/Nuget.config
</code></pre>
<p><strong>Warning: If you had custom NuGet sources, this will remove them, and you'll have to re-add them.</strong></p>
<hr>
<p>Longer version:</p>
<p>You might have corrupted your NuGet config. Oh no :(</p>
<p>Nuget.config is a file used to keep track of all of the places that NuGet pulls from, as well as configuring other things.
More likely than not, this xml file got broken somehow.</p>
<ul>
<li>Go to this path: <code>C:\Users\{{username}}\AppData\Roaming\</code></li>
<li>Delete <code>Nuget.config</code></li>
<li>Restart VS for good measure</li>
</ul>
<hr>
<p>For reference: in the good days of 2017, your file should look something like this</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageRestore>
<add key="enabled" value="True" />
<add key="automatic" value="True" />
</packageRestore>
<activePackageSource>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</activePackageSource>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
<!-- Others -->
</packageSources>
<packageSourceCredentials>
<!-- secret stuff -->
</packageSourceCredentials>
</configuration>
</code></pre> |
5,789,879 | Does a replacement for Gallery widget with View recycling exist? | <p>The default Gallery widget on Android does not recycle views - everytime the view for a new position is called the widget always calls the <code>getView</code> method of the adapter with <code>convertView</code> set to null.</p>
<p>As you scroll backwards and forwards this ends up in lots of views being created, which the recycler component that the Gallery stores them in does not seem to recycle them quickly enough leading to an OOM situation.</p>
<p>You can test this easily with a few large-ish images as your gallery items, but just a TextView will cause it in the end. Put a log statement with a counter in the <code>getView</code> method of your adapter also to see how many new views are created.</p>
<p>Does a third-party widget which behaves like a Gallery but that also implements view recycling exist?</p> | 5,882,944 | 5 | 2 | null | 2011-04-26 11:52:29.257 UTC | 12 | 2014-01-13 23:25:29.563 UTC | 2011-08-18 10:34:03.427 UTC | null | 114,066 | null | 290,028 | null | 1 | 12 | android|view|gallery|out-of-memory|recycle | 9,736 | <p>My solution was, in the end, going with @CommonsWare's suggestion to modify the Gallery source code. This is also required copying the following files:</p>
<ul>
<li><code>AdapterView</code></li>
<li><code>AbsSpinner</code></li>
</ul>
<p>but these are pretty simple.</p>
<p>After that I modified code to do the following:</p>
<blockquote>
<p><code>RecycleBin</code> (<code>AbsSpinner</code>)<br></p>
<ul>
<li>Place objects in the recycler one after another, rather than according
to position</li>
<li>Retrieve objects from the bottom of the recycler, regardless of the
position requested</li>
<li>The existing implementation assumed that each different position in the adapter
resulted in a unique view. The changes above are only good if your Gallery contains
only one type of item, if not you'll need to add some sort of key based on item type
and the amount of that type required</li>
</ul>
<p><code>Gallery</code></p>
<ul>
<li>Used reflection (ugh) to modify the private <code>mGroupFlags</code> variable of <code>ViewGroup</code> to allow child re-ordering - I also set a boolean value indicating whether the field access succeeded which I test before using the component.</li>
<li>Removed all calls to <code>mRecycler.clear()</code></li>
<li>The number of
items the gallery has to display
changes as it scrolls and the existing
implementation would clear the
recycler when (a) setSelection was
called (b) a motion scroll occurred</li>
</ul>
</blockquote>
<p>With these modifications my counter in my <code>newView</code> method in my adapter reached... 7.</p>
<p><a href="http://pastebin.com/FWyYTt4D">Here is the code</a> (Placed in the public domain 2013/08/07 under <a href="http://en.wikipedia.org/wiki/WTFPL">http://en.wikipedia.org/wiki/WTFPL</a>)</p> |
6,259,745 | Volatile variable in Java | <p>So I am reading this book titled <em>Java Concurrency in Practice</em> and I am stuck on this one explanation which I cannot seem to comprehend without an example. This is the quote:</p>
<blockquote>
<p>When thread <code>A</code> writes to a volatile
variable and subsequently thread <code>B</code>
reads that same variable, the values
of all variables that were visible to
<code>A</code> prior to writing to the volatile
variable become visible to <code>B</code> after
reading the volatile variable.</p>
</blockquote>
<p>Can someone give me a counterexample of why "the values of ALL variables that were visible to <code>A</code> prior to writing to the volatile variable become visible to <code>B</code> AFTER reading the volatile variable"?</p>
<p>I am confused why all other non-volatile variables do not become visible to <code>B</code> before reading the volatile variable?</p> | 6,259,761 | 5 | 3 | null | 2011-06-07 01:17:31.79 UTC | 16 | 2015-12-17 11:23:27.097 UTC | 2015-12-17 11:23:27.097 UTC | null | 2,093,236 | null | 364,253 | null | 1 | 23 | java|multithreading|concurrency|volatile | 15,208 | <p>Thread B may have a CPU-local cache of those variables. A read of a volatile variable ensures that any intermediate cache flush from a previous write to the volatile is observed.</p>
<p>For an example, read the following link, which concludes with "Fixing Double-Checked Locking using Volatile":</p>
<p><a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html">http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</a></p> |
6,020,450 | Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM | <p>Is it possible to create user-defined exceptions and be able to change the SQLERRM?</p>
<p>For example:</p>
<pre><code>DECLARE
ex_custom EXCEPTION;
BEGIN
RAISE ex_custom;
EXCEPTION
WHEN ex_custom THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
</code></pre>
<p>The output is "User-Defined Exception". Is it possible to change that message?</p>
<p>EDIT: Here is some more detail.</p>
<p>I hope this one illustrates what I'm trying to do better.</p>
<pre><code>DECLARE
l_table_status VARCHAR2(8);
l_index_status VARCHAR2(8);
l_table_name VARCHAR2(30) := 'TEST';
l_index_name VARCHAR2(30) := 'IDX_TEST';
ex_no_metadata EXCEPTION;
BEGIN
BEGIN
SELECT STATUS
INTO l_table_status
FROM USER_TABLES
WHERE TABLE_NAME = l_table_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- raise exception here with message saying
-- "Table metadata does not exist."
RAISE ex_no_metadata;
END;
BEGIN
SELECT STATUS
INTO l_index_status
FROM USER_INDEXES
WHERE INDEX_NAME = l_index_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- raise exception here with message saying
-- "Index metadata does not exist."
RAISE ex_no_metadata;
END;
EXCEPTION
WHEN ex_no_metadata THEN
DBMS_OUTPUT.PUT_LINE('Exception will be handled by handle_no_metadata_exception(SQLERRM) procedure here.');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
</code></pre>
<p>In reality, there are dozens of those sub-blocks. I'm wondering if there's a way to have a single user-defined exception for each of those sub-blocks to raise, but have it give a different message, instead of creating a separate user-defined exception for each sub-block.</p>
<p>In .NET, it would be sort of like having a custom exception like this:</p>
<pre><code> public class ColorException : Exception
{
public ColorException(string message)
: base(message)
{
}
}
</code></pre>
<p>And then, a method would have something like this:</p>
<pre><code> if (isRed)
{
throw new ColorException("Red is not allowed!");
}
if (isBlack)
{
throw new ColorException("Black is not allowed!");
}
if (isBlue)
{
throw new ColorException("Blue is not allowed!");
}
</code></pre> | 6,020,523 | 5 | 0 | null | 2011-05-16 16:32:55.703 UTC | 37 | 2018-12-24 10:23:44.55 UTC | 2015-06-02 11:11:55.713 UTC | null | 2,296,199 | null | 467,055 | null | 1 | 86 | oracle|exception|plsql|custom-exceptions | 335,997 | <p>Yes. You just have to use the <code>RAISE_APPLICATION_ERROR</code> function. If you also want to name your exception, you'll need to use the <code>EXCEPTION_INIT</code> pragma in order to associate the error number to the named exception. Something like</p>
<pre><code>SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
</code></pre> |
6,228,092 | How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS? | <p>The Security services API doesn't appear to allow me to compute a hash directly. There are plenty of public domain and liberally licensed versions available, but I'd rather use a system library implementation if possible.</p>
<p>The data is accessible via NSData, or plain pointers.</p>
<p>The cryptographic strength of the hash is important to me. SHA-256 is the minimum acceptable hash size.</p> | 6,228,385 | 6 | 0 | null | 2011-06-03 14:02:52.91 UTC | 36 | 2018-07-17 20:44:20.797 UTC | null | null | null | null | 233,201 | null | 1 | 59 | objective-c|ios|security|hash|sha256 | 33,868 | <p>This is what I'm using for SHA1:</p>
<pre><code>#import <CommonCrypto/CommonDigest.h>
+ (NSData *)sha1:(NSData *)data {
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
if ( CC_SHA1([data bytes], [data length], hash) ) {
NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH];
return sha1;
}
return nil;
}
</code></pre>
<p>Replace <code>CC_SHA1</code> with <code>CC_SHA256</code> (or whichever you need), as well as <code>CC_SHA1_DIGEST_LENGTH</code> with <code>CC_SHA256_DIGEST_LENGTH</code>.</p> |
6,091,427 | MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777 | <p>Any ideas? </p>
<pre><code>SELECT * INTO OUTFILE '/home/myacnt/docs/mysqlCSVtest.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '*'
LINES TERMINATED BY '\n'
FROM tbl_property
WHERE managerGroupID = {$managerGroupID}
</code></pre>
<p>Error:</p>
<pre><code>Access denied for user 'asdfsdf'@'localhost' (using password: YES)
</code></pre> | 6,091,447 | 6 | 2 | null | 2011-05-22 23:07:51.18 UTC | 24 | 2020-05-10 14:45:20.38 UTC | 2011-05-22 23:22:17.837 UTC | null | 135,152 | null | 646,456 | null | 1 | 86 | mysql|mysql-error-1045|into-outfile | 185,439 | <p>Try executing this SQL command:</p>
<pre><code>> grant all privileges
on YOUR_DATABASE.*
to 'asdfsdf'@'localhost'
identified by 'your_password';
> flush privileges;
</code></pre>
<p>It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.</p>
<p>Also, make sure you have granted <code>FILE</code> to user <code>'asdfsdf'@'localhost'</code>.</p>
<pre><code>> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';
</code></pre> |
6,236,251 | Android: get facebook friends list | <p>I am using the <a href="https://github.com/facebook/facebook-android-sdk/" rel="nofollow">Facebook SDK</a> to post messages on walls.</p>
<p>Now I need to fetch the Facebook friends list. Can anybody help me with this?</p>
<p>-- Edit --</p>
<pre><code>try {
Facebook mFacebook = new Facebook(Constants.FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mFacebook.request("me/friends", bundle);
} catch(Exception e){
Log.e(Constants.LOGTAG, " " + CLASSTAG + " Exception = "+e.getMessage());
}
</code></pre>
<p>When I execute my <code>activity</code>, I'm not seeing anything, but in <code>LogCat</code> there is a debug message like: </p>
<pre><code>06-04 17:43:13.863: DEBUG/Facebook-Util(409): GET URL: https://graph.facebook.com/me/friends?format=json&fields=birthday
</code></pre>
<p>And when I tried to access this url directly from the browser, I'm getting the following error response:</p>
<pre><code>{
error: {
type: "OAuthException"
message: "An active access token must be used to query information about the current user."
}
}
</code></pre> | 6,236,755 | 8 | 2 | null | 2011-06-04 10:42:01.87 UTC | 7 | 2015-10-16 09:05:36.4 UTC | 2014-04-11 06:37:04.913 UTC | null | 2,463,160 | null | 540,638 | null | 1 | 13 | android|facebook | 42,510 | <p>You are about half way there. You've sent the request, but you haven't defined anything to receive the response with your results. You can extend <code>BaseRequestListener</code> class and implement its <code>onComplete</code> method to do that. Something like this: </p>
<pre><code>public class FriendListRequestListener extends BaseRequestListener {
public void onComplete(final String response) {
_error = null;
try {
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Do stuff here with your friends array,
// which is an array of JSONObjects.
}
});
} catch (JSONException e) {
_error = "JSON Error in response";
} catch (FacebookError e) {
_error = "Facebook Error: " + e.getMessage();
}
if (_error != null)
{
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error occurred: " +
_error, Toast.LENGTH_LONG).show();
}
});
}
}
}
</code></pre>
<p>Then in your request you can specify the request listener to use for receiving the response from the request, like this: </p>
<pre><code>mFacebook.request("me/friends", bundle, new FriendListRequestListener());
</code></pre> |
49,741,379 | DialogFragment Class Deprecated in Android P | <p>The Android Documentation gives the following warning.</p>
<blockquote>
<p>This class was deprecated in API level P.
Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle.</p>
</blockquote>
<p>Does this simply mean that the only change for me as a developer is to import <code>android.support.v4.app.DialogFragment</code> instead of the old <code>android.app.DialogFragment</code>?</p> | 49,742,389 | 1 | 1 | null | 2018-04-09 20:40:45.53 UTC | 3 | 2018-12-14 11:07:57.94 UTC | 2018-05-07 10:30:07.177 UTC | null | 9,298,629 | null | 8,700,524 | null | 1 | 32 | android|android-fragments|android-alertdialog|android-9.0-pie | 20,695 | <p>Google is encouraging all developers to shift from the ordinary DialogFragment to the support version of the same class, you can still use the deprecated version of course but if Google recommends the support version, why wouldn't you?</p>
<p>Simply change your import statement from <code>android.app.DialogFragment</code> to <code>android.support.v4.app.DialogFragment</code>.</p>
<p>Also, consider changing all the imports if you are using the deprecated version of normal fragments.</p>
<p><strong>UPDATE</strong></p>
<p>If you are using the brand new AndroidX library instead of the old support library change it to <code>androidx.fragment.app.DialogFragment</code> but pay attention about how you are using the DialogFragment in your code because you have to migrate also to the new <code>androidx.fragment.app.FragmentActivity</code>.</p> |
25,372,911 | python/pip error on osx | <p>I've recently purchased a new hard drive and installed a clean copy of OS X Mavericks. I installed python using homebrew and i need to create a python virtual environment. But when ever i try to run any command using pip, I get this error. I haven't been able to find a solution online for this problem. Any reference would be appreciated. Here is the error I'm getting. </p>
<pre><code>ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 356, in load_entry_point
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 2439, in load_entry_point
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 2155, in load
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/util.py", line 18, in <module>
from pip._vendor.distlib import version
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/version.py", line 14, in <module>
from .compat import string_types
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
</code></pre>
<p>If you need any extra information from me let me know, this is my first time posting a question here. Thanks.</p> | 25,373,020 | 4 | 1 | null | 2014-08-18 22:17:15.087 UTC | 14 | 2019-11-27 18:41:04.587 UTC | null | null | null | null | 3,954,316 | null | 1 | 24 | python|macos | 24,738 | <p>Ok I found out <a href="https://github.com/Homebrew/legacy-homebrew/issues/22816#issuecomment-39017095" rel="noreferrer">online</a> that these errors are related to openssl. But i already had openssl installed. A little more research and I tried the following and it solved the issue for me. Here's my solution in case you get the same error.</p>
<pre><code>brew install openssl
brew link openssl --force
brew uninstall python
brew install python --with-brewed-openssl
</code></pre>
<p>Hope that helps.</p> |
24,566,692 | Filezilla FTP Server Fails to Retrieve Directory Listing | <p>I'm running Filezilla Server 0.9.45 beta to manage my server remotely.
After setting it up, I tested connecting to it using the IP <code>127.0.0.1</code>, and it worked successfully. However, to connect to the server remotely, I port forwarded to port 21, and tried to connect using my computer's IP.</p>
<pre><code>Status: Connecting to [My IP]:21...
Status: Connection established, waiting for welcome message...
Response: 220 Powered By FileZilla Server version 0.9.45 beta
Command: USER hussain khalil
Response: 331 Password required for user
Command: PASS *********
Response: 230 Logged on
Status: Connected
Status: Retrieving directory listing...
Command: CWD /
Response: 250 CWD successful. "/" is current directory.
Command: PWD
Response: 257 "/" is current directory.
Command: TYPE I
Response: 200 Type set to I
Command: PORT 192,168,0,13,205,63
Response: 200 Port command successful
Command: MLSD
Response: 150 Opening data channel for directory listing of "/"
Response: 425 Can't open data connection for transfer of "/"
Error: Failed to retrieve directory listing
</code></pre>
<p>This continues to work locally, but not when connecting remotely... How can I fix this?</p> | 24,570,363 | 22 | 1 | null | 2014-07-04 04:25:35 UTC | 12 | 2021-11-13 07:21:13.513 UTC | null | null | null | null | 3,571,248 | null | 1 | 101 | ftp|filezilla | 352,874 | <p>When you send the port command to your server, you are asking the server to connect to you (on the remote network). If the remote network also has a NAT router, and you have not port-forwarded the port you are sending with your PORT command, the server will not be able reach you.</p>
<p>The most common solution would be to send the PASV command to the server instead of the PORT command. The PASV command will ask the server to create a listening socket and accept a connection from the remote machine to establish the data connection.</p>
<p>For the PASV command to work, you will also need to port-forward a range of ports for the passive data connections. The passive connection ports (which need to be forwarded) should be listed in the FileZilla documentation.</p> |
27,712,472 | Choosing between SimHash and MinHash for a production system | <p>I'm familiar with the LSH (Locality Sensitive Hashing) techniques of SimHash and MinHash. SimHash uses cosine similarity over real-valued data. MinHash calculates resemblance similarity over binary vectors. But I can't decide which one would be better to use.</p>
<p>I am creating a backend system for a website to find near duplicates of semi-structured text data. For example, each record will have a title, location, and a brief text description (<500 words).</p>
<p>Specific language implementation aside, which algorithm would be best for a greenfield production system?</p> | 46,415,603 | 2 | 2 | null | 2014-12-30 20:59:04.21 UTC | 10 | 2019-05-23 15:24:53.027 UTC | 2019-05-23 15:24:53.027 UTC | null | 1,987,762 | null | 1,987,762 | null | 1 | 16 | minhash|simhash | 11,339 | <p><strong>Simhash</strong> is faster (very fast) and typically requires less storage, but imposes a strict limitation on how dissimilar two documents can be and still be detected as duplicates. If you are using a 64-bit simhash (a common choice), and depending on how many permuted tables you are capable of storing, you might be limited to hamming distances of as low as 3 or possibly as high as 6 or 7. Those are small hamming distances! You'll be limited to detecting documents that are mostly identical, and even then you may need to do some careful tuning of what features you choose to go into the simhash and what weightings you give to them.</p>
<p>The generation of simhashes is patented by google, though in practice they seem to allow at least non-commercial use.</p>
<p><strong>Minhash</strong> uses more memory, since you'd be typically storing 50-400 hashes per document, and it's not as CPU-efficient as simhash, but it allows you to find quite distant similarities, e.g. as low as 5% estimated similarity, if you want. It's also a bit easier to understand than simhash, particularly in terms of how the tables work. It's quite straightforward to implement, typically using shingling, and doesn't need a lot of tuning to get good results. It's not (to my knowledge) patented.</p>
<p>If you're dealing with big data, the most CPU-intensive part of the minhash approach will likely be <em>after</em> you've generated the minhashes for your document, when you're hunting through your table to find other documents that share some of its hashes. There may be tens or hundreds of thousands of documents that share at least one hash with it, and you've got to weed through all of these to find those few that share e.g. a minimum of half its hashes. Simhash is a lot quicker here.</p>
<p>As Otmar points out in his comment below, there are optimizations of minhash that allow you to achieve the same precision on your similarity estimates with fewer hashes per document. This can substantially reduce the amount of weeding you have to do.</p>
<p><em>Edit:</em></p>
<p>I have now tried <a href="https://arxiv.org/pdf/1706.05698.pdf" rel="noreferrer"><strong>superminhash</strong></a>. It's fairly fast, though my implementation of minhash <a href="https://stackoverflow.com/questions/19701052/how-many-hash-functions-are-required-in-a-minhash-algorithm">using a single hash function plus bit-transformations to produce all the other hashes</a> was faster for my purposes. It offers more accurate jaccard estimates, about 15% better under some situations I tested (though almost no difference under others). This should mean you need about a third fewer hashes to achieve the <em>same</em> accuracy. Storing fewer hashes in your table means less "weeding" is needed to identify near duplicates, which delivers a significant speed-up. I'm not aware of any patent on superminhash. Thanks Otmar!</p> |
21,609,012 | Disable readonly to text box onclicking the button | <p>I have used "readonly" attribute to the textbox which makes the textbox non editable and may i know how to disable the readonly attribute on clicking the button. can we do this by using any script ?</p>
<pre class="lang-html prettyprint-override"><code><input type="text" name="" value="" readonly="readonly"/><br/>
<input type="submit" name="" value="update" onclick="" />
</code></pre> | 21,609,128 | 3 | 1 | null | 2014-02-06 16:50:20.143 UTC | 2 | 2020-11-17 18:06:53.183 UTC | 2020-11-17 18:06:53.183 UTC | null | 806,169 | null | 2,823,321 | null | 1 | 17 | javascript|html | 68,959 | <p>You can do two things:</p>
<ul>
<li>Remove the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-readonly" rel="noreferrer"><code>readonly</code></a> (case insensitive) attribute, using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute" rel="noreferrer"><code>removeAttribute</code></a></li>
<li>Set the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties" rel="noreferrer"><code>readOnly</code></a> (case sensitive) property to <code>false</code></li>
</ul>
<p>HTML:</p>
<pre><code><input id="myInput" type="text" readonly="readonly" /><br />
<input id="myButton" type="submit" value="update" />
</code></pre>
<p>JS (option 1): [<a href="http://jsfiddle.net/343Rb/" rel="noreferrer"><strong>Demo</strong></a>]</p>
<pre><code>document.getElementById('myButton').onclick = function() {
document.getElementById('myInput').removeAttribute('readonly');
};
</code></pre>
<p>JS (option 2): [<a href="http://jsfiddle.net/343Rb/1/" rel="noreferrer"><strong>Demo</strong></a>]</p>
<pre><code>document.getElementById('myButton').onclick = function() {
document.getElementById('myInput').readOnly = false;
};
</code></pre> |
21,569,718 | How do I exit a Rust program early from outside the main function? | <p>I am in the process of writing a <code>bash</code> clone in Rust. I need to have my program exit when the user types <code>exit</code>. In previous iterations of my program, before I added more complicated features, I used <code>return</code> to get out of the loop that was prompting the user for input. This logic is now in a function, because of the way I am implementing built in shell functions, so when I <code>return</code> it just jumps out of the function back into the control loop, instead of short-circuiting the control loop and ending the program.</p>
<p>I realize that I could probably return a boolean when the user types <code>exit</code> and exit the loop, but I would like to at least know if Rust has a way to terminate programs early, similar to Java's <code>System.exit()</code>, as this is useful for certain types of programs.</p> | 21,570,851 | 2 | 1 | null | 2014-02-05 06:00:20.17 UTC | 4 | 2019-02-15 09:36:38.397 UTC | 2018-05-31 15:42:01.123 UTC | null | 155,423 | null | 2,448,605 | null | 1 | 52 | system|rust | 30,162 | <h3>Rust 1.0 stable</h3>
<p><a href="http://doc.rust-lang.org/std/process/fn.exit.html" rel="noreferrer"><code>std::process::exit()</code></a> does exactly that - it terminates the program with the specified exit code:</p>
<pre><code>use std::process;
fn main() {
for i in 0..10 {
if i == 5 {
process::exit(1);
}
println!("{}", i);
}
}
</code></pre>
<p>This function causes the program to terminate immediately, without unwinding and running destructors, so it should be used sparingly.</p>
<h3>Alternative (not recommended) solution</h3>
<p>You can use C API directly. Add <code>libc = "0.2"</code> to <code>Cargo.toml</code>, and:</p>
<pre><code>fn main() {
for i in 0..10 {
if i == 5 {
unsafe { libc::exit(1); }
}
println!("{}", i);
}
}
</code></pre>
<p>Calling C functions cannot be verified by the Rust compiler, so this requires the <code>unsafe</code> block. Resources used by the program will not be freed properly. This may cause problems such as hanging sockets.
As far as I understand, the proper way to exit from the program is to terminate all threads somehow, then the process will exit automatically. </p> |
32,642,417 | PHP date time greater than today | <p>please help what's wrong with my code? It always returns that today's date is greater than '01/02/2016' wherein 2016 is greater than in 2015.</p>
<pre><code><?php
$date_now = date("m/d/Y");
$date = date_create("01/02/2016");
$date_convert = date_format($date, "m/d/Y");
if ($date_now > $date_convert) {
echo 'greater than';
} else {
echo 'Less than';
}
</code></pre>
<p>P.S: 01/02/2016 is coming from the database.</p> | 32,642,436 | 3 | 1 | null | 2015-09-18 01:20:53.093 UTC | 18 | 2022-07-01 07:59:45.86 UTC | 2020-06-02 14:34:16.077 UTC | null | 5,211,514 | null | 3,363,230 | null | 1 | 58 | php|date | 174,806 | <p>You are <em>not</em> comparing dates. You are comparing <em>strings</em>. In the world of string comparisons, <code>09/17/2015</code> > <code>01/02/2016</code> because <code>09</code> > <code>01</code>. You need to either put your date in a comparable string format or compare <code>DateTime</code> objects which are comparable.</p>
<pre><code><?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
</code></pre>
<p><a href="https://3v4l.org/LU115" rel="noreferrer">Demo</a></p>
<p>Or</p>
<pre><code><?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
</code></pre>
<p><a href="https://3v4l.org/5rQVP" rel="noreferrer">Demo</a></p> |
9,623,769 | ORA-04045: errors during recompilation/revalidation | <p>I just suddenly started getting this error when trying to query the table AVC.</p>
<pre><code>ORA-04045: errors during recompilation/revalidation of PUBLIC.AVC
ORA-04098: trigger 'TTMS.ALTERED_TTMSDB_TABS_TRIGGER' is invalid and failed re-validation
</code></pre>
<p><code>select * from avc</code> doesnt work
but <code>select * from exfc.avc</code> does work.</p>
<p>Can anyone tell me what is going on?</p> | 9,623,890 | 2 | 0 | null | 2012-03-08 19:41:17.87 UTC | null | 2019-09-12 12:42:22.027 UTC | 2016-11-17 21:03:12.473 UTC | null | 393,243 | null | 802,331 | null | 1 | 3 | oracle | 45,983 | <p>Presumably there is not an object in your schema named <code>AVC</code>. When you reference <code>AVC</code> without a schema qualifier, it is therefore accessing the <code>PUBLIC</code> object with that name. To find out what kind of object that is, <code>SELECT object_type FROM all_objects WHERE object_name='AVC' AND owner='PUBLIC'</code>.</p>
<p>Whatever it is, querying it is for some reason causing a trigger to fire. Maybe this is some sort of auditing function. But currently the trigger is invalid. This could mean that someone modified the trigger itself but made an error; or it could mean that someone dropped or modified some other object that the trigger depends on, in such a way that the trigger code is no longer valid.</p>
<p>So, whoever's responsible for that trigger needs to find out what error is occurring in its compilation and resolve it.</p>
<p>When you explicitly query <code>EXFC.AVC</code>, you are bypassing the <code>PUBLIC</code> object and going directly to some underlying object, probably an actual table. It seems very odd that you would have access to this, since the whole point of routing access through a public synonym is usually to prevent direct access to the object. And if, in fact, the purpose of the trigger is to audit accesses to the table, then allowing you to bypass it entirely is a pretty big design flaw.</p> |
9,283,188 | How to efficiently find CGRects for visible words in UITextView? | <p>My goal is to mark all visible misspelled words in an UITextView. </p>
<p>The inefficient algorithm is to use the spell checker to find all ranges of misspelled words in the text, convert them to UITextRange objects using positionFromPosition:inDirection:offset etc, then get the graphics rects using the UITextInput method firstRectFromRange.</p>
<p>Thus all the text -> misspelled words-> NSRange collection -> UITextRange collection -> CGRect collection -> evaluate for visibility, draw visible ones</p>
<p>The problem is that this requires that all the text is checked, and all misspelled words are converted to graphics rects.</p>
<p>Thus, I imagine the way to go is to somehow find out what parts of the underlying .text in the UITextView that is visible at the moment.</p>
<p>Thus for range of text visible -> misspelled words-> NSRange collection -> UITextRange collection -> CGRect collection -> evaluate for visibility, draw visible ones</p>
<p>The code in <a href="https://stackoverflow.com/questions/6067803/ios-how-to-find-what-is-the-visible-range-of-text-in-uitextview">ios - how to find what is the visible range of text in UITextView?</a> might work as a way to bound what parts of the text to check, but still requires that all text is measured, which I imagine could be quite costly.</p>
<p>Any suggestions?</p> | 9,283,311 | 2 | 0 | null | 2012-02-14 19:43:50.417 UTC | 9 | 2018-05-28 05:07:10.38 UTC | 2017-05-23 12:08:47.533 UTC | null | -1 | null | 787,610 | null | 1 | 10 | ios | 4,665 | <p>Since <code>UITextView</code> is a subclass of <code>UIScrollView</code>, its <code>bounds</code> property reflects the visible part of its coordinate system. So something like this should work:</p>
<pre><code>- (NSRange)visibleRangeOfTextView:(UITextView *)textView {
CGRect bounds = textView.bounds;
UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start;
UITextPosition *end = [textView characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
return NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start],
[textView offsetFromPosition:start toPosition:end]);
}
</code></pre>
<p>This assumes a top-to-bottom, left-to-right text layout. If you want to make it work for other layout directions, you will have to work harder. :)</p> |
9,127,301 | Get entity name from class object | <p>I have the following code: </p>
<pre><code>namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\StoreBundle\Entity\User
*
* @ORM\Table(name="users")
* @ORM\Entity()
*/
class User {
...
}
$user = new User();
</code></pre>
<p>Does anybody know how I can now get the entity name (<code>AcmeStoreBundle:User</code>) from the <code>User</code> object?</p> | 14,229,984 | 4 | 0 | null | 2012-02-03 10:42:07.563 UTC | 0 | 2020-04-16 19:38:49.89 UTC | 2013-11-14 19:58:34.73 UTC | user212218 | null | null | 1,028,177 | null | 1 | 19 | symfony|doctrine-orm | 43,001 | <p>This should always work (no return of Proxy class):</p>
<pre><code>$em = $this->container->get('doctrine')->getEntityManager();
$className = $em->getClassMetadata(get_class($object))->getName();
</code></pre>
<p><strong>As <code>getClassMetadata</code> is deprecated, you can now use <code>getMetadataFor</code></strong></p>
<pre><code>$entityName = $this->em->getMetadataFactory()->getMetadataFor(get_class($object))->getName();
</code></pre> |
9,226,263 | Moving Onto The Next UITextField When 'Next' Is Tapped | <p>I have an iPad application which has a sign up form within it. The form is very basic and contains only two UITextFields which are for Name & Email address.</p>
<p>The first TextField is for the candidates Name, When they enter their name in and press 'Next' on the keyboard I want this to automatically move to the next Email Address TextField to editing.</p>
<p>Any idea how I can set the next button the keyboard to jump to the next keyboard?</p>
<p>Thanks</p> | 9,226,363 | 7 | 0 | null | 2012-02-10 10:26:33.117 UTC | 12 | 2018-11-14 21:08:59.787 UTC | null | null | null | null | 659,583 | null | 1 | 38 | objective-c|xcode|ipad|ios4|uitextfield | 30,851 | <p>You need to make your view controller the UITextField delegate, and implement the UITextField delegate method:</p>
<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == nameField) {
[textField resignFirstResponder];
[emailField becomeFirstResponder];
} else if (textField == emailField) {
// here you can define what happens
// when user presses return on the email field
}
return YES;
}
</code></pre>
<p><strong>Swift version:</strong></p>
<pre><code>func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == nameField {
textField.resignFirstResponder()
emailField.becomeFirstResponder()
} else if textField == emailField {
// here you can define what happens
// when user presses return on the email field
}
return true
}
</code></pre>
<p>You may also want to scroll your view for the emailField to become visible. If your view controller is an instance of UITableViewController, this should happen automatically. If not, you should read <a href="https://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html" rel="noreferrer">this Apple document</a>, especially <em>Moving Content That Is Located Under the Keyboard</em> part.</p> |
34,114,679 | Convert a React.element to a JSX string | <p>I am trying to build a component which,</p>
<ol>
<li>Takes children and </li>
<li>Renders the children in the DOM and also,</li>
<li>Shows the children DOM in a <code>pre</code> for documentation sake</li>
</ol>
<p>One solution is to pass the JSX as a separate <code>prop</code> as well. This makes it repetitive since I am already able to access it through <code>this.props.children</code>. Ideally, I just need to somehow convert the <code>children</code> prop as a <code>string</code> so that I can render it in a <code>pre</code> to show that <em>"this code produces this result"</em>.</p>
<p>This is what I have so far</p>
<pre><code>class DocumentationSection extends React.Component{
render(){
return <div className="section">
<h1 className="section__title">{heading || ""}</h1>
<div className="section__body"> {this.props.children}</div>
<pre className="section__src">
//Change this to produce a JSX string from the elements
{this.props.children}
</pre>
</div>;
}
}
</code></pre>
<p>How can I get the a jsx string in the format <code>'<Div className='myDiv'>...</Div></code> when I render DocumentationSection as </p>
<pre><code><DocumentationSection heading='Heading 1'>
<Div className='myDiv'>...</Div>
</DocumentationSection>
</code></pre>
<p>Thanks. </p>
<p><strong>Edit</strong>: </p>
<p>I tried toString, it dint work, gave [object Object]</p> | 34,114,771 | 4 | 1 | null | 2015-12-06 06:19:31.173 UTC | 7 | 2021-06-23 19:17:45.887 UTC | null | null | null | null | 2,621,400 | null | 1 | 35 | javascript|reactjs | 79,566 | <p>If you want the HTML representation of a React element you can use <code>#renderToString</code> or <code>#renderToStaticMarkup</code>.</p>
<pre><code>ReactDomServer.renderToString(<div>p</div>);
ReactDomServer.renderToStaticMarkup(<div>p</div>);
</code></pre>
<p>will produce</p>
<pre><code><div data-reactid=".1" data-react-checksum="-1666119235">p</div>
</code></pre>
<p>and</p>
<pre><code><div>p</div>
</code></pre>
<p>respectively. You will however not be able to render the parent as a string from within itself. If you need the parent too then from where you render the parent pass a <code>renderToString</code> version of it as props to itself.</p> |
34,075,486 | How to list the regions in an HBase table through the shell? | <p>I would like to get the same information about the regions of a table that appear in the web UI (i.e. region name, region server, start/end key, locality), but through the hbase shell. </p>
<p>(The UI is flaky/slow, and furthermore I want to process this information as part of a script.)</p>
<p>After much googling, I can't find out how, and this surprises me immensely. version is 1.0.0.-cdh5.4.0</p> | 34,082,230 | 5 | 2 | null | 2015-12-03 20:24:48.317 UTC | 13 | 2020-08-13 11:03:44.77 UTC | null | null | null | null | 19,269 | null | 1 | 21 | hbase | 33,119 | <p>To get the region info about the table, you need to scan <code>hbase:meta</code> table.</p>
<pre><code>scan 'hbase:meta',{FILTER=>"PrefixFilter('table_name')"}
</code></pre>
<p>This command will give details of all the regions. Row key will have region name and there will be four column qualifiers. You may need following two column qualifiers:</p>
<p><code>info:regioninfo</code> - This qualifier contains STARTKEY and ENDKEY.</p>
<p><code>info:server</code> - This qualifier contains region server details</p> |
10,538,718 | jQuery Mobile pageinit/pagecreate not firing | <p>I have 5 pages - for ease lets say:</p>
<ul>
<li>one.html</li>
<li>two.html</li>
<li>three.html</li>
<li>four.html</li>
<li>five.html</li>
</ul>
<p>When I load each individual page, both <code>pageinit</code> and <code>pagecreate</code> are firing correctly. </p>
<p>The Problem:</p>
<p>When I go from one.html to two.html, <code>pageinit</code> and <code>pagecreate</code> both fire, BUT when I go back to one.html (from two.html), <code>pageinit</code> and <code>pagecreate</code> DO NOT fire. </p>
<p>Why is this and how can I always fire <code>pageinit</code> and <code>pagecreate</code> on page load, as well as navigating through each page?</p>
<p>Update:</p>
<p>For each page I have:</p>
<pre><code><div data-role="page" id="page-name">
// content
</div>
</code></pre>
<p>To test the order at when things are firing I do:</p>
<pre><code>$(document).on('pagecreate','[data-role=page]', function(){
console.log('PAGECREATE');
});
$(document).on('pageinit','[data-role=page]', function(){
console.log('PAGEINIT');
});
$(document).on('pagebeforeshow','[data-role=page]', function(){
console.log('PAGEBEFORESHOW');
});
$(document).on('pageshow','[data-role=page]', function(){
console.log('PAGESHOW');
});
</code></pre>
<p>How do I use the pagechange to always call the <code>pageinit</code> and <code>pagecreate</code></p> | 10,542,821 | 7 | 1 | null | 2012-05-10 16:48:04.457 UTC | 9 | 2014-06-25 03:40:32.177 UTC | 2012-05-10 17:20:44.98 UTC | null | 884,951 | null | 884,951 | null | 1 | 18 | jquery|jquery-mobile | 26,988 | <p>You're checking for the wrong events, pageinit and pageshow are what you should be concerned about.</p>
<p><strong>pageinit</strong> fires everytime a page is loaded for the first time, jQM caches pages in the DOM/memory so when you navigate back from two.html to one.html, pageinit won't fire (it's already initialized)</p>
<p><strong>pageshow</strong> fires everytime a page is shown, this is what you need to be looking for when you navigate back from two.html to one.html</p>
<p>Together you can pull off a lot of clean code, use pageinit for initializing, configuration etc and update your DOM to the initial state. If you have dynamic data on the page that may change between views, handle it in pageshow
<br/>
<br/></p>
<p>Here's a good design for larger websites that we use in a production environment:</p>
<ol>
<li><p>bind a live event to all pages/dialogs pageinit and pageshow events in some include that is on every page:</p>
<p><code>$(document).on('pageinit pageshow', 'div:jqmData(role="page"), div:jqmData(role="dialog")', function(event){</code></p></li>
<li><p>I reference each page with a name: <code><div data-role="page" data-mypage="employeelist"></code>
In this live event you can basically have a switch statement for each page "name", and then check event.type for pageinit/pageshow or both and put your code there, then every time a page is created/shown this event will be fired, it knows what page triggered it and then calls the corresponding code</p></li>
<li><p>Now no matter what entry point a user lands on your site, all the handlers for all the pages are loaded. As you may already know, when you navigate to a page, it only pulls in <code><script/></code> within the div[data-role="page"] - ignoring any JS in the <code><head/></code>, placing separate JS on each page is a mess and should be avoided in any large site I believe</p></li>
<li><p>Try not to use blanket selectors in your jQuery, e.g. <code>$('div.myClass')</code> since this will search all of your DOM which may have more than one jQM page in it. Luckily in the live event handler for pageinit/pageshow mentioned above, <code>this</code> refers to the current page. So do all DOM searches within it, e.g. <code>$(this).find('div.myClass')</code> this ensures you are only grabbing elements within the current page. (of course this isn't a concern for ids). <em>Note in the pageshow event you can also use <code>$.mobile.activePage</code>, but this isn't available in the pageinit, so I don't use it for consistency</em></p></li>
</ol>
<p><br/>
I eventually had too much code, so I built a handler object where each page's js is included in a separate js file and can register handlers with the live event</p>
<p>The drawback is that all your js for your entire site is loaded on the first page the user reaches, but minified even a large site is smaller than jQuery or jQM so this shouldn't be a concern. <em>But if your site really is large I suppose you could look into RequireJS.</em></p>
<p>An advantage is you are no longer loading all your JS for each page through AJAX each time the user navigates to a new page. <strong>If all your JS is available on entry, you can now put debugger statements and debug much more easily!</strong></p> |
10,398,543 | Play framework 2.0 continuous integration setup | <p>I am looking for ideas for a Play 2.0 continuous integration setup. It would contain typical jobs like build after a git push, nightly builds with deployment to a test Heroku instance etc. Also code quality and test coverage metrics generation would be handy.</p>
<p>At the moment the stack looks like Play 2.0 with Java but that might change to Scala.</p>
<p>For "traditional" Java web app I would use Hudson/Jenkins. I found a <a href="http://wiki.hudson-ci.org/display/HUDSON/play-plugin" rel="noreferrer">Hudson plugin for Play</a> but it doesn't seem to support Play 2.0. Is Hudson suitable tool here in general or what is your setup for Play 2.0 applications?</p> | 10,409,020 | 4 | 1 | null | 2012-05-01 13:43:05.227 UTC | 13 | 2013-05-31 09:56:59.993 UTC | 2013-05-28 18:49:59.737 UTC | null | 98,632 | null | 28,841 | null | 1 | 26 | testing|continuous-integration|hudson|jenkins|playframework-2.0 | 10,363 | <p>Play 2.0's build tool is just a thin wrapper around <a href="https://github.com/harrah/xsbt/wiki">SBT</a>. You should be able to use Hudson's <a href="http://wiki.hudson-ci.org/display/HUDSON/sbt+plugin">sbt plugin</a> to execute SBT build commands that are the equivalent of the Play commands you would execute from the console.</p>
<p>We execute the following under Bamboo for our builds:</p>
<pre><code>SBT_OPTS="-Dsbt.log.noformat=true"
sbt clean compile test
</code></pre>
<p>(The SBT_OPTS variable turns off the colour formatting, making test output legible in log files.)</p> |
10,467,024 | How do I create my own NLTK text from a text file? | <p>I'm a Literature grad student, and I've been going through the O'Reilly book in Natural Language Processing (nltk.org/book). It looks incredibly useful. I've played around with all the example texts and example tasks in Chapter 1, like concordances. I now know how many times Moby Dick uses the word "whale." The problem is, I can't figure out how to do these calculations on one of my own texts. I've found information on how to create my own corpora (Ch. 2 of the O'Reilly book), but I don't think that's exactly what I want to do. In other words, I want to be able to do </p>
<pre><code>import nltk
text1.concordance('yellow')
</code></pre>
<p>and get the places where the word 'yellow' is used in my text. At the moment I can do this with the example texts, but not my own. </p>
<p>I'm very new to python and programming, and so this stuff is very exciting, but very confusing. </p> | 10,467,054 | 3 | 1 | null | 2012-05-06 00:13:23.22 UTC | 16 | 2020-09-07 09:35:17.063 UTC | null | null | null | null | 584,121 | null | 1 | 37 | python|nltk | 28,884 | <p>Found the answer myself. That's embarrassing. Or awesome. </p>
<p>From Ch. 3: </p>
<pre><code>f=open('my-file.txt','rU')
raw=f.read()
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
</code></pre>
<p>Does the trick. </p> |
7,451,299 | How do I preserve the remote filename when Downloading a file using curl | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2698552/how-do-i-save-a-file-using-the-response-header-filename-with-curl">How do I save a file using the response header filename with cURL</a> </p>
</blockquote>
<p>I need to download many thousands of images in the format</p>
<p><a href="http://oregondigital.org/cgi-bin/showfile.exe?CISOROOT=/baseball&CISOPTR=0" rel="noreferrer">http://oregondigital.org/cgi-bin/showfile.exe?CISOROOT=/baseball&CISOPTR=0</a></p>
<p>If you paste that link in a browser, it tries to download a file named 1.jp2</p>
<p>I want to use curl to do the same. However, when I run </p>
<p>curl -I '<a href="http://oregondigital.org/cgi-bin/showfile.exe?CISOROOT=/baseball&CISOPTR=0" rel="noreferrer">http://oregondigital.org/cgi-bin/showfile.exe?CISOROOT=/baseball&CISOPTR=0</a>'</p>
<p>the filename is reported as 404.txt which you can download and see that it is actually the file I want. I can't use the -O option because the name assigned to the file is no good, and I have technical reasons for needing the actual name used on the system.</p>
<p>How do I get curl to download the same file I have no trouble retrieving in my browser? Thanks.</p> | 7,451,779 | 2 | 1 | null | 2011-09-16 23:19:51.35 UTC | 29 | 2018-03-29 18:55:15.817 UTC | 2017-05-23 11:54:59.723 UTC | null | -1 | null | 493,144 | null | 1 | 115 | shell|scripting|curl | 57,595 | <p>The solution is to use <code>-O -J</code></p>
<blockquote>
<pre><code>-O, --remote-name Write output to a file named as the remote file
-J, --remote-header-name Use the header-provided filename
</code></pre>
</blockquote>
<p>So...</p>
<pre><code>curl -O -J 'http://oregondigital.org/cgi-bin/showfile.exe?CISOROOT=/baseball&CISOPTR=0'
</code></pre>
<p>I had to upgrade my CURL. I had v 7.19 which doesn't support -J but 7.22 (which is the latest) does. </p> |
31,415,270 | Parse JSON and show data in Angular | <p>I have a trouble with displaying JSON data in Angular. I successfully send data from backend to frontend (Angular), but I cannot display them.</p>
<p>I tried to simulate a similar situation on <a href="http://jsfiddle.net/29y61wtg/2/" rel="noreferrer">JSFiddle</a>, although I already have prepared data from backend <img src="https://i.stack.imgur.com/tMN37.png" alt="following format"></p>
<p>get/send data -> Backend side:</p>
<pre><code>//push data to Redis
var messages= JSON.stringify(
[
{
"name": "Msg1",
"desc": "desc Msg1"
},
{
"name": "Msg2",
"desc": "desc Msg2"
},
{
"name": "Msg3",
"desc": "desc Msg3"
},
{
"name": "Msg4",
"desc": "desc Msg4"
}
]);
redisClient.lpush('list', messages, function (err, response) {
console.log(response);
});
//get from redis and send to frontend
app.get('/messages', function(req, res){
// Query your redis dataset here
redisClient.lrange('list', 0, -1, function(err, messages) {
console.log(messages);
// Handle errors if they occur
if(err) res.status(500).end();
// You could send a string
res.send(messages);
// or json
// res.json({ data: reply.toString() });
});
});
</code></pre>
<p>get data -> frontend (Angular)</p>
<pre><code>angular.module('app')
.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
'use strict';
getFromServer();
function getFromServer(){
$http.get('/messages')
.success(function(res){
$scope.messages= res;
console.log(res);
});
}
}])
</code></pre>
<p>HTML part with ng-repeat directive:</p>
<pre><code><div ng-app="app" ng-controller="MainCtrl" class="list-group">
<div class="list-group-item" ng-repeat="item in messages">
<h4 class="list-group-item-heading">{{item.name}}</h4>
<p class="list-group-item-text">{{item.desc}}</p>
<div>
</div>
</code></pre>
<p>Would anyone know what the problem is?</p> | 31,415,414 | 1 | 3 | null | 2015-07-14 19:08:27.397 UTC | 2 | 2015-07-14 19:28:14.51 UTC | null | null | null | null | 3,265,921 | null | 1 | 13 | json|angularjs|node.js|express | 113,199 | <p>As far as I can see, you're storing your Object as JSON, but you never parse it. Therefore using</p>
<pre><code>$scope.messages = JSON.parse(res);
</code></pre>
<p>instead of</p>
<pre><code>$scope.messages = res;
</code></pre>
<p>should fix your problem.</p>
<p>Here is a working JSFiddle version of yours: <a href="https://jsfiddle.net/29y61wtg/5/" rel="noreferrer">https://jsfiddle.net/29y61wtg/5/</a></p>
<p>Note, that this doesn't include a $http call, if you're still having problems after using $http, tell me in the comments.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.