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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,320,794 | How to add a sub item in Android ListView? | <p>I have made a android listView taking the help from <a href="http://www.vogella.com/articles/AndroidListView/article.html" rel="noreferrer">Vogella.com</a> using following layout and ListActivity class. </p>
<p><strong>RowLayout.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/icon"
android:layout_width="22px"
android:layout_height="22px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="@drawable/icon" >
</ImageView>
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="20px" >
</TextView>
</LinearLayout>
</code></pre>
<p><strong>MyListActivity.java</strong></p>
<pre><code>package de.vogella.android.listactivity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MyListActivity extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// use your own layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>I want to add a sub item below the textView and keep the full text portion in the center of each row. How can I do it?</p> | 20,321,239 | 4 | 6 | null | 2013-12-02 04:21:49.81 UTC | 4 | 2016-11-08 14:22:52.013 UTC | 2013-12-02 05:10:08.663 UTC | null | 2,986,057 | null | 2,986,057 | null | 1 | 9 | android|listview | 67,323 | <p>A <code>ListView</code> item can have it's own custom layout. When you create your adapter for the <code>ListView</code> you can pass in the layout id to the Adapter constructor. See <a href="http://developer.android.com/reference/android/widget/SimpleAdapter.html">SimpleAdapter</a> and <a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html">ArrayAdapter</a>. </p>
<p>If you want to show some more details like image and text or two textview then You will have to extend an Adapter and implement <strong><code>getView()</code></strong> to property set the image+text.</p>
<p>Check out <a href="http://www.learn2crack.com/2013/10/android-custom-listview-images-text-example.html">Custom ListView</a></p>
<p>And if you want to categorize the ListView in sections then you should go for the <a href="http://bartinger.at/listview-with-sectionsseparators/">Section ListView in Android</a> also check <a href="http://sunil-android.blogspot.in/2013/08/section-header-listview-in-android.html">Section Header in ListView</a></p> |
3,558,561 | Oracle SQL - select within a select (on the same table!) | <p>I'll try and explain what I'm trying to achieve quickly, since I have no idea how to explain it otherwise!</p>
<p>We have a table here that shows all employment history for all employees, I want the "Start_Date" of the current post ("Current_Flag" = 'Y'). As well as that, I want the "End_Date" of the post before that (was going to filter by current flag, sort by end date, and just grab the top one)</p>
<p>So anyway, here's my code:</p>
<pre><code>SELECT "Gc_Staff_Number",
"Start_Date",
(SELECT "End_Date"
FROM "Employment_History"
WHERE "Current_Flag" != 'Y'
AND ROWNUM = 1
AND "Employee_Number" = "Employment_History"."Employee_Number"
ORDER BY "End_Date" ASC)
FROM "Employment_History"
WHERE "Current_Flag" = 'Y'
</code></pre>
<p>Any suggestions on how to get this working would be fantastic, hopefully the above makes a little bit of sense - to be honest the query at the moment won't even work which really sucks, hmm.</p>
<p>(edit: Oh! I'm writing this to query an existing system... which for some reason has all of the stupid double quotes around the table and field names, sigh!)</p> | 3,558,815 | 6 | 3 | null | 2010-08-24 16:14:12.3 UTC | 1 | 2016-09-14 09:12:59.19 UTC | 2010-08-24 16:21:25.45 UTC | null | 134,779 | null | 134,779 | null | 1 | 8 | sql|oracle|select|join | 118,757 | <p>This is precisely the sort of scenario where analytics come to the rescue.</p>
<p>Given this test data:</p>
<pre><code>SQL> select * from employment_history
2 order by Gc_Staff_Number
3 , start_date
4 /
GC_STAFF_NUMBER START_DAT END_DATE C
--------------- --------- --------- -
1111 16-OCT-09 Y
2222 08-MAR-08 26-MAY-09 N
2222 12-DEC-09 Y
3333 18-MAR-07 08-MAR-08 N
3333 01-JUL-09 21-MAR-09 N
3333 30-JUL-10 Y
6 rows selected.
SQL>
</code></pre>
<p>An inline view with an analytic LAG() function provides the right answer:</p>
<pre><code>SQL> select Gc_Staff_Number
2 , start_date
3 , prev_end_date
4 from (
5 select Gc_Staff_Number
6 , start_date
7 , lag (end_date) over (partition by Gc_Staff_Number
8 order by start_date )
9 as prev_end_date
10 , current_flag
11 from employment_history
12 )
13 where current_flag = 'Y'
14 /
GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
1111 16-OCT-09
2222 12-DEC-09 26-MAY-09
3333 30-JUL-10 21-MAR-09
SQL>
</code></pre>
<p>The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.</p> |
3,347,997 | get a total of jquery's .each() | <p>I'm using jquery's .each() to iterate over a group of li's. I need a total of all the li's matched. Is the only way to create a count variable outside the .each() and increment this inside the .each()? It doesn't seem very elegant.</p>
<pre><code>var count;
$('#accordion li').each(function() {
++count;
});
</code></pre> | 3,348,010 | 6 | 0 | null | 2010-07-27 21:06:49.453 UTC | 5 | 2021-03-19 07:32:06.27 UTC | null | null | null | null | 392,572 | null | 1 | 35 | javascript|jquery | 58,976 | <p>Two options:</p>
<pre><code>$('#accordion li').size(); // the jQuery way
$('#accordion li').length; // the Javascript way, which jQuery uses
</code></pre>
<p>Since jQuery calls length under the hood, it's faster to use that instead of the size() call.</p> |
3,299,981 | How can I see qDebug messages while debugging in QtCreator | <p>I'm making the transition from Eclipse CDT (with Qt integration plugin) to QtCreator 2.0 but there is still one thing that bother me with QtCreator :</p>
<p>When I debug in QtCreator, I don't see my qDebug messages inside the <code>Application output tab</code> until I stop the application I'm debugging... Then they are all displayed at once which is not very useful.</p>
<p>With Eclipse, I don't have this problem : the qDebug messages are displayed correctly when encountered while stepping through the source code.</p>
<p>I'm using both Eclipse CDT and Qt Creator under Windows. I didn't try under Linux (which is not an option right now).</p> | 3,392,118 | 8 | 4 | null | 2010-07-21 13:54:58.657 UTC | 6 | 2022-03-03 09:24:08.65 UTC | 2015-10-24 16:32:17.993 UTC | null | 462,639 | null | 134,973 | null | 1 | 15 | qt|gdb|mingw|qt-creator | 45,879 | <p>While not a complete answer, you can install <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="noreferrer">DebugView</a> (If you're on an XP machine) to view the qDebug output while you try to figure this out.</p>
<p>Another solution might be considered a hack, but works quite nicely, is to simply hijack debug messages yourself:</p>
<pre><code>#include <QtCore/QCoreApplication>
#include <QDebug>
#include <iostream>
void msgHandler( QtMsgType type, const char* msg )
{
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg );
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
int main(int argc, char *argv[])
{
qInstallMsgHandler( msgHandler );
QCoreApplication a(argc, argv);
qDebug() << "Hello world.";
qWarning() << "Uh, oh...";
qCritical() << "Oh, noes!";
qFatal( "AAAAAAAAAH!" );
return a.exec();
}
</code></pre>
<p>Which would output:</p>
<pre><code>[I] Hello world.
[E] Uh, oh...
[!] Oh, noes!
[X] AAAAAAAAAH!
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</code></pre>
<p>This is actually a modification of some code that I use myself to send qDebug, qWarning, etc., to a log file.</p> |
3,659,809 | Where am I? - Get country | <p>An android mobile actually does know quite well where it is - but is there a way of retrieving the country by something like a country code?</p>
<p>No need of knowing the exact GPS position - the <em>country</em> is sufficient </p>
<p>I first thought of using the time zone, but actually I need more information than that since it makes a difference if the location is New York or Lima.</p>
<p><em>The background of the question:</em> I have an application that uses temperature values, and I'd like to set the default unit either to Celsius or Fahrenheit, depending on whether the location is US or outside</p> | 3,660,245 | 10 | 1 | null | 2010-09-07 14:57:04.1 UTC | 65 | 2022-03-16 14:01:56.393 UTC | null | null | null | null | 415,347 | null | 1 | 138 | android|geolocation | 128,468 | <p>This will get the <a href="http://developer.android.com/reference/java/util/Locale.html#getCountry()" rel="noreferrer">country code</a> set for the phone (phones language, NOT user location):</p>
<pre><code> String locale = context.getResources().getConfiguration().locale.getCountry();
</code></pre>
<p>can also replace getCountry() with <a href="http://developer.android.com/reference/java/util/Locale.html#getISO3Country()" rel="noreferrer">getISO3Country()</a> to get a 3 letter ISO code for the country. This will get the <a href="http://developer.android.com/reference/java/util/Locale.html#getDisplayCountry()" rel="noreferrer">country name</a>:</p>
<pre><code> String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
</code></pre>
<p>This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :) </p>
<p><strong>Editors note</strong>: This solution has nothing to do with the location of the phone. It is constant. When you travel to Germany locale will NOT change. In short: locale != location.</p> |
8,152,454 | Vim: changing/deleting up to the end of a "block" | <p>When you have a block of text delimitated by brackets or quotes, you can use</p>
<pre><code>ci"
da(
</code></pre>
<p>and so on to change that block of text. But is there a way to change or delete from the cursor to the end of that block (in the way <code>cw</code> does it for words)?</p> | 8,164,936 | 4 | 2 | null | 2011-11-16 13:30:27.663 UTC | 9 | 2011-11-17 22:36:59.187 UTC | null | null | null | null | 164,171 | null | 1 | 17 | vim|editor | 7,553 | <p>Benoit's answer of using <code>t f T</code> and <code>F</code> is the best way that I know of. When it comes to deleting to the end of a parenthesised block you can use <code>])</code>. This will take into account any nested parenthesis. There is also a corresponding <code>[(</code>, <code>]}</code> and <code>[{</code>.</p> |
7,805,530 | Neural Network Project Ideas | <p>I am a Computing student with AI major. I am now researching topics for my final year project and I'm quite interested in Neural Network though I have almost no knowledge about it.</p>
<p>Topics I'm considering right now are language and music, so I'm looking for suggestion what will be interesting or popular scope what can be done with Neural Network for language and music. Feel free to give suggestion for different field, too.</p>
<p>Any input, suggestion, link, advice or pointer will be appreciated. Thanks! :)</p>
<p>Update: So I've narrowed the topic I'm most possibly doing to:</p>
<ol>
<li>Music Genre Classification using NN</li>
<li>Text Mining Using NN</li>
</ol>
<p>My question is whether both are too advanced to be done by undergraduate student?</p> | 7,805,628 | 5 | 0 | null | 2011-10-18 10:07:03.717 UTC | 11 | 2021-02-03 11:40:49.857 UTC | 2011-12-09 16:36:16.097 UTC | null | 3,043 | null | 812,398 | null | 1 | 13 | artificial-intelligence|neural-network | 30,892 | <p>have a look at <a href="https://archive.ics.uci.edu/ml/datasets.php" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets.php</a>
and see if you find some topic that you like.</p>
<p>If you have experience with C++ and C it will be easier learning Matlab.</p>
<p>Regarding your topic to use, i suggest you see the link above, and try to find something that you like that can be applied to NN, search acm, ieee or other repositories for papers about NN and see if you can find also studies or reports about the topic you may be looking for.</p>
<p>Good luck.</p> |
8,343,509 | Better error message for stopifnot? | <p>I am using <code>stopifnot</code> and I understand it just returns the first value that was not <code>TRUE</code>. I f that is some freaky dynamic expression someone who is not into the custom function cannot really make something out of that. So I would love to add a custom error message. Any suggestions?</p>
<pre><code>Error: length(unique(nchar(check))) == 1 is not TRUE
</code></pre>
<p>Basically states that the elements of the vector <code>check</code> do not have the same length.
Is there a way of saying: <code>Error: Elements of your input vector do not have the same length!</code>?</p> | 8,343,728 | 8 | 0 | null | 2011-12-01 15:07:32.193 UTC | 12 | 2021-11-20 08:47:23.897 UTC | null | null | null | null | 366,256 | null | 1 | 41 | r | 19,509 | <p>Use <code>stop</code> and an <code>if</code> statement:</p>
<pre><code>if(length(unique(nchar(check))) != 1)
stop("Error: Elements of your input vector do not have the same length!")
</code></pre>
<p>Just remember that <code>stopifnot</code> has the convenience of stating the negative, so your condition in the <code>if</code> needs to be the negation of your stop condition.</p>
<hr>
<p>This is what the error message looks like:</p>
<pre><code>> check = c("x", "xx", "xxx")
> if(length(unique(nchar(check))) != 1)
+ stop("Error: Elements of your input vector do not have the same length!")
Error in eval(expr, envir, enclos) :
Error: Elements of your input vector do not have the same length!
</code></pre> |
7,943,903 | maximum subarray of an array with integers | <p>In an interview one of my friends was asked to find the subarray of an array with maximum sum, this my solution to the problem , how can I improve the solution make it more optimal , should i rather consider doing in a recursive fashion ? </p>
<pre><code>def get_max_sum_subset(x):
max_subset_sum = 0
max_subset_i = 0
max_subset_j = 0
for i in range(0,len(x)+1):
for j in range(i+1,len(x)+1):
current_sum = sum(x[i:j])
if current_sum > max_subset_sum:
max_subset_sum = current_sum
max_subset_i = i
max_subset_j = j
return max_subset_sum,max_subset_i,max_subset_j
</code></pre> | 7,943,955 | 12 | 1 | null | 2011-10-30 08:15:30.257 UTC | 20 | 2018-02-27 22:37:25.923 UTC | null | null | null | null | 236,106 | null | 1 | 15 | algorithm | 39,813 | <p>Your solution is O(n^2). The optimal solution is linear. It works so that you scan the array from left to right, taking note of the best sum and the current sum:</p>
<pre><code>def get_max_sum_subset(x):
bestSoFar = 0
bestNow = 0
bestStartIndexSoFar = -1
bestStopIndexSoFar = -1
bestStartIndexNow = -1
for i in xrange(len(x)):
value = bestNow + x[i]
if value > 0:
if bestNow == 0:
bestStartIndexNow = i
bestNow = value
else:
bestNow = 0
if bestNow > bestSoFar:
bestSoFar = bestNow
bestStopIndexSoFar = i
bestStartIndexSoFar = bestStartIndexNow
return bestSoFar, bestStartIndexSoFar, bestStopIndexSoFar
</code></pre>
<p>This problem was also discussed thourougly in <a href="https://rads.stackoverflow.com/amzn/click/com/0201657880" rel="noreferrer" rel="nofollow noreferrer">Programming Pearls: Algorithm Design Techniques</a> (highly recommended). There you can also find a recursive solution, which is not optimal (O(n log n)), but better than O(n^2).</p> |
4,686,526 | Why is the static keyword used in UITableViewCell identifiers? | <p>I've read up on "static" on several occasions, including just before posting this question.
I'm still searching for an "Aha" though.</p>
<p>In the context of UITableView's static comes up in Cell Identifiers in every piece of code I've looked at. For example in a recent CellForRowAtIndexPath:</p>
<pre><code> static NSString *defaultIndentifier = @"Managed Object Cell Identifier";
</code></pre>
<p>My question is why do we need and use "static"?</p> | 4,686,548 | 3 | 0 | null | 2011-01-13 23:32:47.877 UTC | 9 | 2013-11-13 19:57:52.31 UTC | null | null | null | null | 519,493 | null | 1 | 22 | objective-c|ios | 3,448 | <p>So that it will only be constructed once. If it's not static, you'll be making one every time the message is sent (which is a lot)</p> |
4,724,904 | How to change style of iframe content cross-domain? | <p>I want to make background color black and text color white for the content inside iframe from its default of normal white background and black text.
The iframe src attribute points to different domain to which I have no access or cannot place any file or stylesheets in that domain. So given these conditions is it possible to make just these style changes in the iframe content and if so then how?</p> | 4,724,942 | 3 | 0 | null | 2011-01-18 13:58:05.787 UTC | 2 | 2015-03-27 11:48:45.043 UTC | null | null | null | null | 574,122 | null | 1 | 22 | javascript|html|css|iframe | 42,391 | <p>The only possibility would be to load the iframe content through a proxy of yours and modify the HTML content. You can not access iframes from another domain via JavaScript.</p> |
14,666,852 | jQuery form validation - CSS of error label | <p>I am using the exact same example used on the jquery website for a simple form validation;
<a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">http://docs.jquery.com/Plugins/Validation</a></p>
<p>There is one thing I don't understand though, the error message in the example is displayed to the right of each input field. I want to display the errors under each input field. How does that work? I tried playing around with the width and padding but no luck so far.</p>
<p>The CSS code I am using is slightly altered, but still very simple;</p>
<pre><code>label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: 0px; vertical-align: bottom; }
p { clear: both; }
fieldset {position: absolute; left: 450px; width: 400px; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</code></pre>
<p>Here is the jfiddle <a href="http://jsfiddle.net/nBv7v/" rel="noreferrer">http://jsfiddle.net/nBv7v/</a></p> | 14,666,984 | 4 | 2 | null | 2013-02-02 21:45:04.277 UTC | 3 | 2016-12-10 13:22:12.183 UTC | 2013-02-02 22:07:23.757 UTC | null | 1,889,273 | null | 1,319,067 | null | 1 | 6 | jquery|css|jquery-validate | 55,375 | <blockquote>
<p>Quote OP: "the error message in the example is displayed to the right
of each input field. I want to display the errors under each input
field. How does that work?"</p>
</blockquote>
<p>You can simply change the default element from <code>label</code> to <code>div</code> by using the <a href="http://docs.jquery.com/Plugins/Validation/validate#toptions"><code>errorElement</code> option</a>. Since <code>div</code> is "block-level", it will automatically wrap to another line.</p>
<pre><code>$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
errorElement: 'div',
// your other rules and options
});
});
</code></pre>
<p><strong>Working Demo:</strong> <a href="http://jsfiddle.net/xvAPY/">http://jsfiddle.net/xvAPY/</a></p>
<p>You don't even have to mess with the CSS. But if you need to change anything, target them with <code>div.error</code>.</p>
<pre><code>div.error {
/* your rules */
}
</code></pre>
<hr>
<p>See <a href="http://docs.jquery.com/Plugins/Validation/validate#toptions">the documentation for more Validate plugin options</a>.</p> |
4,702,852 | PHP: Testing whether three variables are equal | <p>I've never come across this before, but how would you test whether three variables are the same? The following, obviously doesn't work but I can't think of an elegant (and correct) way to write the following:</p>
<p><code>if ($select_above_average === $select_average === $select_below_average) { }</code></p> | 4,702,875 | 5 | 0 | null | 2011-01-15 23:48:06.95 UTC | 4 | 2016-11-28 19:35:39.567 UTC | null | null | null | null | 509,271 | null | 1 | 48 | php|variables|equality | 34,107 | <pre><code>if ((a == b) && (b == c)) {
... they're all equal ...
}
</code></pre>
<p>by the <a href="http://en.wikipedia.org/wiki/Transitive_relation" rel="noreferrer">transitive relation</a></p> |
4,501,196 | Keygen tag in HTML5 | <p>So I came across this new tag in HTML5, <code><keygen></code>. I can't quite figure out what it is for, how it is applied, and how it might affect browser behavior. </p>
<p>I understand that this tag is for form encryption, but what is the difference between <code><keygen></code> and having a SSL certificate for your domain. Also, what is the <code>challenge</code> attribute? </p>
<p>I'm not planning on using it as it is far from implemented in an acceptable range of browsers, but I am curious as to what EXACTLY this tag does. All I can find is vague cookie-cutter documentation with no real examples of usage.</p>
<hr>
<p><em>Edit:</em> </p>
<p>I have found a VERY informative document, <a href="https://web.archive.org/web/20160409081411/https://lists.whatwg.org/pipermail/whatwg-whatwg.org/attachments/20080714/07ea5534/attachment.txt" rel="nofollow noreferrer">here</a>. This runs through both client-side and server-side implementation of the keygen tag.</p>
<p>I am still curious as to what the benefit of this over a domain SSL certificate would be.</p> | 4,852,285 | 6 | 4 | null | 2010-12-21 16:00:03.007 UTC | 18 | 2020-04-25 18:07:01.26 UTC | 2018-02-06 01:32:45.993 UTC | user1585455 | null | null | 449,805 | null | 1 | 75 | security|html|ssl | 32,401 | <p>SSL is about "server identification" or "server AND client authentication (mutual authentication)".</p>
<p>In most cases only the server presents its server-certificate during the SSL handshake so that you could make sure that this really is the server you expect to connect to. In some cases the server also wants to verify that <em>you</em> really are the person you pretend to be. For this you need a client-certificate.</p>
<p>The <code><keygen></code> tag generates a public/private key pair and then creates a certificate request. This certificate request will be sent to a Certificate Authority (CA). The CA creates a certificate and sends it back to the browser. Now you are able to use this certificate for user authentication.</p> |
4,481,388 | Why does MYSQL higher LIMIT offset slow the query down? | <p>Scenario in short: A table with more than 16 million records [2GB in size]. The higher LIMIT offset with SELECT, the slower the query becomes, when using ORDER BY *primary_key*</p>
<p>So </p>
<pre><code>SELECT * FROM large ORDER BY `id` LIMIT 0, 30
</code></pre>
<p>takes far less than </p>
<pre><code>SELECT * FROM large ORDER BY `id` LIMIT 10000, 30
</code></pre>
<p>That only orders 30 records and same eitherway. So it's not the overhead from ORDER BY.<br>
Now when fetching the latest 30 rows it takes around 180 seconds. How can I optimize that simple query?</p> | 4,502,426 | 6 | 3 | null | 2010-12-19 03:01:04.69 UTC | 112 | 2020-11-30 16:15:17.933 UTC | 2013-03-27 20:25:35.86 UTC | null | 212,555 | null | 547,435 | null | 1 | 212 | mysql|performance|sql-order-by|limit | 98,205 | <p>It's normal that higher offsets slow the query down, since the query needs to count off the first <code>OFFSET + LIMIT</code> records (and take only <code>LIMIT</code> of them). The higher is this value, the longer the query runs.</p>
<p>The query cannot go right to <code>OFFSET</code> because, first, the records can be of different length, and, second, there can be gaps from deleted records. It needs to check and count each record on its way.</p>
<p>Assuming that <code>id</code> is the primary key of a MyISAM table, or a unique non-primary key field on an InnoDB table, you can speed it up by using this trick:</p>
<pre><code>SELECT t.*
FROM (
SELECT id
FROM mytable
ORDER BY
id
LIMIT 10000, 30
) q
JOIN mytable t
ON t.id = q.id
</code></pre>
<p>See this article:</p>
<ul>
<li><a href="http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/" rel="noreferrer"><strong>MySQL ORDER BY / LIMIT performance: late row lookups</strong></a></li>
</ul> |
4,589,184 | What are the risks with Project Lombok? | <p>I'm coming up with performance goals for the new year, and I thought I'd be fun to put a goal to reduce the size of the code base, especially boilerplate. One action I've come up with to address this is to use <a href="http://projectlombok.org/" rel="noreferrer">Project Lombok</a> to make beans as short as they should be. But I have a habit of overlooking downsides to new software and approaches, so I'm relying on the Stack Overflow community: Can anyone tell me why Lombok is a bad idea?</p> | 4,589,243 | 8 | 3 | null | 2011-01-03 22:55:06.333 UTC | 11 | 2022-01-20 11:20:49.083 UTC | 2016-01-06 22:34:21.917 UTC | user4639281 | null | null | 9,947 | null | 1 | 47 | java|jakarta-ee|boilerplate|lombok | 25,589 | <p>A major downside is IDE support. Since Lombok is not actually a language change, and since your IDE only understands java, you will need an IDE that supports Lombok to get things working right. As of now, <s>that's only Eclipse</s> that includes Eclipse and IntelliJ. If you use eclipse that might be ok, but remember that you are making a decision for future developers as well. </p>
<p>I'd suggest you consider moving some of your code into a less ceremonial language such as groovy. We've had success moving some of our business logic and models into groovy and it works really smoothly.</p> |
4,251,124 | Inserting JSON into MySQL using Python | <p>I have a JSON object in Python. I am Using Python DB-API and SimpleJson. I am trying to insert the json into a MySQL table.</p>
<p>At moment am getting errors and I believe it is due to the single quotes '' in the JSON Objects. </p>
<p>How can I insert my JSON Object into MySQL using Python?</p>
<p>Here is the error message I get:</p>
<pre><code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code></pre>
<p>Another error for reference</p>
<pre><code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code></pre>
<p>Here is a link to the code that I am using <a href="http://pastebin.com/q5QSfYLa" rel="noreferrer">http://pastebin.com/q5QSfYLa</a></p>
<pre><code>#!/usr/bin/env python
try:
import json as simplejson
except ImportError:
import simplejson
import twitstream
import MySQLdb
USER = ''
PASS = ''
USAGE = """%prog"""
conn = MySQLdb.connect(host = "",
user = "",
passwd = "",
db = "")
# Define a function/callable to be called on every status:
def callback(status):
twitdb = conn.cursor ()
twitdb.execute ("INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)",(status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status))
# print status
#print "%s:\t%s\n" % (status.get('user', {}).get('screen_name'), status.get('text'))
if __name__ == '__main__':
# Call a specific API method from the twitstream module:
# stream = twitstream.spritzer(USER, PASS, callback)
twitstream.parser.usage = USAGE
(options, args) = twitstream.parser.parse_args()
if len(args) < 1:
args = ['Blackberry']
stream = twitstream.track(USER, PASS, callback, args, options.debug, engine=options.engine)
# Loop forever on the streaming call:
stream.run()
</code></pre> | 4,316,867 | 9 | 5 | null | 2010-11-22 23:07:03.88 UTC | 14 | 2020-10-07 05:30:34.203 UTC | 2015-05-27 03:52:25.323 UTC | null | 445,131 | null | 161,570 | null | 1 | 24 | python|mysql|json|python-db-api | 89,194 | <p>use json.dumps(json_value) to convert your json object(python object) in a json string that you can insert in a text field in mysql</p>
<p><a href="http://docs.python.org/library/json.html" rel="noreferrer">http://docs.python.org/library/json.html</a></p> |
4,308,262 | Calculate compass bearing / heading to location in Android | <p>I want to display an arrow at my location on a google map view that displays my direction relative to a destination location (instead of north).</p>
<p>a) I have calculated north using the sensor values from the magnetometer and accelerometer. I know this is correct because it lines up with the compass used on the Google Map view.</p>
<p>b) I have calculated the initial bearing from my location to the destination location by using myLocation.bearingTo(destLocation); </p>
<p>I'm missing the last step; from these two values (a & b) what formula do I use to get the direction in which the phone is pointing relative to the destination location?</p>
<p>Appreciate any help for an addled mind! </p> | 4,316,717 | 11 | 3 | null | 2010-11-29 21:25:09.437 UTC | 69 | 2022-07-07 07:19:44.53 UTC | null | null | null | null | 227,228 | null | 1 | 72 | android|location|compass-geolocation|heading|bearing | 133,447 | <p>Ok I figured this out. For anyone else trying to do this you need:</p>
<p>a) heading: your heading from the hardware compass. This is in degrees east of <strong>magnetic</strong> north</p>
<p>b) bearing: the bearing from your location to the destination location. This is in degrees east of <strong>true</strong> north.</p>
<pre><code>myLocation.bearingTo(destLocation);
</code></pre>
<p>c) declination: the difference between true north and magnetic north</p>
<p>The heading that is returned from the magnetometer + accelermometer is in degrees east of true (magnetic) north (-180 to +180) so you need to get the difference between north and magnetic north for your location. This difference is variable depending where you are on earth. You can obtain by using GeomagneticField class.</p>
<pre><code>GeomagneticField geoField;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
geoField = new GeomagneticField(
Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis()
);
...
}
}
</code></pre>
<p>Armed with these you calculate the angle of the arrow to draw on your map to show where you are facing in relation to your destination object rather than true north.</p>
<p>First adjust your heading with the declination:</p>
<pre><code>heading += geoField.getDeclination();
</code></pre>
<p>Second, you need to offset the direction in which the phone is facing (heading) from the target destination rather than true north. This is the part that I got stuck on. The heading value returned from the compass gives you a value that describes where magnetic north is (in degrees east of true north) in relation to where the phone is pointing. So e.g. if the value is -10 you know that magnetic north is 10 degrees to your left. The bearing gives you the angle of your destination in degrees east of true north. So after you've compensated for the declination you can use the formula below to get the desired result:</p>
<pre><code>heading = myBearing - (myBearing + heading);
</code></pre>
<p>You'll then want to convert from degrees east of true north (-180 to +180) into normal degrees (0 to 360):</p>
<pre><code>Math.round(-heading / 360 + 180)
</code></pre> |
14,689,348 | Mocking a Spy method with Mockito | <p>I am writing a unit test for a <code>FizzConfigurator</code> class that looks like:</p>
<pre><code>public class FizzConfigurator {
public void doFoo(String msg) {
doWidget(msg, Config.ALWAYS);
}
public void doBar(String msg) {
doWidget(msg, Config.NEVER);
}
public void doBuzz(String msg) {
doWidget(msg, Config.SOMETIMES);
}
public void doWidget(String msg, Config cfg) {
// Does a bunch of stuff and hits a database.
}
}
</code></pre>
<p>I'd like to write a simple unit test that stubs the <code>doWidget(String,Config)</code> method (so that it doesn't actually fire and hit the database), but that allows me to <em>verify</em> that calling <code>doBuzz(String)</code> ends up executing <code>doWidget</code>. Mockito seems like the right tool for the job here.</p>
<pre><code>public class FizzConfiguratorTest {
@Test
public void callingDoBuzzAlsoCallsDoWidget() {
FizzConfigurator fixture = Mockito.spy(new FizzConfigurator());
Mockito.when(fixture.doWidget(Mockito.anyString(), Config.ALWAYS)).
thenThrow(new RuntimeException());
try {
fixture.doBuzz("This should throw.");
// We should never get here. Calling doBuzz should invoke our
// stubbed doWidget, which throws an exception.
Assert.fail();
} catch(RuntimeException rte) {
return; // Test passed.
}
}
}
</code></pre>
<p>This <em>seems</em> like a good gameplan (to me at least). But when I actually go to code it up, I get the following compiler error on the 2nd line inside the test method (the <code>Mockito.when(...)</code> line:</p>
<blockquote>
<p>The method when(T) in the type Mockito is not applicable for the arguments (void)</p>
</blockquote>
<p>I see that Mockito can't mock a method that returns <code>void</code>. So I ask:</p>
<ol>
<li>Am I approaching this test setup correctly? Or is there a better, Mockito-recommended, way of testing that <code>doBuzz</code> calls <code>doWidget</code> under the hood? And</li>
<li>What can I do about mocking/stubbing <code>doWidget</code> as it is the most critical method of my entire <code>FizzConfigurator</code> class?</li>
</ol> | 14,690,422 | 4 | 0 | null | 2013-02-04 14:56:09.17 UTC | 5 | 2021-05-28 07:36:26.847 UTC | null | null | null | user1768830 | null | null | 1 | 14 | java|unit-testing|junit|mocking|mockito | 53,714 | <p>I wouldn't use exceptions to test that, but verifications. And another problem is that you can't use <code>when()</code> with methods returning void.</p>
<p>Here's how I would do it:</p>
<pre><code>FizzConfigurator fixture = Mockito.spy(new FizzConfigurator());
doNothing().when(fixture).doWidget(Mockito.anyString(), Mockito.<Config>any()));
fixture.doBuzz("some string");
Mockito.verify(fixture).doWidget("some string", Config.SOMETIMES);
</code></pre> |
14,717,217 | Converting from a character to a numeric data frame | <p>I have a character data frame in R which has <code>NaN</code>s in it. I need to remove any row with a <code>NaN</code> and then convert it to a numeric data frame.</p>
<p>If I just do as.numeric on the data frame, I run into the following</p>
<pre><code>Error: (list) object cannot be coerced to type 'double'
1:
0:
</code></pre> | 14,717,373 | 2 | 1 | null | 2013-02-05 21:24:45.367 UTC | 3 | 2015-12-03 00:02:49.32 UTC | 2015-12-03 00:02:49.32 UTC | null | 4,370,109 | null | 1,727,485 | null | 1 | 15 | r|dataframe | 79,819 | <p>As @thijs van den bergh points you to, </p>
<pre><code>dat <- data.frame(x=c("NaN","2"),y=c("NaN","3"),stringsAsFactors=FALSE)
dat <- as.data.frame(sapply(dat, as.numeric)) #<- sapply is here
dat[complete.cases(dat), ]
# x y
#2 2 3
</code></pre>
<p>Is <em>one</em> way to do this.</p>
<p>Your error comes from trying to make a <code>data.frame</code> numeric. The <code>sapply</code> option I show is instead making each column vector numeric.</p> |
14,845,048 | Client-side Javascript app - url routing with no hash tag | <p>I'm working on a new client-side only app with the latest version of Ember.js. There is a single PHP page which builds the scripts, css, template files, etc. and delivers it all into index.php. I'm using an htaccess directive so that all requests are rewritten to /index.php. The PHP is only there to conveniently package the Javascript, as far as I'm concerned.</p>
<p>Currently, routes in the browser look like this and work just fine.</p>
<pre><code>/#/about
/#/favorites
/#/etc
/#/posts/5/edit
</code></pre>
<p>However, I would like them to look like this - which do not work just fine.</p>
<pre><code>/about
/favorites
/etc
/posts/5/edit
</code></pre>
<p>The exact same client-code is still delivered with the second option - but it always hits the index route handler. I've seen client-side apps pull this off before - what am I missing? Do I need to have matching route handlers on the PHP side?</p>
<p>Edit: I'm looking for a specific answer of how to approach this. The web is full of "oh - you just do this" information that leaves everybody else scratching their heads.</p> | 16,554,242 | 4 | 0 | null | 2013-02-13 01:34:22.043 UTC | 15 | 2014-04-28 19:14:59.823 UTC | 2013-02-13 17:23:16.67 UTC | null | 338,632 | null | 338,632 | null | 1 | 23 | ember.js|url-routing|client-side|javascript-framework | 9,093 | <p>In Ember.js (version 1.0.0rc3) this can be accomplished by using the <a href="http://emberjs.com/guides/routing/specifying-the-location-api/" rel="nofollow noreferrer">Ember.js location API</a>:</p>
<pre><code>App.Router.reopen({
location: 'history'
});
</code></pre>
<p>And then setting the web server to redirect traffic to the Ember application.</p>
<p>To give a concrete example here is a basic Apache <code>.htaccess</code> file redirecting traffic to the Ember application located in index.html:</p>
<pre><code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html#$1 [L]
</code></pre>
<p>As <a href="https://stackoverflow.com/a/21704913/657661">Alex White</a> points out Apache 2.2.16 and above supports a simpler configuration for redirecting traffic to a single target:</p>
<pre><code>FallbackResource /index.html
</code></pre>
<p>The <a href="https://httpd.apache.org/docs/trunk/mod/mod_dir.html#FallbackResource" rel="nofollow noreferrer">FallbackResource</a> is part of the <code>mod_dir</code> module and requires <code>AllowOverride Indexes</code> to be set.</p>
<p>Make sure to test the application routes thoroughly. One common error is <code>Uncaught SyntaxError: Unexpected token <</code>, which is caused by using relative links to CSS and JS files. Prepend them with a <code>/</code> mark to make them absolute.</p>
<p><strong>This functionality is <a href="http://caniuse.com/#search=pushstate" rel="nofollow noreferrer">not supported in Internet Explorer <10</a>.</strong></p> |
14,614,946 | How to turn a vector into a matrix in R? | <p>I have a vector with 49 numeric values. I want to have a 7x7 numeric matrix instead. </p>
<p>Is there some sort of convenient automatic conversion statement I can use, or do I have to do 7 separate column assignments of the correct vector subsets to a new matrix? I hope that there is something like the oposite of <code>c(myMatrix)</code>, with the option of giving the number of rows and/or columns I want to have, of course. </p> | 14,614,969 | 2 | 4 | null | 2013-01-30 22:19:48.137 UTC | 6 | 2013-01-30 22:35:13.147 UTC | null | null | null | null | 553,434 | null | 1 | 78 | r|vector|matrix | 141,338 | <p>Just use <code>matrix</code>:</p>
<pre><code>matrix(vec,nrow = 7,ncol = 7)
</code></pre>
<p>One advantage of using <code>matrix</code> rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the <code>byrow</code> argument in <code>matrix</code>.</p> |
25,978,771 | What is regex for currency symbol? | <p>In java I can use the regex : <a href="http://www.regular-expressions.info/unicode.html"><code>\p{Sc}</code></a> for detecting currency symbol in text. What is the equivalent in Python? </p> | 25,978,807 | 2 | 0 | null | 2014-09-22 16:25:09.77 UTC | 5 | 2020-07-10 15:21:06.567 UTC | 2014-09-22 23:28:41.273 UTC | user212218 | null | null | 2,688,733 | null | 1 | 29 | python|regex | 7,081 | <p>You can use the unicode category if you use <a href="https://pypi.python.org/pypi/regex"><code>regex</code></a> package:</p>
<pre><code>>>> import regex
>>> regex.findall(r'\p{Sc}', '$99.99 / €77') # Python 3.x
['$', '€']
</code></pre>
<hr>
<pre><code>>>> regex.findall(ur'\p{Sc}', u'$99.99 / €77') # Python 2.x (NoteL unicode literal)
[u'$', u'\xa2']
>>> print _[1]
¢
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Alterantive way using <a href="https://docs.python.org/3/library/unicodedata.html#unicodedata.category"><code>unicodedata.category</code></a>:</p>
<pre><code>>>> import unicodedata
>>> [ch for ch in '$99.99 / €77' if unicodedata.category(ch) == 'Sc']
['$', '€']
</code></pre> |
7,029,944 | When should I use the := operator in data.table? | <p><code>data.table</code> objects now have a := operator. What makes this operator different from all other assignment operators? Also, what are its uses, how much faster is it, and when should it be avoided?</p> | 7,030,140 | 1 | 0 | null | 2011-08-11 17:01:50.06 UTC | 37 | 2018-11-13 12:57:29.07 UTC | 2018-11-13 12:57:29.07 UTC | null | 2,270,475 | null | 636,656 | null | 1 | 89 | r|data.table|colon-equals | 17,419 | <p>Here is an example showing 10 minutes reduced to 1 second (from NEWS on <a href="http://datatable.r-forge.r-project.org/">homepage</a>). It's like subassigning to a <code>data.frame</code> but doesn't copy the entire table each time.</p>
<pre><code>m = matrix(1,nrow=100000,ncol=100)
DF = as.data.frame(m)
DT = as.data.table(m)
system.time(for (i in 1:1000) DF[i,1] <- i)
user system elapsed
287.062 302.627 591.984
system.time(for (i in 1:1000) DT[i,V1:=i])
user system elapsed
1.148 0.000 1.158 ( 511 times faster )
</code></pre>
<p>Putting the <code>:=</code> in <code>j</code> like that allows more idioms :</p>
<pre><code>DT["a",done:=TRUE] # binary search for group 'a' and set a flag
DT[,newcol:=42] # add a new column by reference (no copy of existing data)
DT[,col:=NULL] # remove a column by reference
</code></pre>
<p>and :</p>
<pre><code>DT[,newcol:=sum(v),by=group] # like a fast transform() by group
</code></pre>
<p>I can't think of any reasons to avoid <code>:=</code> ! Other than, inside a <code>for</code> loop. Since <code>:=</code> appears inside <code>DT[...]</code>, it comes with the small overhead of the <code>[.data.table</code> method; e.g., S3 dispatch and checking for the presence and type of arguments such as <code>i</code>, <code>by</code>, <code>nomatch</code> etc. So for inside <code>for</code> loops, there is a low overhead, direct version of <code>:=</code> called <code>set</code>. See <code>?set</code> for more details and examples. The disadvantages of <code>set</code> include that <code>i</code> must be row numbers (no binary search) and you can't combine it with <code>by</code>. By making those restrictions <code>set</code> can reduce the overhead dramatically.</p>
<pre><code>system.time(for (i in 1:1000) set(DT,i,"V1",i))
user system elapsed
0.016 0.000 0.018
</code></pre> |
22,486,709 | SCSS divide operator not compiling | <p>I am using Sublime Text 2 and LiveReload to compile my <code>.scss</code> file. I also tried codekit with the same problem.</p>
<p>Using <code>+</code> and <code>-</code> work no problem, but <code>*</code> and <code>/</code> don't compile.</p>
<pre><code>font-size: 30px / 2px; doesn't compile to font-size: 15px;
</code></pre>
<p>but</p>
<pre><code>font-size: 30px + 2px; does compile to font-size: 32px;
</code></pre>
<p>Any ideas? The code hinting also doesn't seem to be working for the multiply and divide operators, could it be a package conflict? Seems unlikely.</p> | 22,486,831 | 1 | 0 | null | 2014-03-18 17:29:13.79 UTC | 3 | 2020-07-15 02:24:04.65 UTC | 2020-07-15 02:24:04.65 UTC | null | 6,331,353 | null | 3,434,295 | null | 1 | 30 | sass | 14,057 | <p>Put it in parenthesis so SCSS understands you want it to do an arithmetic operation. Also, you do not want to divide px by another px number as this will result in a unitless number.</p>
<p>This is what you are looking for:</p>
<pre><code>div {
font-size: (30px / 2)
}
</code></pre> |
49,962,542 | Why Google play services dependency automatically added com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE permission | <p>Recently i have updated google play services dependency version to 15.0.0 it automatically added the below permission.</p>
<p>i don't no wheather i need this <a href="https://android-developers.googleblog.com/2017/11/google-play-referrer-api-track-and.html" rel="noreferrer">Google Play Referrer API</a> permission or not</p>
<pre><code><uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE" />
</code></pre>
<p>I'm able to remove this permission</p>
<pre><code> <uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE"
tools:node="remove" />
</code></pre>
<p>but i need know which dependency will need BIND_GET_INSTALL_REFERRER_SERVICE permission does the dependency really need this permission or not.</p>
<p>App Level Gradle</p>
<pre><code>dependencies {
ext {
support_library_version = '27.0.2'
google_play_services_version = '15.0.0'
}
implementation 'com.android.support:multidex:1.0.3'
implementation "com.android.support:appcompat-v7:${support_library_version}"
implementation "com.android.support:design:${support_library_version}"
implementation "com.android.support:recyclerview-v7:${support_library_version}"
implementation "com.android.support:cardview-v7:${support_library_version}"
implementation "com.google.android.gms:play-services-analytics:${google_play_services_version}"
implementation "com.google.android.gms:play-services-gcm:${google_play_services_version}"
implementation "com.google.firebase:firebase-messaging:${google_play_services_version}"
implementation "com.google.firebase:firebase-core:${google_play_services_version}"
implementation "com.google.firebase:firebase-ads:${google_play_services_version}"
}
</code></pre>
<p>Project Level Gradle</p>
<pre><code>dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath 'com.google.gms:google-services:3.2.0'
}
</code></pre>
<p><strong>Note:</strong> For referrer tracking am already using google analytics </p>
<pre><code><service android:name="com.google.android.gms.analytics.CampaignTrackingService"
android:enabled="true"
android:exported="false" />
</code></pre> | 50,148,593 | 1 | 4 | null | 2018-04-22 04:39:09.87 UTC | 5 | 2019-01-29 22:34:43.05 UTC | 2018-09-22 11:51:25.763 UTC | null | 989,349 | null | 3,182,144 | null | 1 | 26 | android|android-gradle-plugin|google-play-services|install-referrer | 41,613 | <p>Won't Fix (Intended behavior)</p>
<p>For More details check <a href="https://issuetracker.google.com/issues/78380811#comment22" rel="noreferrer">Google Issue Tracker</a></p> |
22,026,984 | Trying to disable Chrome same origin policy | <p>I'm trying to follow a melonJS tutorial. It says I should disable cross-origin request using one of two methods:</p>
<p><em><strong></em>--disable-web-security</strong></p>
<p><strong>--allow-file-access-from-files**</strong></p>
<p>I've tried both of these in my command prompt as such:</p>
<pre><code>C:\Users\danniu>C:\Users\danniu\AppData\Local\Google\Chrome\Application\Chrome.e
xe --allow-file-access-from-files
C:\Users\danniu>C:\Users\danniu\AppData\Local\Google\Chrome\Application\Chrome.e
xe --disable-web-security
</code></pre>
<p>When I try to run the game in Chrome I'm still getting this error:</p>
<p><code>XMLHttpRequest cannot load file:///C:/Users/danniu/Desktop/JavaScript/melonJS/data/map/area01.tmx. Cross origin requests are only supported for HTTP.</code> </p>
<p>What am I doing wrong?</p>
<p>Thanks</p> | 22,027,002 | 4 | 0 | null | 2014-02-25 21:47:39.923 UTC | 6 | 2022-03-29 08:12:27.293 UTC | null | null | null | null | 507,624 | null | 1 | 9 | javascript|security|google-chrome|same-origin-policy | 82,788 | <p>You need to use both arguments. This is how I run it on my mac.</p>
<pre><code>open -a Google\ Chrome --args --disable-web-security -–allow-file-access-from-files
</code></pre>
<p>This is how it should be for windows:</p>
<pre><code>"C:\PathTo\Chrome.exe" –allow-file-access-from-files -disable-web-security
</code></pre> |
2,354,742 | How to make buttons cover full screen width in Android Linear Layout? | <p>I have following three button in a Linear Layout with width <code>fill_parent</code>.</p>
<p>How can I set the width of these buttons to equally cover the whole screen area?</p>
<pre><code><Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnReplyMessage"
android:gravity="left"
android:text="Reply"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnMarkAsUnread"
android:gravity="left"
android:text="Mark as unread"
/>
<ImageButton
android:id="@+id/btnDeleteMessage"
android:src="@drawable/imgsearch"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
/>
</code></pre> | 2,354,759 | 3 | 0 | null | 2010-03-01 09:10:37.743 UTC | 4 | 2022-01-29 17:01:57.683 UTC | 2022-01-29 17:01:57.683 UTC | null | 10,749,567 | null | 249,991 | null | 1 | 17 | android|layout|width|android-linearlayout | 40,968 | <p>Give all buttons the following properties</p>
<pre><code>android:layout_width="fill_parent"
android:layout_weight="1"
</code></pre>
<p><code>fill_parent</code> tells them to consume as much width as possible, and <code>weight</code> determines how that width shall be distributed, when more than one control are competing for the same space. (Try playing around with different values of <code>weight</code> for each button to see how that works)</p> |
2,891,523 | rails best practices where to place unobtrusive javascript | <p>my rails applications (all 2.3.5) use a total mix of inline javascript, rjs, prototype and jquery. Let's call it learning or growing pains. Lately i have been more and more infatuated with unobtrusive javascript. It makes your html clean, in the same way css cleaned it up.</p>
<p>But most examples i have seen are small examples, and they put all javascript(jquery) inside application.js</p>
<p>Now i have a pretty big application, and i am thinking up ways to structure my js. I like somehow that my script is still close to the view, so i am thinking something like</p>
<pre><code>orders.html.erb
orders.js
</code></pre>
<p>where orders.js contains the unobtrusive javascript specific to that view. But maybe that's just me being too conservative :)</p>
<p>I have read some posts by Yehuda Katz about this very problem <a href="http://yehudakatz.com/2007/05/17/jquery-on-rails-a-fresh-approach/" rel="noreferrer">here</a> and <a href="http://yehudakatz.com/2007/05/25/10/" rel="noreferrer">here</a>, where he tackles this problem. It will go through your js-files and only load those relevant to your view. But alas i can't find a current implementation.</p>
<p>So my questions:</p>
<ul>
<li>how do you best structure your unobtrusive javascript; manage your code, how do you make sure that it is obvious from the html what something is supposed to do. I guess good class names go a long way :)</li>
<li>how do you arrange your files, load them all in? just a few? do you use <code>content_for :script</code> or <code>javascript_include_tag</code> in your view to load the relevant scripts. Or ... ?</li>
<li>do you write very generic functions (like a delete), with parameters (add extra attributes?), or do you write very specific functions (DRY?). I know in Rails 3 there is a standard set, and everything is unobtrusive there. But how to start in Rails 2.3.5?</li>
</ul>
<p>In short: what are the best practices for doing unobtrusive javascript in rails? :)</p> | 2,891,894 | 3 | 0 | null | 2010-05-23 11:31:19.467 UTC | 12 | 2014-09-30 02:53:09.573 UTC | 2010-05-23 13:30:07 UTC | null | 17,174 | null | 216,513 | null | 1 | 31 | javascript|jquery|ruby-on-rails|ruby|unobtrusive-javascript | 3,124 | <p>I do not think there is one best practice, but I'll let you know what I do.</p>
<ol>
<li><p>I have a series of js files each for with their own purpose in the <code>public/javascripts/</code> directory. Some examples could be <code>utility.js</code> <code>chat.js</code> <code>shopping_basket.js</code> and so on. </p></li>
<li><p>I use <a href="http://github.com/sbecker/asset_packager" rel="nofollow noreferrer">asset packager</a> and define one big fat collection for all my general use functionality and another for admin only functionality. Round trips to the server cost way too much. I basically include all the js in on first page load minified into one blob (in general) </p></li>
<li><p>I allow basic <code>$(document).ready</code> hooks inline in the pages, and keep them really short.</p></li>
<li><p>Data that my js files needs to access is rendered inline with the page. (Usually in the DOM, sometimes as vars - Eg. <code>var xyz = 100</code>)</p></li>
<li><p>I will usually develop my controllers with javascript off (and make sure it all works), then I turn it on and sprinkle a few <code>if request.xhr?</code> where needed.</p></li>
</ol>
<hr>
<p>Keep in mind, Rail 3.1 introduces a built-in best practice, see: <a href="http://guides.rubyonrails.org/asset_pipeline.html" rel="nofollow noreferrer">http://guides.rubyonrails.org/asset_pipeline.html</a> - on a personal note I have had performance and configuration issues with the new pipeline, however many others have had great success with it. </p> |
2,657,658 | Wanted: Command line HTML5 beautifier | <h3>Wanted</h3>
<p>A command line HTML5 beautifier running under Linux.</p>
<h3>Input</h3>
<p>Garbled, ugly HTML5 code. Possibly the result of multiple templates. You don't love it, it doesn't love you.</p>
<h3>Output</h3>
<p>Pure beauty. The code is nicely indented, has enough line breaks, cares for it's whitespace. Rather than viewing it in a webbrowser, you would like to display the code on your website directly.</p>
<h3>Suspects</h3>
<ul>
<li><strong>tidy</strong> does too much (heck, it alters my doctype!), and it doesn't work well with HTML5. Maybe there is a way to make it cooperate and not alter <em>anything</em>?</li>
<li><strong>vim</strong> does too little. It only indents. I want the program to add and remove line breaks, and to play with the whitespace inside of tags.</li>
</ul>
<h2>DEAD OR ALIVE!</h2> | 8,320,059 | 4 | 5 | null | 2010-04-17 07:41:50 UTC | 20 | 2019-02-05 02:11:55.5 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 248,734 | null | 1 | 76 | html|command-line|indentation|pretty-print | 20,866 | <p>HTML Tidy has been forked by the w3c and now has support for HTML5 validation.</p>
<p><a href="https://github.com/w3c/tidy-html5" rel="noreferrer">https://github.com/w3c/tidy-html5</a></p> |
2,470,089 | javascript getElementById and convert it to String | <p>is there a way to convert a javascript HTML object to a string?
i.e.</p>
<pre><code>var someElement = document.getElementById("id");
var someElementToString = someElement.toString();
</code></pre>
<p>thanks a lot in advance</p> | 2,470,148 | 5 | 0 | null | 2010-03-18 13:27:19.687 UTC | 1 | 2020-05-30 15:30:05.577 UTC | null | null | null | null | 275,890 | null | 1 | 8 | javascript | 51,206 | <p>If you want a string representation of the entire tag then you can use <code>outerHTML</code> for browsers that support it:</p>
<pre><code>var someElementToString = someElement.outerHTML;
</code></pre>
<p>For other browsers, <a href="https://stackoverflow.com/questions/1700870/how-do-i-do-outerhtml-in-firefox">apparently you can use XMLSerializer</a>:</p>
<pre><code>var someElement = document.getElementById("id");
var someElementToString;
if (someElement.outerHTML)
someElementToString = someElement.outerHTML;
else if (XMLSerializer)
someElementToString = new XMLSerializer().serializeToString(someElement);
</code></pre> |
31,976,527 | Why does AWS RDS Aurora have the option of "Multi-AZ Deployment" when it does replication across different zones already by default? | <p>When launching an Aurora instance I have the option of "Multi-AZ Deployment", which it describes as "Specifies if the DB Instance should have a standby deployed in another Availability Zone."</p>
<p>However the Aurora documentation states that Aurora already automatically spreads the database across different availability zones?</p>
<p>Additionally, what is the difference between an Aurora Multi-AZ standby and an ordinary Aurora replica. Is that that an ordinary replica can be read from increasing performance whereas a standby cannot be read from?</p> | 31,978,929 | 3 | 0 | null | 2015-08-12 22:31:41.923 UTC | 4 | 2022-02-23 13:22:51.23 UTC | null | null | null | null | 964,634 | null | 1 | 41 | amazon-web-services|amazon-rds|amazon-aurora | 19,438 | <p>Aurora replicates your <em>data</em> across three availability zones, at the storage layer... but the database server instance, itself, is still a virtual machine running on a single physical machine that is located in a single availability zone. </p>
<p>The Aurora storage layer is outside that instance, and is able to let access continue uninterrupted without data loss, even in the event of the loss of up to two AZs, but the loss of the zone containing the db instance will still cause an outage for you, if you only have a single Aurora instance in your cluster (1 master, 0 replicas). Loss of an entire availability zone is one of those things that is highly improbable but not impossible. Your db instance is still a single point of failure when you only have one.</p>
<p>Multi-AZ makes allowance for a complete redundant database instance, in a different AZ, which will automatically take over for the primary within one minute, if it works as designed, in case of the loss of the AZ hosting the primary instance or a catastrophic failure of the primary instance. It's a second virtual machine, on a second physical machine, in a second availability zone. It's always running, but you can't access it. It's in the background, managed and monitored by the RDS infrastructure, but it is only accessible to you in the case of primary instance failure. The secondary machine can also be used to reduce downtime in the event of a software upgrade or maintenance event on the primary. When failover occurs, if you are using DNS to connect to your database (as you should), you'll find that the DNS entry is automatically pointed to the secondary.</p>
<p>Contrast this to a read replica, which is accessible all the time and can thus provide a significant performance benefit, by allowing the offloading of reads. Failing over to a replica involves promoting it to become a standalone master (which permanently detaches it from its own former master) and reconfiguring your application to use the alternate endpoint. This, of course, is still faster than recovering from a failure in the master by using a point-in-time snapshot to create a replacement master instance.</p>
<p><a href="https://aws.amazon.com/rds/details/multi-az/" rel="noreferrer">https://aws.amazon.com/rds/details/multi-az/</a></p> |
37,861,500 | BigQuery: convert epoch to TIMESTAMP | <p>I'm trying to range-join two tables, like so</p>
<pre><code>SELECT *
FROM main_table h
INNER JOIN
test.delay_pairs d
ON
d.interval_start_time_utc < h.visitStartTime
AND h.visitStartTime < d.interval_end_time_utc
</code></pre>
<p>where <code>h.visitStartTime</code> is an <code>INT64</code> epoch and <code>d.interval_start_time_utc</code> and <code>d.interval_end_time_utc</code> are proper <code>TIMESTAMP</code>s.</p>
<p>The above fails with</p>
<pre><code>No matching signature for operator < for argument types: TIMESTAMP, INT64. Supported signature: ANY < ANY
</code></pre>
<p>Neither wrapping <code>h.visitStartTime</code> in <code>TIMESTAMP()</code> nor <code>CAST(d.interval_start_time_utc AS INT64)</code> work. How do I make the two comparable in BigQuery's Standard SQL dialect?</p> | 37,863,758 | 2 | 0 | null | 2016-06-16 14:02:20.07 UTC | 4 | 2021-03-03 03:24:47.033 UTC | 2021-03-03 03:24:47.033 UTC | user10563627 | null | null | 1,291,563 | null | 1 | 24 | google-bigquery|timestamp|epoch | 53,239 | <p>You can use <a href="https://cloud.google.com/bigquery/sql-reference/functions-and-operators#additional-date-and-timestamp-conversion-functions" rel="noreferrer">timestamp conversion functions</a> like <code>TIMESTAMP_SECONDS</code>, <code>TIMESTAMP_MILLIS</code>, <code>TIMESTAMP_MICROS</code></p>
<p>for example, assuming your h.visitStartTime is microseconds since the unix epoch</p>
<pre><code>SELECT *
FROM main_table h
INNER JOIN test.delay_pairs d
ON d.interval_start_time_utc < TIMESTAMP_MICROS(h.visitStartTime)
AND TIMESTAMP_MICROS(h.visitStartTime) < d.interval_end_time_utc
</code></pre> |
38,768,454 | Repository size limits for GitHub.com | <p>Lately I have been using GitHub and I am wondering what is the repository size limit for files hosted on github.com?</p> | 38,768,668 | 5 | 1 | null | 2016-08-04 13:17:08.633 UTC | 33 | 2022-08-05 04:22:06.023 UTC | 2022-08-03 18:28:53.263 UTC | null | 832,230 | user6510107 | null | null | 1 | 213 | git|github|repository|storage|limit | 181,006 | <p>From GitHub's <a href="https://help.github.com/articles/what-is-my-disk-quota/" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>GitHub doesn't have any set disk quotas. We try to provide abundant storage for all Git repositories, within reason. Keeping repositories small ensures that our servers are fast and downloads are quick for our users.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>In addition, we place a strict limit of files exceeding 100 MB in size.</p>
</blockquote>
<p>Now for the non-canned part of my answer. GitHub might allow you to store files up to 100MB, but you should also be vigilant to <em>not</em> version binary or other similar blob type files. The reason for this is that Git doesn't handle binaries well, and storage can be a big penalty. So if you find yourself pushing 100MB per file, you should check what type of file you are dealing with.</p> |
48,681,024 | How to set Azure SQL to rebuild indexes automatically? | <p>In on premise SQL databases, it is normal to have a maintenance plan for rebuilding the indexes once in a while, when it is not being used that much.</p>
<p>How can I set it up in Azure SQL DB?</p>
<p>P.S: I tried it before, but since I couldn't find any options for that, I thought maybe they are doing it automatically until I've read <a href="https://blogs.msdn.microsoft.com/dilkushp/2013/07/27/fragmentation-in-sql-azure/" rel="noreferrer">this post</a> and tried:</p>
<pre><code>SELECT
DB_NAME() AS DBName
,OBJECT_NAME(ps.object_id) AS TableName
,i.name AS IndexName
,ips.index_type_desc
,ips.avg_fragmentation_in_percent
FROM sys.dm_db_partition_stats ps
INNER JOIN sys.indexes i
ON ps.object_id = i.object_id
AND ps.index_id = i.index_id
CROSS APPLY sys.dm_db_index_physical_stats(DB_ID(), ps.object_id, ps.index_id, null, 'LIMITED') ips
ORDER BY ps.object_id, ps.index_id
</code></pre>
<p>And found out that I have indexes that need maintaining
<a href="https://i.stack.imgur.com/S2SIq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S2SIq.png" alt="enter image description here"></a></p> | 51,567,028 | 4 | 0 | null | 2018-02-08 08:38:30.527 UTC | 10 | 2021-05-09 03:41:36.963 UTC | null | null | null | null | 6,519,111 | null | 1 | 23 | sql-server|azure|azure-sql-database|azure-sql-server | 27,979 | <p>Update: Note that the engineering team has published updated guidance to better codify some of the suggestions in this answer in a more "official" from Microsoft place as some customers asked for that. <a href="https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fsql%2Frelational-databases%2Findexes%2Freorganize-and-rebuild-indexes&data=04%7C01%7CConor.Cunningham%40microsoft.com%7C26821bcd95b241c835eb08d90ff2f431%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C637558358420520035%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=l8IKbBoweyH%2F71X1szMsTxhBuG6XXnZ%2BCGOFplggGbg%3D&reserved=0" rel="nofollow noreferrer">SQL Server/DB Index Guidance</a>. Thanks, Conor</p>
<p>original answer:</p>
<p>I'll point out that most people don't need to consider rebuilding indexes in SQL Azure at all. Yes, B+ Tree indexes can become fragmented, and yes this can cause some space overhead and some CPU overhead compared to having perfectly tuned indexes. So, there are some scenarios where we do work with customers to rebuild indexes. (The primary scenario is when the customer may run out of space, currently, as disk space is somewhat limited in SQL Azure due to the current architecture). So, I will encourage you to step back and consider that using the SQL Server model for managing databases is not "wrong" but it may or may not be worth your effort.</p>
<p>(If you do end up needing to rebuild an index, you are welcome to use the models posted here by the other posters - they are generally fine models to script tasks. Note that SQL Azure Managed Instance also supports SQL Agent which you can also use to create jobs to script maintenance operations if you so choose).</p>
<p>Here are some details that may help you decide if you may be a candidate for index rebuilds:</p>
<ul>
<li>The link you referenced is from a post in 2013. The architecture for SQL Azure was completely redone after that post. Specifically, the hardware architecture moved from a model that was based on local spinning disks to one based on local SSDs (in most cases). So, the guidance in the original post is out of date.</li>
<li>You can have cases in the current architecture where you can run out of space with a fragmented index. You have options to rebuild the index or to move to a larger reservation size for awhile (which will cost more money) that supports a larger disk space allocation. [Since the local SSD space on the machines is limited, reservation sizes are roughly linked to proportions of the machine. As we get newer hardware with larger/more drives, you have more scale-up options].</li>
<li>SSD fragmentation impact is relatively low compared to rotating disks since the cost of a random IO is not really any higher than a sequential one. The CPU overhead of walking a few more B+ Tree intermediate pages is modest. I've usually seen an overhead of perhaps 5-20% max in the average case (which may or may not justify regular rebuilds which have a much bigger workload impact when rebuilding)</li>
<li>If you are using query store (which is on by default in SQL Azure), you can evaluate whether a specific index rebuild helps your performance visibly or not. You can do this as a test to see if your workload improves before bothering to take the time to build and manage index rebuild operations yourself.</li>
<li>Please note that there is currently no intra-database resource governance within SQL Azure for user workloads. So, if you start an index rebuild, you may end up consuming lots of resources and impacting your main workload. You can try to time things to be done off-hours, of course, but for applications with lots of customers around the world this may not be possible.</li>
<li>Additionally, I will note that many customers have index rebuild jobs "because they want stats to be updated". It is not necessary to rebuild an index just to rebuild the stats. In recent SQL Server and SQL Azure, the algorithm for stats update was made more aggressive on larger tables and the model for how we estimate cardinality in cases where customers are querying recently inserted data (since the last stats update) have been changed in later compatibility levels. So, it is often the case that the customer doesn't even need to do any manual stats update at all.</li>
<li>Finally, I will note that the impact of stats being out of date was historically that you'd get plan choice regressions. For repeated queries, a lot of the impact of this was mitigated by the introduction of the automatic tuning feature over query store (which forces prior plans if it notices a large regression in query performance compared to the prior plan).</li>
</ul>
<p>The official recommendation that I give customers is to not bother with index rebuilds unless they have a tier-1 app where they've demonstrated real need (benefits outweigh the costs) or where they are a SaaS ISV where they are trying to tune a workload over many databases/customers in elastic pools or in a multi-tenant database design so they can reduce their COGS or avoid running out of disk space (as mentioned earlier) on a very big database. In the largest customers we have on the platform, we <em>sometimes</em> see value in doing index operations manually with the customer, but we often do not need to have a regular job where we do this kind of operation "just in case". The intent from the SQL team is that you don't need to bother with this at all and you can just focus on your app instead. There are always things that we can add or improve into our automatic mechanisms, of course, so I completely allow for the possibility that an individual customer database may have a need for such actions. I've not seen any myself beyond the cases I mentioned, and even those are rarely an issue.</p>
<p>I hope this gives you some context to understand why this isn't being done in the platform yet - it just hasn't been an issue for the vast majority of customer databases we have today in our service compared to other pressing needs. We revisit the list of things we need to build each planning cycle, of course, and we do look at opportunities like this regularly.</p>
<p>Good luck - whatever your outcome here, I hope this helps you make the right choice.</p>
<p>Sincerely,
Conor Cunningham
Architect, SQL</p> |
50,441,093 | Is there a point to doing 'import type' rather than 'import' with Flow? | <p>Flow allows you to use the following syntax to import types:</p>
<pre><code>// SomeClass.js
export default class SomeClass {}
// SomeFile.js
import type SomeClass from './SomeClass';
</code></pre>
<p>What's the benefit of using <code>import type</code> instead of <code>import</code>? Does it tell Flow more information and let it perform better static analysis?</p> | 50,442,181 | 2 | 0 | null | 2018-05-21 02:03:34.58 UTC | 4 | 2022-07-26 03:24:41.513 UTC | null | null | null | null | 4,077,294 | null | 1 | 46 | javascript|ecmascript-6|flowtype|commonjs | 29,236 | <p>For the specific case of classes, it is either example will work. The key thing is that it breaks down like this:</p>
<ul>
<li><code>import type ... from</code> imports a Flow type</li>
<li><code>import ... from</code> imports a standard JS value, and the type of that value.</li>
</ul>
<p>A JS class produces a value, but Flowtype also interprets a class declaration as a type declaration, so it is <em>both</em>.</p>
<p>So where is <code>import type</code> important?</p>
<ol>
<li>If the thing you're importing doesn't have a value, using a value import will in some cases be interpreted as an error, because most JS tooling doesn't know that Flow exists.</li>
</ol>
<ul>
<li><code>export type Foo = { prop: number };</code> for instance can only be imported with <code>import type { Foo } from ...</code>, since there is no <em>value</em> named <code>Foo</code></li>
</ul>
<ol start="2">
<li>If the thing you're importing has a JS value, but all you want is the type</li>
</ol>
<ul>
<li>Importing only the type can make code more readable, because it is clear from the imports that only the type is used, so nothing in the file could for instance, create a new instance of that class.</li>
<li>Sometimes importing only the type will allow you to avoid dependency cycles in your files. Depending on how code is written, it can sometimes matter what order things are imported in. Since <code>import type ...</code> only influences typechecking, and not runtime behavior, you can import a type without actually requiring the imported file to execute, avoiding potential cycles.</li>
</ul> |
35,320,674 | How can I have same rule for two locations in NGINX config? | <p>How can I have same rule for two locations in NGINX config?</p>
<p>I have tried the following</p>
<pre><code>server {
location /first/location/ | /second/location/ {
..
..
}
}
</code></pre>
<p>but nginx reload threw this error:</p>
<pre><code>nginx: [emerg] invalid number of arguments in "location" directive**
</code></pre> | 35,369,570 | 5 | 0 | null | 2016-02-10 16:30:03.6 UTC | 47 | 2022-08-04 10:16:56.3 UTC | 2017-02-06 16:22:08.267 UTC | null | 123,671 | null | 1,661,010 | null | 1 | 244 | nginx|nginx-location | 191,265 | <p>Try</p>
<pre><code>location ~ ^/(first/location|second/location)/ {
...
}
</code></pre>
<p>The <code>~</code> means to use a regular expression for the url. The <code>^</code> means to check from the first character. This will look for a <code>/</code> followed by either of the locations and then another <code>/</code>.</p> |
26,393,231 | Using python Requests with javascript pages | <p>I am trying to use the Requests framework with python (<a href="http://docs.python-requests.org/en/latest/">http://docs.python-requests.org/en/latest/</a>) but the page I am trying to get to uses javascript to fetch the info that I want. </p>
<p>I have tried to search on the web for a solution but the fact that I am searching with the keyword javascript most of the stuff I am getting is how to scrape with the javascript language.</p>
<p>Is there anyway to use the requests framework with pages that use javascript?</p> | 26,393,257 | 5 | 0 | null | 2014-10-15 22:31:11.697 UTC | 25 | 2021-10-19 04:46:40.347 UTC | null | null | null | null | 2,840,324 | null | 1 | 78 | python|web-scraping|python-requests | 154,917 | <p>You are going to have to make the same request (using the Requests library) that the javascript is making. You can use any number of tools (including those built into Chrome and Firefox) to inspect the http request that is coming from javascript and simply make this request yourself from Python.</p> |
27,039,083 | mongodb move documents from one collection to another collection | <p>How can <strong>documents</strong> be <strong>moved from one collection to another collection</strong> in <strong>MongoDB</strong>?? For example: I have lot of documents in collection A and I want to move all 1 month older documents to collection B (these 1 month older documents should not be in collection A).</p>
<p>Using <strong>aggregation</strong> we can do <strong>copy</strong>. But what I am trying to do is <strong>moving</strong> of documents.
What method can be used to move documents?</p> | 27,041,518 | 14 | 0 | null | 2014-11-20 12:00:11.49 UTC | 28 | 2020-02-21 10:19:51.227 UTC | 2016-05-23 13:22:29.817 UTC | null | 1,259,510 | null | 3,805,045 | null | 1 | 67 | mongodb | 92,736 | <p><strong>Update 2</strong></p>
<p>Please do NOT upvote this answer any more. As written <a href="https://stackoverflow.com/a/41483981/1296707">@jasongarber's answer</a> is better in any aspect.</p>
<p><strong>Update</strong></p>
<p><a href="https://stackoverflow.com/a/41483981/1296707">This answer by @jasongarber</a> is a safer approach and should be used instead of mine.</p>
<hr>
<p>Provided I got you right and you want to move all documents older than 1 month, and you use mongoDB 2.6, there is no reason not to use bulk operations, which are the most efficient way of doing multiple operations I am aware of:</p>
<pre><code>> var bulkInsert = db.target.initializeUnorderedBulkOp()
> var bulkRemove = db.source.initializeUnorderedBulkOp()
> var date = new Date()
> date.setMonth(date.getMonth() -1)
> db.source.find({"yourDateField":{$lt: date}}).forEach(
function(doc){
bulkInsert.insert(doc);
bulkRemove.find({_id:doc._id}).removeOne();
}
)
> bulkInsert.execute()
> bulkRemove.execute()
</code></pre>
<p>This should be pretty fast and it has the advantage that in case something goes wrong during the bulk insert, the original data still exists.</p>
<hr>
<p><strong>Edit</strong></p>
<p>In order to prevent too much memory to be utilized, you can execute the bulk operation on every <code>x</code> docs processed:</p>
<pre><code>> var bulkInsert = db.target.initializeUnorderedBulkOp()
> var bulkRemove = db.source.initializeUnorderedBulkOp()
> var x = 10000
> var counter = 0
> var date = new Date()
> date.setMonth(date.getMonth() -1)
> db.source.find({"yourDateField":{$lt: date}}).forEach(
function(doc){
bulkInsert.insert(doc);
bulkRemove.find({_id:doc._id}).removeOne();
counter ++
if( counter % x == 0){
bulkInsert.execute()
bulkRemove.execute()
bulkInsert = db.target.initializeUnorderedBulkOp()
bulkRemove = db.source.initializeUnorderedBulkOp()
}
}
)
> bulkInsert.execute()
> bulkRemove.execute()
</code></pre> |
51,086,407 | How to reuse template HTML block in Angular? | <p>Lets suppose we have html block in file:</p>
<pre><code><div id="text">Text</div>
</code></pre>
<p>How can I reuse this html code below in the same file, I mean something like this:</p>
<pre><code><re-use id="text"></re-use>
</code></pre>
<p>Is it possible?</p> | 51,096,013 | 5 | 0 | null | 2018-06-28 15:16:41.62 UTC | 21 | 2021-04-20 20:43:09.95 UTC | null | null | null | null | 8,291,684 | null | 1 | 103 | angular | 48,387 | <p>I think you wanted to reuse the same html block again. If i understand you correctly, below code should help</p>
<pre><code><ng-template #MsgRef >
{{ mycontent }}
</ng-template>
</code></pre>
<p>To reuse above block in the same template, </p>
<pre><code> <ng-template [ngTemplateOutlet]="MsgRef"></ng-template> //reuse any number of times
</code></pre> |
21,275,911 | Working maven obfuscate example | <p>I just want to obfuscate simple maven java app. I use maven-proguard-plugin. All classes main/java must be obfuscated. I try different configs with no luck. The last is:</p>
<pre><code> <build>
<plugins>
<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<version>2.0.6</version>
<dependencies>
<dependency>
<groupId>net.sf.proguard</groupId>
<artifactId>proguard-base</artifactId>
<version>4.10</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<executions>
<execution>
<phase>package</phase>
<goals><goal>proguard</goal></goals>
</execution>
</executions>
<configuration>
<proguardVersion>4.10</proguardVersion>
<options>
<option>-keep class *{*;}</option>
</options>
<libs>
<lib>${java.home}/lib/rt.jar</lib>
</libs>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>result - all classes exist in target jar, but not obfuscated, jad decompiles it well. How to do obfuscate right?
Can't understand - is just obfuscate all source are very uncommon task? All other plugins works out of the box like a charm. Why i must type some strange options in this one? I spent a day already. I want convention over configuration! :)</p> | 21,277,480 | 1 | 0 | null | 2014-01-22 06:38:17.943 UTC | 8 | 2019-03-20 08:58:39.747 UTC | null | null | null | null | 1,442,163 | null | 1 | 7 | maven|obfuscation|proguard | 26,921 | <p>Maven such a great thing :). You can make what you want and even not understand, what you want. After i read <a href="https://www.guardsquare.com/en/products/proguard/manual/introduction" rel="noreferrer">the introduction</a>, i understand that it's a stupid question. Keep parameter is very important. Here pass in the public methods which must not changed. Of course plugin can't undestand by itself what methods you plan to use. Correct config:</p>
<pre><code><build>
<plugins>
<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<version>2.0.6</version>
<dependencies>
<dependency>
<groupId>net.sf.proguard</groupId>
<artifactId>proguard-base</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>package</phase>
<goals><goal>proguard</goal></goals>
</execution>
</executions>
<configuration>
<proguardVersion>4.10</proguardVersion>
<options>
<option>-keep public class myapp.Main{public static void main(java.lang.String[]);}</option>
</options>
<libs>
<lib>${java.home}/lib/rt.jar</lib>
<lib>${java.home}/lib/jce.jar</lib>
</libs>
</configuration>
</plugin>
</plugins>
</build>
</code></pre> |
37,510,487 | Lowest overhead camera to CPU to GPU approach on android | <p>My application needs to do some processing on live camera frames on the CPU, before rendering them on the GPU. There's also some other stuff being rendered on the GPU which is dependent on the results of the CPU processing; therefore it's important to keep everything synchronised so we don't render the frame itself on the GPU until the results of the CPU processing for that frame are also available.</p>
<p>The question is what's the lowest overhead approach for this on android?</p>
<p>The CPU processing in my case just needs a greyscale image, so a YUV format where the Y plane is packed is ideal (and tends to be a good match to the native format of the camera devices too). NV12, NV21 or fully planar YUV would all provide ideal low-overhead access to greyscale, so that would be preferred on the CPU side.</p>
<p>In the original camera API the setPreviewCallbackWithBuffer() was the only sensible way to get data onto the CPU for processing. This had the Y plane separate so was ideal for the CPU processing. Getting this frame available to OpenGL for rendering in a low overhead way was the more challenging aspect. In the end I wrote a NEON color conversion routine to output RGB565 and just use glTexSubImage2d to get this available on the GPU. This was first implemented in the Nexus 1 timeframe, where even a 320x240 glTexSubImage2d call took 50ms of CPU time (poor drivers trying to do texture swizzling I presume - this was significantly improved in a system update later on).</p>
<p>Back in the day I looked into things like eglImage extensions, but they don't seem to be available or well documented enough for user apps. I had a little look into the internal android GraphicsBuffer classes but ideally want to stay in the world of supported public APIs.</p>
<p>The android.hardware.camera2 API had promise with being able to attach both an ImageReader and a SurfaceTexture to a capture session. Unfortunately I can't see any way of ensuring the right sequential pipeline here - holding off calling updateTexImage() until the CPU has processed is easy enough, but if another frame has arrived during that processing then updateTexImage() will skip straight to the latest frame. It also seems with multiple outputs there will be independent copies of the frames in each of the queues that ideally I'd like to avoid.</p>
<p>Ideally this is what I'd like:</p>
<ol>
<li>Camera driver fills some memory with the latest frame</li>
<li>CPU obtains pointer to the data in memory, can read Y data without a copy being made</li>
<li>CPU processes data and sets a flag in my code when frame is ready</li>
<li>When beginning to render a frame, check if a new frame is ready</li>
<li>Call some API to bind the same memory as a GL texture</li>
<li>When a newer frame is ready, release the buffer holding the previous frame back into the pool</li>
</ol>
<p>I can't see a way of doing exactly that zero-copy style with public API on android, but what's the closest that it's possible to get?</p>
<p>One crazy thing I tried that seems to work, but is not documented: The ANativeWindow NDK API can accept data NV12 format, even though the appropriate format constant is not one of the ones in the public headers. That allows a SurfaceTexture to be filled with NV12 data by memcpy() to avoid CPU-side colour conversion and any swizzling that happens driver side in glTexImage2d. That is still an extra copy of the data though that feels like it should be unnecessary, and again as it's undocumented might not work on all devices. A supported sequential zero-copy Camera -> ImageReader -> SurfaceTexture or equivalent would be perfect.</p> | 37,513,328 | 1 | 0 | null | 2016-05-29 13:30:58.893 UTC | 10 | 2016-05-29 18:17:08.26 UTC | null | null | null | null | 2,335,025 | null | 1 | 7 | android|opengl-es|android-ndk|android-camera | 2,647 | <p>The most efficient way to process video is to avoid the CPU altogether, but it sounds like that's not an option for you. The public APIs are generally geared toward doing everything in hardware, since that's what the framework itself needs, though there are some paths for RenderScript. (I'm assuming you've seen the <a href="https://www.youtube.com/watch?v=kH9kCP2T5Gg" rel="nofollow noreferrer">Grafika filter demo</a> that uses fragment shaders.)</p>
<p>Accessing the data on the CPU used to mean slow Camera APIs or working with GraphicBuffer and relatively obscure EGL functions (e.g. <a href="https://stackoverflow.com/questions/25564203/what-is-wrong-when-i-use-eglimage-replace-glreadpixels-in-ndk-program">this question</a>). The point of ImageReader was to provide zero-copy access to YUV data from the camera.</p>
<p>You can't really serialize Camera -> ImageReader -> SurfaceTexture as ImageReader doesn't have a "forward the buffer" API. Which is unfortunate, as that would make this trivial. You could try to replicate what SurfaceTexture does, using EGL functions to package the buffer as an external texture, but again you're into non-public GraphicBuffer-land, and I worry about ownership/lifetime issues of the buffer.</p>
<p>I'm not sure how the parallel paths help you (Camera2 -> ImageReader, Camera2 -> SurfaceTexture), as what's being sent to the SurfaceTexture wouldn't have your modifications. FWIW, it doesn't involve an extra copy -- in Lollipop or thereabouts, BufferQueue was updated to allow individual buffers to move through multiple queues.</p>
<p>It's entirely possible there's some fancy new APIs I haven't seen yet, but from what I know your ANativeWindow approach is probably the winner. I suspect you'd be better off with one of the Camera formats (YV12 or NV21) than NV12, but I don't know for sure.</p>
<p>FWIW, you will drop frames if your processing takes too long, but unless your processing is uneven (some frames take much longer than others) you'll have to drop frames no matter what. Getting into the realm of non-public APIs again, you could switch the SurfaceTexture to "synchronous" mode, but if your buffers fill up you're still dropping frames.</p> |
31,273,093 | How to add custom html attributes in JSX | <p>There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?</p> | 31,273,478 | 11 | 1 | null | 2015-07-07 15:34:33.343 UTC | 9 | 2020-12-29 06:11:10.517 UTC | 2018-11-07 05:52:47.01 UTC | null | 4,652,706 | null | 1,386,003 | null | 1 | 85 | javascript|html|node.js|reactjs|react-component | 135,452 | <h2>EDIT: Updated to reflect React 16</h2>
<p>Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a <code>render</code> function, like so:</p>
<pre><code>render() {
return (
<div custom-attribute="some-value" />
);
}
</code></pre>
<p>For more:<br>
<a href="https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes" rel="noreferrer">https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes</a><br>
<a href="https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html" rel="noreferrer">https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html</a></p>
<hr>
<h2>Previous answer (React 15 and earlier)</h2>
<p>Custom attributes are currently not supported. See this open issue for more info: <a href="https://github.com/facebook/react/issues/140" rel="noreferrer">https://github.com/facebook/react/issues/140</a></p>
<p>As a workaround, you can do something like this in <code>componentDidMount</code>:</p>
<pre><code>componentDidMount: function() {
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('custom-attribute', 'some value');
}
</code></pre>
<p>See <a href="https://jsfiddle.net/peterjmag/kysymow0/" rel="noreferrer">https://jsfiddle.net/peterjmag/kysymow0/</a> for a working example. (Inspired by syranide's suggestion in <a href="https://github.com/facebook/react/issues/140#issuecomment-62527758" rel="noreferrer">this comment</a>.)</p> |
6,110,782 | How can I view transitive dependencies of a Maven pom.xml file? | <p>Is there a CLI tool I can use to quickly view the transitive dependencies of a Maven <code>pom.xml</code> file?</p> | 6,110,881 | 1 | 1 | null | 2011-05-24 12:57:40.767 UTC | 12 | 2022-09-08 12:40:13.647 UTC | 2022-09-08 12:40:13.647 UTC | null | 183,704 | null | 2,454 | null | 1 | 66 | maven-2|maven|dependencies|pom.xml | 68,183 | <p>On the CLI, use <a href="http://maven.apache.org/plugins/maven-dependency-plugin/tree-mojo.html" rel="noreferrer"><code>mvn dependency:tree</code></a><br>
(Here are some additional <a href="http://maven.apache.org/plugins/maven-dependency-plugin/usage.html#The_dependency:tree_Mojo" rel="noreferrer">Usage notes</a>)</p>
<p>When running <code>dependency:tree</code> on multi-module maven project, use <code>mvn compile dependency:tree</code> instead<sup>1</sup>.</p>
<p>Otherwise, the POM Editor in <a href="http://m2eclipse.sonatype.org/" rel="noreferrer">M2Eclipse</a> (Maven integration for Eclipse) is very good, and it includes a hierarchical dependency view.</p>
<hr>
<p><sup><sup>1</sup>If you don't compile, you might get error <code>Failed to execute goal on project baseproject: Could not resolve dependencies for project com.company:childproject:jar:1.0.0: Could not find artifact</code>. This might happen because <code>dependency:tree</code> command doesn't build projects and doesn't resolve dependencies, and your projects are not installed in maven repository.</sup></p> |
28,704,642 | Multiple conditions for ng-disabled | <p>I have the following table with 3 checkboxes. I assigned each one its own model.</p>
<p>I have a button which I want to be disabled unless any one of the 3 checkbox models are true.</p>
<p>However I'm confused since I expected to use </p>
<p><code><button " ng-disabled="!mt0 || !mt1 || !mt2">Reassign</button></code></p>
<p>since if <strong>any</strong> of those were to be true the button should not be disabled.</p>
<p>However, the <em>opposite</em> worked:</p>
<p><code><button ng-disabled="!mt0 && !mt1 && !mt2">Reassign</button></code></p>
<p>Why?</p>
<p>See plnkr here: <a href="http://plnkr.co/edit/yURa3g0aNjDyfEvjK2D0?p=preview" rel="noreferrer">http://plnkr.co/edit/yURa3g0aNjDyfEvjK2D0?p=preview</a></p> | 28,705,369 | 4 | 0 | null | 2015-02-24 19:33:04.667 UTC | 6 | 2017-09-28 10:56:35.727 UTC | null | null | null | null | 187,835 | null | 1 | 14 | angularjs|boolean | 47,626 | <p>You can do this to achieve what you want: <a href="http://jsfiddle.net/8bc24nau/1/">fiddle</a></p>
<pre><code><div ng-app>
<input type="checkbox" ng-model="mt0">
<input type="checkbox" ng-model="mt1">
<input type="checkbox" ng-model="mt2">
<button ng-disabled=" (mt0||mt1||mt2) ? false : true">Reassign</button>
</div>
</code></pre> |
25,290,229 | Laravel named route for resource controller | <p>Using Laravel 4.2, is it possible to assign a name to a resource controller route? My route is defined as follows:</p>
<pre><code>Route::resource('faq', 'ProductFaqController');
</code></pre>
<p>I tried adding a name option to the route like this:</p>
<pre><code>Route::resource('faq', 'ProductFaqController', array("as"=>"faq"));
</code></pre>
<p>However, when I hit the /faq route and place <code>{{ Route::currentRouteName() }}</code> in my view, it yields <code>faq.faq.index</code> instead of just <code>faq</code>.</p> | 25,291,737 | 11 | 0 | null | 2014-08-13 15:28:29.923 UTC | 31 | 2022-05-13 08:48:32.673 UTC | null | null | null | null | 736,864 | null | 1 | 80 | php|laravel|laravel-4 | 125,520 | <p>When you use a resource controller route, it automatically generates names for each individual route that it creates. <code>Route::resource()</code> is basically a helper method that then generates individual routes for you, rather than you needing to define each route manually.</p>
<p>You can view the route names generated by typing <code>php artisan routes</code> in Laravel 4 or <code>php artisan route:list</code> in Laravel 5 into your terminal/console. You can also see the types of route names generated on the resource controller docs page (<a href="http://laravel.com/docs/4.2/controllers#restful-resource-controllers">Laravel 4.x</a> | <a href="http://laravel.com/docs/5.0/controllers#restful-resource-controllers">Laravel 5.x</a>).</p>
<p>There are two ways you can modify the route names generated by a resource controller:</p>
<ol>
<li><p>Supply a <code>names</code> array as part of the third parameter <code>$options</code> array, with each key being the resource controller method (index, store, edit, etc.), and the value being the name you want to give the route.</p>
<pre><code>Route::resource('faq', 'ProductFaqController', [
'names' => [
'index' => 'faq',
'store' => 'faq.new',
// etc...
]
]);
</code></pre></li>
<li><p>Specify the <code>as</code> option to define a prefix for every route name.</p>
<pre><code>Route::resource('faq', 'ProductFaqController', [
'as' => 'prefix'
]);
</code></pre>
<p>This will give you routes such as <code>prefix.faq.index</code>, <code>prefix.faq.store</code>, etc.</p></li>
</ol> |
25,323,753 | Laravel league/flysystem getting file URL with AWS S3 | <p>I am trying to build a file management system in Laravel based on league/flysystem: <a href="https://github.com/thephpleague/flysystem">https://github.com/thephpleague/flysystem</a></p>
<p>I am using the S3 adapter and I have it working to save the uploaded files using:</p>
<pre><code>$filesystem->write('filename.txt', 'contents');
</code></pre>
<p>Now I am stuck on generating the <strong>download file URL</strong> when using the S3 adapter.</p>
<p>The files are saved correctly in the S3 bucket, I have permissions to access them, I just don't know how to get to the S3 getObjectUrl method through the league/flysystem package.</p>
<p>I have tried:</p>
<pre><code>$contents = $filesystem->read('filename.txt');
</code></pre>
<p>but that returns the content of the file.</p>
<pre><code>$contents = $filemanager->listContents();
</code></pre>
<p>or</p>
<pre><code>$paths = $filemanager->listPaths();
</code></pre>
<p>but they give me the relative paths to my files.</p>
<p>What I need is something like "ht...//[s3-region].amazonaws.com/[bucket]/[dir]/[file]..."</p> | 25,331,310 | 7 | 0 | null | 2014-08-15 08:56:04.1 UTC | 8 | 2021-07-23 09:23:49.797 UTC | null | null | null | null | 1,225,202 | null | 1 | 19 | php|laravel|amazon-s3|package | 47,727 | <p>I'm not sure what the <em>correct</em> way of doing this is with Flysystem, but the underlying <code>S3Client</code> object has a method for doing that. You could do <code>$filesystem->getAdapter()->getClient()->getObjectUrl($bucket, $key);</code>. Of course, building the URL is as trivial as you described, so you don't really need a special method to do it.</p> |
18,427,031 | Median Filter with Python and OpenCV | <p>I try make python program for do median filter. I got this article <a href="http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html" rel="noreferrer">http://www.programming-techniques.com/2013/02/median-filter-using-c-and-opencv-image.html</a> , so I try to translate that code to python code.</p>
<p>this the code in python</p>
<pre><code>from cv2 import * #Import functions from OpenCV
import cv2
if __name__ == '__main__':
source = cv2.imread("Medianfilterp.png", CV_LOAD_IMAGE_GRAYSCALE)
final = source[:]
for y in range(len(source)):
for x in range(y):
final[y,x]=source[y,x]
members=[source[0,0]]*9
for y in range(1,len(source)-1):
for x in range(1,y-1):
members[0] = source[y-1,x-1]
members[1] = source[y,x-1]
members[2] = source[y+1,x-1]
members[3] = source[y-1,x]
members[4] = source[y,x]
members[5] = source[y+1,x]
members[6] = source[y-1,x+1]
members[7] = source[y,x+1]
members[8] = source[y+1,x+1]
members.sort()
final[y,x]=members[4]
cv.NamedWindow('Source_Picture', cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow('Final_Picture', cv.CV_WINDOW_AUTOSIZE)
cv2.imshow('Source_Picture', source) #Show the image
cv2.imshow('Final_Picture', final) #Show the image
cv2.waitKey()
</code></pre>
<p>This is a picture before the median filter:
<img src="https://i.stack.imgur.com/gig8E.png" alt="source picture"></p>
<p>but I got strange results, the results of the program :
<img src="https://i.stack.imgur.com/tnlO9.png" alt="final picture"></p> | 18,449,389 | 1 | 0 | null | 2013-08-25 08:21:08.96 UTC | 3 | 2013-08-26 17:13:24.127 UTC | null | null | null | null | 2,128,847 | null | 1 | 7 | python|opencv|filter|median | 41,307 | <p>First, I recommend that you not <a href="http://docs.opencv.org/modules/imgproc/doc/filtering.html?#cv2.medianBlur" rel="noreferrer">re-invent the wheel</a>. OpenCV already contains a method to perform median filtering:</p>
<pre><code>final = cv2.medianBlur(source, 3)
</code></pre>
<p>That said, the problem with your implementation lies in your iteration bounds. Your <code>y</code> range is correct. However, <code>for x in range(1,y-1):</code> only iterates up to the current <code>y</code> value, and not the entire <code>x</code> range of the image. This explains why the filter is only applied to a triangular region in the lower-left of the image. You can use the <code>shape</code> field of the image (which is really just a numpy array) to get the image dimensions, which can then be iterated over:</p>
<pre><code>for y in range(1,source.shape[0]-1):
for x in range(1,source.shape[1]-1):
</code></pre>
<p>This will apply the filter to the entire image:</p>
<p><img src="https://i.stack.imgur.com/dw60I.png" alt="Median filter result"></p> |
25,701,247 | Yii2 Restful API - Example to Add a New Action | <p>For buiding restful API using Yii2, does anyone has good example on how to add a new action in a controller? Thanks.</p> | 26,031,015 | 2 | 0 | null | 2014-09-06 14:25:36.503 UTC | 11 | 2014-10-09 18:34:11.24 UTC | null | null | null | null | 912,309 | null | 1 | 14 | api|rest|yii2 | 21,337 | <p>I am not sure if you are asking for extra actions beside CRUD or just for CRUD, so I write in details for both cases.</p>
<p>Firstly, the framework includes <code>\yii\rest\ActiveController</code> that provides typical restful API operation and URL management.</p>
<p>Basically, the controller predefines the CRUD operations as followed:</p>
<p><code>POST /resource</code> -> <code>actionCreate</code> -> Create the resource</p>
<p><code>GET /resource/{id}</code> -> <code>actionView</code> -> Read the resource</p>
<p><code>PUT, PATCH /resource/{id}</code> -> <code>actionUpdate</code> -> Update the resource</p>
<p><code>DELETE /resource/{id}</code> -> <code>actionDelete</code> -> Delete the resource</p>
<p><code>GET /resource</code> -> <code>actionIndex</code> -> List all the resources</p>
<p>The URL routing rules and actions definition can be found in <code>\yii\rest\ActiveController</code>, <code>\yii\rest\UrlRule</code> and the respective <code>\yii\rest\*Action</code>.</p>
<p>Secondly, if you want to add extra restful API in the controller, you can simply write your extra <code>actionXxxxx()</code>, and in configuration, add the following url rules under <code>urlManager</code>:</p>
<pre><code>'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['resource'],
'pluralize' => false,
'extraPatterns' => [
'POST {id}/your_preferred_url' => 'xxxxx', // 'xxxxx' refers to 'actionXxxxx'
],
],
],
],
</code></pre>
<p>Effectively, this will generate a new routing rule, requesting <code>POST /resource/{id}/your_preferred_url</code> will invoke <code>actionXxxxx</code> of your ResourceController.</p> |
36,641,137 | How exactly does link rel="preload" work? | <p>Chrome's new version added support for <code><link rel="preload"></code>. They have posted a lot of info with references to the original documentation. Can someone provide simple explanation on how it works and what is the difference compared to the case without <code>rel="preload"</code>.</p> | 36,641,585 | 2 | 0 | null | 2016-04-15 07:43:37.357 UTC | 13 | 2022-06-05 18:23:40.96 UTC | 2016-04-15 08:46:42.077 UTC | null | 1,671,558 | null | 1,671,558 | null | 1 | 41 | css|html|browser|preloading | 59,308 | <p>In it's most basic form it sets the <code>link</code> that has <code>rel="preload"</code> to a high priority, Unlike prefetching, which the browser can decide whether it's a good idea or not, preload will force the browser to do so.</p>
<p>===<strong>A more in-depth look:</strong>===</p>
<p>Here's a snippet from W3c</p>
<blockquote>
<p>Many applications require fine-grained control over when resources are
fetched, processed, and applied to the document. For example, the
loading and processing of some resources may be deferred by the
application to reduce resource contention and improve performance of
the initial load. This behavior is typically achieved by moving
resource fetching into custom resource loading logic defined by the
application - i.e. resource fetches are initiated via injected
elements, or via XMLHttpRequest, when particular application
conditions are met.</p>
<p>However, there are also cases where some resources need to be fetched
as early as possible, but their processing and execution logic is
subject to application-specific requirements - e.g. dependency
management, conditional loading, ordering guarantees, and so on.
Currently, it is not possible to deliver this behavior without a
performance penalty.</p>
<p>Declaring a resource via one of the existing elements (e.g. img,
script, link) couples resource fetching and execution. Whereas, an
application may want to fetch, but delay execution of the resource
until some condition is met. Fetching resources with XMLHttpRequest to
avoid above behavior incurs a serious performance penalty by hiding
resource declarations from the user agent's DOM and preload parsers.
The resource fetches are only dispatched when the relevant JavaScript
is executed, which due to abundance of blocking scripts on most pages
introduces significant delays and affects application performance. The
preload keyword on link elements provides a declarative fetch
primitive that addresses the above use case of initiating an early
fetch and separating fetching from resource execution. As such,
preload keyword serves as a low-level primitive that enables
applications to build custom resource loading and execution behaviors
without hiding resources from the user agent and incurring delayed
resource fetching penalties.</p>
<p>For example, the application can use the preload keyword to initiate
early, high-priority, and non-render-blocking fetch of a CSS resource
that can then be applied by the application at appropriate time:</p>
</blockquote>
<pre><code><!-- preload stylesheet resource via declarative markup -->
<link rel="preload" href="/styles/other.css" as="style">
<!-- or, preload stylesheet resource via JavaScript -->
<script>
var res = document.createElement("link");
res.rel = "preload";
res.as = "style";
res.href = "styles/other.css";
document.head.appendChild(res);
</script>
</code></pre>
<p>Here's a really <a href="https://w3c.github.io/preload/" rel="nofollow noreferrer">in-depth description</a> from the W3C spec.</p>
<p>Global support is <a href="http://caniuse.com/#search=preload" rel="nofollow noreferrer">good across modern browsers</a>, at ~93% (as of June 2022).</p> |
36,335,328 | TypeError: object is not subscriptable | <p>I`ve obtain this error</p>
<pre><code> File "/class.py", line 246, in __init__
if d and self.rf == 2 and d["descriptionType"] in ["900000000000003001"] and d["conceptId"] in konZer.zerrenda:
TypeError: 'Desk' object is not subscriptable
</code></pre>
<p>I created this object</p>
<pre><code>class Desk:
descriptionId = ""
descriptionStatus = ""
conceptId = ""
term = ""
</code></pre>
<p>And I called it in another class</p>
<pre><code>class DescriptionList():
def deskJ(self,line):
er = line.strip().split('\t')
desc = Desk()
if er[1] == "0":
desc.descriptionId = er[0]
desc.descriptionStatus = er[1]
desc.conceptId = er[2]
desc.term = er[3]
return description
</code></pre>
<p>Then I called the function "deskJ" at <strong>init</strong> and I get the error at this part (I've deleted some parts of the function):</p>
<pre><code>def __init__(self,fitx,konZer,lanZer={}):
with codecs.open(fitx,encoding='utf-8') as fitx:
lines = fitx.read().split('\n')[1:-1]
for line in lines:
d = self.deskJ(line)
if d and self.rf == 2 and d["descriptionType"] in ["900000000000003001"] and d["conceptId"] in konZer.zerrenda:
c = konZer.zerrenda[d["conceptId"]]
c["fullySpecifiedName"] = d["term"]
</code></pre>
<p>What am I doing wrong?</p> | 36,335,447 | 1 | 0 | null | 2016-03-31 13:47:54.423 UTC | 1 | 2016-03-31 13:52:46.667 UTC | null | null | null | null | 6,125,957 | null | 1 | 7 | python|typeerror | 53,981 | <p>Using <code>d["descriptionType"]</code> is trying to access <code>d</code> with the key <code>"descriptionType"</code>. That doesn't work, though, because <code>d</code> is a <code>Desk</code> object that doesn't have keys. Instead, get the attributes:</p>
<pre><code>if d and self.rf == 2 and d.descriptionType in ["900000000000003001"] and d.conceptId in konZer.zerrenda:
</code></pre> |
901,045 | Screen-scraping a site with a asp.net form login in C#? | <p>Would it be possible to write a screen-scraper for a website protected by a form login. I have access to the site, of course, but I have no idea how to login to the site and save my credentials in C#. </p>
<p>Also, any good examples of screenscrapers in C# would be hugely appreciated.</p>
<p>Has this already been done? </p> | 901,168 | 2 | 0 | null | 2009-05-23 07:04:47.417 UTC | 11 | 2012-02-01 19:21:57.697 UTC | 2009-05-23 16:43:05.79 UTC | null | 67,445 | null | 67,445 | null | 1 | 7 | c#|screen-scraping | 6,100 | <p>It's pretty simple. You need your custom login (HttpPost) method. </p>
<p>You can come up with something like this (in this way you will get all needed cookies after login, and you need just to pass them to the next HttpWebRequest):</p>
<pre><code>public static HttpWebResponse HttpPost(String url, String referer, String userAgent, ref CookieCollection cookies, String postData, out WebHeaderCollection headers, WebProxy proxy)
{
try
{
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.Proxy = proxy;
http.AllowAutoRedirect = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.UserAgent = userAgent;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(cookies);
http.Referer = referer;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
headers = http.Headers;
cookies.Add(httpResponse.Cookies);
return httpResponse;
}
catch { }
headers = null;
return null;
}
</code></pre> |
2,799,941 | How to determine if VSTO 2010 Runtime is Installed? | <p>It was easy to check if VSTO 2005 SE was installed by just calling MsiGetProductInfo() with the product code {388E4B09-3E71-4649-8921-F44A3A2954A7}, as <a href="http://msdn.microsoft.com/en-us/library/aa537173(office.11).aspx#officevstowindowsinstalleroverview_productcodesandcomponentids" rel="nofollow noreferrer">listed in MSDN</a>. </p>
<p>What is the product code for the VSTO 2010/4.0 runtime? Or is there a better way to determine if it's already installed? This is for our installation process.</p>
<p>Also, I am trying to figure out the same for <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=8e011506-6307-445b-b950-215def45ddd8&displaylang=en" rel="nofollow noreferrer">Windows Imaging Component</a>.</p> | 2,831,419 | 6 | 0 | null | 2010-05-10 01:56:37.887 UTC | 7 | 2015-09-01 10:13:52.833 UTC | 2013-07-24 17:18:59.6 UTC | null | 1,065,525 | null | 232,444 | null | 1 | 13 | installation|vsto|ms-office | 41,451 | <p>The easiest way is to check the registry.</p>
<p>HKLM\Microsoft\vsto runtime setup\v4\Install </p>
<p>HKLM\Microsoft\vsto runtime setup\v4R\VSTORFeature_CLR40 (this is for the 4.0 Office extensions)</p> |
2,688,888 | Why can't I use resources as ErrorMessage with DataAnnotations? | <p>Why can't I do like this?</p>
<pre><code>[Required(ErrorMessage = "*")]
[RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = Resources.RegistrationModel.UsernameError)]
public string Username { get; set; }
</code></pre>
<p>What is the error message telling me?</p>
<blockquote>
<p>An attribute argument must be a
constant expression , typeof
expression or array creation
expression of an attribute parameter
type.</p>
</blockquote> | 2,688,965 | 6 | 0 | null | 2010-04-22 07:17:58.287 UTC | 9 | 2020-04-08 13:51:46.23 UTC | 2013-02-25 22:21:21.8 UTC | null | 889,949 | null | 282,006 | null | 1 | 20 | c#|asp.net|asp.net-mvc|resources|data-annotations | 27,918 | <p>When you are using the <code>ErrorMessage</code> property only constant strings or string literal can be assigned to it.</p>
<p>Use the <code>ErrorMessageResourceType</code> and <code>ErrorMessageResourceName</code> instead to specity your resources. </p>
<pre><code>[RegularExpression(
"^[a-zA-Z0-9_]*$",
ErrorMessageResourceType=typeof(Resources.RegistrationModel),
ErrorMessageResourceName= "UsernameError"
)]
</code></pre>
<p>Note that the resources must be <strong>public</strong> (can be set in the resource editor).</p>
<p><a href="https://i.stack.imgur.com/xmsQV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xmsQV.jpg" alt="Setting resource access to public"></a>
</p> |
2,885,190 | Using ConfigParser to read a file without section name | <p>I am using <code>ConfigParser</code> to read the runtime configuration of a script.</p>
<p>I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). <code>ConfigParser</code> will throw a <code>NoSectionError</code> exception, and will not accept the file.</p>
<p>How can I make ConfigParser simply retrieve the <code>(key, value)</code> tuples of a config file without section names? </p>
<p>For instance:</p>
<pre><code>key1=val1
key2:val2
</code></pre>
<p>I would rather not write to the config file.</p> | 2,885,753 | 7 | 1 | null | 2010-05-21 20:01:34.753 UTC | 19 | 2019-09-15 14:00:02.323 UTC | 2019-09-15 12:26:44.277 UTC | null | 355,230 | null | 104,427 | null | 1 | 106 | python|parsing|configuration-files | 108,722 | <p>Alex Martelli <a href="https://stackoverflow.com/questions/2819696/module-to-use-when-parsing-properties-file-in-python/2819788#2819788">provided a solution</a> for using <code>ConfigParser</code> to parse <code>.properties</code> files (which are apparently section-less config files).</p>
<p><a href="https://stackoverflow.com/a/25493615/3462319">His solution</a> is a file-like wrapper that will automagically insert a dummy section heading to satisfy <code>ConfigParser</code>'s requirements.</p> |
2,745,206 | Output in a table format in Java's System.out | <p>I'm getting results from a database and want to output the data as a table in Java's standard output</p>
<p>I've tried using \t but the first column I want is very variable in length.</p>
<p>Is there a way to display this in a nice table like output?</p> | 2,745,239 | 8 | 1 | null | 2010-04-30 14:32:55.523 UTC | 45 | 2020-12-18 11:58:02.22 UTC | 2017-05-13 12:02:38.587 UTC | null | 4,370,109 | null | 277,671 | null | 1 | 105 | java|string-formatting|tabular | 297,117 | <p>Use <a href="http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html#format(java.lang.String,%20java.lang.Object...)" rel="noreferrer" title="format(String, Object...)"><code>System.out.format</code></a> . You can set lengths of fields like this:</p>
<pre><code>System.out.format("%32s%10d%16s", string1, int1, string2);
</code></pre>
<p>This pads <code>string1</code>, <code>int1</code>, and <code>string2</code> to 32, 10, and 16 characters, respectively.</p>
<p>See the Javadocs for <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html" rel="noreferrer"><code>java.util.Formatter</code></a> for more information on the syntax (<code>System.out.format</code> uses a <code>Formatter</code> internally).</p> |
2,814,880 | How to check if letter is upper or lower in PHP? | <p>I have texts in UTF-8 with diacritic characters also, and would like to check if first letter of this text is upper case or lower case. How to do this?</p> | 55,992,883 | 11 | 2 | null | 2010-05-11 22:29:59.007 UTC | 15 | 2022-01-08 01:56:15.38 UTC | null | null | null | null | 38,940 | null | 1 | 55 | php|string|utf-8 | 62,133 | <p>It is my opinion that making a <code>preg_</code> call is the most direct, concise, and reliable call versus the other posted solutions here.</p>
<pre><code>echo preg_match('~^\p{Lu}~u', $string) ? 'upper' : 'lower';
</code></pre>
<p>My pattern breakdown:</p>
<pre><code>~ # starting pattern delimiter
^ #match from the start of the input string
\p{Lu} #match exactly one uppercase letter (unicode safe)
~ #ending pattern delimiter
u #enable unicode matching
</code></pre>
<p>Please take notice when <code>ctype_</code> and <code>< 'a'</code> fail with this battery of tests.</p>
<p>Code: (<a href="https://3v4l.org/4eGBV" rel="noreferrer">Demo</a>)</p>
<pre><code>$tests = ['âa', 'Bbbbb', 'Éé', 'iou', 'Δδ'];
foreach ($tests as $test) {
echo "\n{$test}:";
echo "\n\tPREG: " , preg_match('~^\p{Lu}~u', $test) ? 'upper' : 'lower';
echo "\n\tCTYPE: " , ctype_upper(mb_substr($test, 0, 1)) ? 'upper' : 'lower';
echo "\n\t< a: " , mb_substr($test, 0, 1) < 'a' ? 'upper' : 'lower';
$chr = mb_substr ($test, 0, 1, "UTF-8");
echo "\n\tMB: " , mb_strtoupper($chr, "UTF-8") == $chr ? 'upper' : 'lower';
}
</code></pre>
<p>Output:</p>
<pre><code>âa:
PREG: lower
CTYPE: lower
< a: lower
MB: lower
Bbbbb:
PREG: upper
CTYPE: upper
< a: upper
MB: upper
Éé: <-- trouble
PREG: upper
CTYPE: lower <-- uh oh
< a: lower <-- uh oh
MB: upper
iou:
PREG: lower
CTYPE: lower
< a: lower
MB: lower
Δδ: <-- extended beyond question scope
PREG: upper <-- still holding up
CTYPE: lower
< a: lower
MB: upper <-- still holding up
</code></pre>
<p>If anyone needs to differentiate between uppercase letters, lowercase letters, and non-letters see <a href="https://stackoverflow.com/a/55992383/2943403">this post</a>.</p>
<hr>
<p>It may be extending the scope of this question too far, but if your input characters are especially squirrelly (they might not exist in a category that <code>Lu</code> can handle), you may want to check if the first character has case variants:</p>
<blockquote>
<p>\p{L&} or \p{Cased_Letter}: a letter that exists in lowercase and uppercase variants (combination of Ll, Lu and Lt).</p>
</blockquote>
<ul>
<li>Source: <a href="https://www.regular-expressions.info/unicode.html" rel="noreferrer">https://www.regular-expressions.info/unicode.html</a></li>
</ul>
<p>To include Roman Numerals ("Number Letters") with <code>SMALL</code> variants, you can add that extra range to the pattern if necessary.</p>
<p><a href="https://www.fileformat.info/info/unicode/category/Nl/list.htm" rel="noreferrer">https://www.fileformat.info/info/unicode/category/Nl/list.htm</a></p>
<p>Code: (<a href="https://3v4l.org/5kao7" rel="noreferrer">Demo</a>)</p>
<pre><code>echo preg_match('~^[\p{Lu}\x{2160}-\x{216F}]~u', $test) ? 'upper' : 'not upper';
</code></pre> |
2,496,814 | Disable selecting in WPF DataGrid | <p>How can I disable selecting in a WPFTooklit's <code>DataGrid</code>?
I tried modifying the solution that works for <code>ListView</code> (from <a href="https://stackoverflow.com/questions/1051215/wpf-listview-turn-off-selection#comment-863179">WPF ListView turn off selection</a>), but that doesn't work:</p>
<pre><code><tk:DataGrid>
<tk:DataGrid.ItemContainerStyle>
<Style TargetType="{x:Type tk:DataGridRow}">
<Setter Property="Focusable" Value="false"/>
</Style>
</tk:DataGrid.ItemContainerStyle>
<tk:DataGrid.CellStyle>
<Style TargetType="{x:Type tk:DataGridCell}">
<Setter Property="Focusable" Value="false"/>
</Style>
</tk:DataGrid.CellStyle>
</tk:DataGrid>
</code></pre> | 2,502,523 | 12 | 0 | null | 2010-03-23 00:49:18.67 UTC | 9 | 2020-09-06 10:34:40.4 UTC | 2017-05-23 11:47:26.357 UTC | null | -1 | null | 41,071 | null | 1 | 56 | c#|wpf|datagrid|focus|selection | 100,538 | <p>There is a trick for this.
You can handle SelectionChanged event of the DataGrid(say dgGrid) and in the handler write:</p>
<pre><code>dgGrid.UnselectAll();
</code></pre>
<p>It will unselect all selected row and result will be "No row selected".</p> |
2,342,162 | std::string formatting like sprintf | <p>I have to format <a href="http://en.cppreference.com/w/cpp/string/basic_string"><code>std::string</code></a> with <a href="http://en.cppreference.com/w/cpp/io/c/fprintf"><code>sprintf</code></a> and send it into file stream. How can I do this?</p> | 2,342,176 | 44 | 4 | null | 2010-02-26 14:15:54.29 UTC | 177 | 2022-09-04 07:37:08.18 UTC | 2020-04-26 13:33:08.037 UTC | user283145 | 3,204,551 | null | 87,152 | null | 1 | 578 | c++|string|formatting|stdstring|c++-standard-library | 1,151,096 | <p>You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's <a href="https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf#comment61134428_2342176">comment</a>). You'll have to do it first in a c-string, then copy it into a std::string:</p>
<pre><code> char buff[100];
snprintf(buff, sizeof(buff), "%s", "Hello");
std::string buffAsStdStr = buff;
</code></pre>
<p>But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:</p>
<pre><code> std::ostringstream stringStream;
stringStream << "Hello";
std::string copyOfStr = stringStream.str();
</code></pre> |
50,876,766 | How to implement Ping/Pong request for webSocket connection alive in javascript? | <p>I use websocket in javascript. But the connection close after one minute.</p>
<p>I am wondering somethings:</p>
<p>1- Is not Websocket naturaly providing with Ping/Pong messages not to close the connection? I think it have to. Otherwise what is the difference between websocket and TCP connection?</p>
<p>2- If I have to send the ping/pong messages, how is the ping message sent? What am I need to do? Is WebSocket object provide a ping method? Or should I call a method as websocket.send("ping") ? I am use naturaly WebSocket object in javascipt.</p>
<p>3- Should the server respond to Ping requests with Pong? Should this be implemented separately on the server side?</p>
<p>Note:Sorry for my english.</p> | 50,883,592 | 4 | 0 | null | 2018-06-15 13:38:27.193 UTC | 9 | 2019-09-16 10:38:14.677 UTC | null | null | null | null | 7,861,684 | null | 1 | 19 | javascript|web|websocket|ping|pong | 76,721 | <p>At this point in time, heartbeats are normally implemented on the server side: there's not much you can do from the client end.</p>
<p>However, if the server keeps killing your socket connection, and you have no control over it, it is possible for the client to send arbitrary data to the websocket on an interval:</p>
<pre><code>let socket = null;
function connect_socket() {
socket = new WebSocket(ws_url);
socket.on("close", connect_socket); // <- rise from your grave!
heartbeat();
}
function heartbeat() {
if (!socket) return;
if (socket.readyState !== 1) return;
socket.send("heartbeat");
setTimeout(heartbeat, 500);
}
connect_socket();
</code></pre>
<p>I strongly recommend trying to sort out what's happening on the server end, rather than trying to work around it on the client.</p> |
42,232,954 | Bootstrap 4 - word wrapping in cards | <p>How can I word wrap text insided cards.</p>
<p>Here's the problem: <a href="https://embed.plnkr.co/EXVeBhLwwGhJ8lM0NTh8/" rel="noreferrer">plunker link</a></p>
<p>Do you have any idea how to fix it?</p> | 42,233,008 | 4 | 1 | null | 2017-02-14 17:51:11.527 UTC | 3 | 2022-01-22 23:26:30.68 UTC | 2017-02-14 18:29:00.737 UTC | null | 171,456 | null | 2,836,246 | null | 1 | 22 | html|twitter-bootstrap|css | 57,868 | <p>You need two rules: </p>
<ul>
<li><code>max-width</code> for your <code>.card</code> elements (because without defining a width CSS will not know where to break your long word) <strong>or</strong> <code>overflow: hidden;</code> to make the <code>.card</code> width no longer depend on the long word length</li>
<li><code>word-wrap: break-word;</code> to tell the browser to break a word</li>
</ul>
<hr>
<pre class="lang-css prettyprint-override"><code>.card {
max-width: 100%;
}
.card-text {
word-wrap: break-word;
}
</code></pre>
<hr>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
overflow: hidden;
}
.card-block {
word-wrap: break-word;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link data-require="[email protected]" data-semver="4.0.0-alpha.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
<div class="card-deck">
<div class="card">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</div>
<div class="card">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</div>
<div class="card">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">supportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingsupportingto additional content. This card has even longer content than the
first to show that equal height action.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p> |
10,827,812 | What is the length maximum for a string data type in MongoDB used with Ruby? | <p>I wasn't able to find any information on the max length for a string data type in MongoDB on the main mongodb.org site. I'm coming from a relational database background and there are usually max lengths. Thank you!</p> | 10,827,837 | 3 | 0 | null | 2012-05-31 05:17:48.847 UTC | 4 | 2019-02-15 07:54:45.847 UTC | null | null | null | null | 1,293,859 | null | 1 | 30 | ruby|mongodb|mongoid | 40,178 | <p>This <a href="https://stackoverflow.com/questions/4667597/understanding-mongodb-bson-document-size-limit">other question</a> should answer your question:</p>
<blockquote>
<p>Documents larger than 4MB (when converted to BSON) cannot be saved to the database. This is a somewhat arbitrary limit (and may be raised in the future); it is mostly to prevent bad schema design and ensure consistent performance.</p>
</blockquote>
<p>Note that in the picked answer for that question the commenter mentions that it could be as large as 8mb or 16mb now. </p>
<p>So to answer your question, it's not necessarily that a single string can only be a certain length, but rather that the <em>whole document</em> must be under 16MB.</p> |
10,260,015 | How does Meteor's reactivity work behind the scenes? | <p>I have read the <a href="http://docs.meteor.com/" rel="noreferrer">docs</a> and looked at the <a href="https://github.com/meteor/meteor/blob/master/packages/tracker/tracker.js" rel="noreferrer">source behind reactivity</a>, but I don't understand it.</p>
<p>Can someone explain how this works behind the scenes, as it looks like magic to me :).</p> | 10,293,760 | 1 | 0 | null | 2012-04-21 14:52:17.1 UTC | 37 | 2015-04-26 11:44:06.843 UTC | 2015-04-26 10:08:54.06 UTC | null | 1,132,101 | null | 291,557 | null | 1 | 66 | meteor | 7,984 | <p>So it's actually rather straight forward, at a basic level there are 2 types of functions involved:</p>
<ol>
<li><p>Functions that create a reactive context (reactive function)</p></li>
<li><p>Functions that invalidate a reactive context (invalidating function)</p></li>
<li><p>Functions that can do both. (I lied there are 3)</p></li>
</ol>
<p>When you call a <code>reactive function</code> it creates a <code>context</code> that meteor stores globally and to which the <code>reactive function</code> subscribes an <code>invalidation</code> callback. The function that you pass to a reactive function, or any functions that run from within it, can be an <code>invalidating function</code> and can grab the current <code>context</code> and store it locally. These functions can then at any time, like on a db update or simply a timer call, invalidate that <code>context</code>. The original <code>reactive function</code> would then receive that event and re-evaluate itself.</p>
<p>Here's a step by step using meteor functions (note that <code>Tracker.autorun</code> used to be called <code>Deps.autorun</code>):</p>
<pre><code>Tracker.autorun(function(){
alert("Hello " + Session.get("name"));
});
Session.set("name", "Greg");
</code></pre>
<ol>
<li>autorun takes a function as its parameter</li>
<li>before autorun runs this function, it creates a <code>context</code></li>
<li>autorun attaches a callback to the <code>context</code>'s invalidation event </li>
<li>This callback will re-run the function passed to autorun</li>
<li>The function is then run in the <code>context</code> for the first time.</li>
<li>Meteor stores this <code>context</code> globally as the currently active <code>context</code></li>
<li>Inside the function is another function: Session.get()</li>
<li>Session.get() is both a <code>reactive function</code> and an <code>invalidating function</code></li>
<li>Session.get sets up it's own <code>context</code> and associates it internally with the key "name" </li>
<li>Session.get retrieves the current context (autorun's context) globally from meteor</li>
<li>The invalidation callback that Session.get registers to it's own context, will simply invalidate it's enclosing context (in this case, autorun's context)</li>
<li>So now we have 2 contexts, autorun's and session.get's</li>
<li><p>when these functions return, meteor cleans up the active context global variable </p></li>
<li><p>Session.set is another function capable of invalidating a <code>context</code>.</p></li>
<li>in this case we're invalidating all <code>context</code>s created by Session associated with the key "name"</li>
<li>All of those <code>contexts</code>, when invalidated, run their invalidation callbacks. </li>
<li>Those callbacks just invalidate their enclosing <code>context</code>s (That's the design of Session.get and not what a invalidation callback must do) </li>
<li>Those enclosing <code>contexts</code> now run their invalidation callbacks.</li>
<li>In the autorun case, that callback runs the function we originally passed to autorun and then sets up the <code>context</code> again.</li>
</ol>
<p><strong>The whole implementation is actually rather straight forward as well, you can see it here:</strong><br>
<a href="https://github.com/meteor/meteor/blob/master/packages/tracker/tracker.js">https://github.com/meteor/meteor/blob/master/packages/tracker/tracker.js</a></p>
<p><strong>And a good example of how it works can be found here:</strong><br>
<a href="https://github.com/meteor/meteor/blob/master/packages/reactive-dict/reactive-dict.js">https://github.com/meteor/meteor/blob/master/packages/reactive-dict/reactive-dict.js</a></p>
<p><strong>Reactive programming is not actually meteor or JS specific</strong><br>
you can read about it here: <a href="http://en.wikipedia.org/wiki/Reactive_programming">http://en.wikipedia.org/wiki/Reactive_programming</a> </p> |
19,625,334 | How to create an event handler for a range slider? | <p>I'm trying to get a range slider to work but I can't.
How do I add an event handler so when the user chooses a value my code reads that value. Right now its value is always <code>1</code>.</p>
<p>I would like to do this using pure Javascript.</p>
<p><strong>HTML:</strong></p>
<pre><code><div id="slider">
<input class="bar" type="range" id="rangeinput" min="1" max="25" value="1" onchange="rangevalue.value=value"/>
<span class="highlight"></span>
<output id="rangevalue">1</output>
</div>
</code></pre>
<p><strong>JAVASCRIPT:</strong></p>
<pre><code>var rangeInput = document.getElementById("rangeinput").value;
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
if (rangeInput > 0 && rangeInput < 5) {
alert("First");
} else {
alert("Second");
}
}
</code></pre>
<p><a href="http://jsfiddle.net/g9ZUs/2/" rel="noreferrer">JSFIDDLE</a></p> | 19,625,696 | 5 | 0 | null | 2013-10-28 00:17:30.01 UTC | 1 | 2022-07-07 09:36:16.56 UTC | 2022-07-07 09:36:16.56 UTC | null | 3,257,186 | null | 2,005,799 | null | 1 | 19 | javascript|html|events | 57,725 | <h2>Single Read</h2>
<p>The problem is that you're only reading the value once (at startup), instead of reading it every time the event occurs:</p>
<pre><code>// this stores the value at startup (which is why you're always getting 1)
var rangeInput = document.getElementById("rangeinput").value;
</code></pre>
<p>You should be reading the value in the handler instead:</p>
<pre><code>function testtest(e) {
// read the value from the slider:
var value = document.getElementById("rangeinput").value;
// now compare:
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
</code></pre>
<p>Or to rewrite your code:</p>
<pre><code>var rangeInput = document.getElementById("rangeinput");
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
var value = rangeInput.value;
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
</code></pre>
<h2>Updating rangevalue</h2>
<p>It also looks like you want to update the output element with the value of the range. What you're currently doing is referring to the element by id:</p>
<pre><code>onchange="rangevalue.value=value"
</code></pre>
<p>However, as far as I know, this isn't standard behavior; you can't refer to elements by their id alone; you have to retrieve the element and then set the value via the DOM.</p>
<p>Might I suggest that you add a change listener via javascript:</p>
<pre><code>rangeInput.addEventListener("change", function() {
document.getElementById("rangevalue").textContent = rangeInput.value;
}, false);
</code></pre>
<p>Of course, you'll have to update the code to use <code>addEventListener</code> or <code>attachEvent</code> depending on the browsers that you want to support; this is where <a href="http://jquery.com/" rel="noreferrer">JQuery</a> really becomes helpful.</p> |
19,338,209 | How to fix a : TypeError 'tuple' object does not support item assignment | <p>The following fragment of code from this tutorial: <a href="http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python" rel="noreferrer">http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python</a> </p>
<pre><code>for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
</code></pre>
<p>is giving me a : </p>
<blockquote>
<p>TypeError: 'tuple' object does not support item assignment</p>
</blockquote>
<p>I understand that this could be becuse <code>badguy</code> is a tuple. This means it is immutable(you can not change its values) Ive tried the following:</p>
<pre><code>t= list(badguy)
t[0]= t[0]-7
i+=1
</code></pre>
<p>I converted the tuple to a list so we can minus 7. But in the game nothing happens.</p>
<p>Does any one know what I could do?</p>
<p>Thanks.</p> | 19,338,259 | 3 | 0 | null | 2013-10-12 19:19:57.773 UTC | 3 | 2020-02-09 09:55:52.68 UTC | null | null | null | null | 1,332,991 | null | 1 | 11 | python|pygame | 57,222 | <p>Change this</p>
<pre><code>badguy[0]-=7
</code></pre>
<p>into this</p>
<pre><code>badguy = list(badguy)
badguy[0]-=7
badguy = tuple(badguy)
</code></pre>
<p>Alternatively, if you can leave <code>badguy</code> as a <code>list</code>, then don't even use tuples and you'll be fine with your current code (with the added change of using lists instead of tuples)</p> |
34,326,745 | What's the difference between @ViewChild and @ContentChild? | <p>Angular 2 provides <code>@ViewChild</code>, <code>@ViewChildren</code>, <code>@ContentChild</code> and <code>@ContentChildren</code> decorators for querying a component's descendant elements.</p>
<p>What's the difference between the first two and the latter two? </p> | 34,327,754 | 5 | 1 | null | 2015-12-17 04:41:20.837 UTC | 91 | 2021-07-19 01:18:48.563 UTC | 2019-04-24 16:42:39.947 UTC | null | 3,345,644 | null | 1,988,693 | null | 1 | 261 | angular | 114,742 | <p>I'll answer your question using <strong>Shadow DOM</strong> and <strong>Light DOM</strong> terminology (it have come from web components, see more <a href="https://www.webcomponents.org/polyfills/shadow-dom/" rel="noreferrer">here</a>). In general:</p>
<ul>
<li><strong><em>Shadow DOM</em></strong> - is an internal DOM of your component that is defined <strong>by you</strong> (as a <strong>creator of the component</strong>) and hidden from an end-user. For example:</li>
</ul>
<pre class="lang-ts prettyprint-override"><code>@Component({
selector: 'some-component',
template: `
<h1>I am Shadow DOM!</h1>
<h2>Nice to meet you :)</h2>
<ng-content></ng-content>
`;
})
class SomeComponent { /* ... */ }
</code></pre>
<ul>
<li><strong><em>Light DOM</em></strong> - is a DOM that <strong>an end-user of your component</strong> supply into your component. For example:</li>
</ul>
<pre class="lang-ts prettyprint-override"><code>@Component({
selector: 'another-component',
directives: [SomeComponent],
template: `
<some-component>
<h1>Hi! I am Light DOM!</h1>
<h2>So happy to see you!</h2>
</some-component>
`
})
class AnotherComponent { /* ... */ }
</code></pre>
<p>So, the answer to your question is pretty simple:</p>
<blockquote>
<p>The difference between <code>@ViewChildren</code> and <code>@ContentChildren</code> is that <code>@ViewChildren</code> look for elements in Shadow DOM while <code>@ContentChildren</code> look for them in Light DOM.</p>
</blockquote> |
21,199,412 | Laravel Blade: @endsection vs @stop | <p>In Laravel Blade, we can basically do this:</p>
<pre><code>@section('mysection')
@endsection
@section('mysection')
@stop
</code></pre>
<p>What is the difference between <code>@stop</code> and <code>@endsection</code>?</p> | 21,199,876 | 3 | 1 | null | 2014-01-18 02:51:25.287 UTC | 4 | 2019-02-05 08:38:51.31 UTC | 2016-02-02 07:46:07.233 UTC | null | 1,587,329 | null | 1,995,781 | null | 1 | 42 | php|laravel-4|laravel-blade | 22,831 | <p>The <code>@endsection</code> was used in Laravel 3 and it was deprecated in Laravel 4</p>
<p>In the Laravel 4 to end a section you have to use <code>@stop</code></p>
<p>You can refer the Changelog here
<a href="http://wiki.laravel.io/Changelog_%28Laravel_4%29#Blade_Templating" rel="noreferrer">http://wiki.laravel.io/Changelog_%28Laravel_4%29#Blade_Templating</a></p> |
18,999,660 | Background image not showing on iPad and iPhone | <p>I want to create a section with a background covering it in a mobile web page, so I was using the following CSS code:</p>
<pre><code>#section1{
background: url("background1.png") auto 749px;
height: 749px;
}
</code></pre>
<p>The background is showing correctly on Android (Chrome, Firefox ...), but it is not showing at all on iPhone or iPad (Safari, Chrome iOS ...). I have tried to set these properties using jQuery when the DOM is ready, but no luck. I read that the size might be a problem, but the image is about 700kB (1124x749px) so it should accomplish the <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/CreatingContentforSafarioniPhone/CreatingContentforSafarioniPhone.html#//apple_ref/doc/uid/TP40006482-SW15" rel="noreferrer">Safari Web Content Guide</a> rules. Which is the problem?</p> | 19,000,670 | 15 | 0 | null | 2013-09-25 08:16:31.263 UTC | 10 | 2022-09-02 23:05:49.97 UTC | null | null | null | null | 1,264,801 | null | 1 | 13 | iphone|ios|css|ipad|background | 64,975 | <p>There's a problem with your CSS rule:</p>
<p>Your using the shorthand notation in which the <code>background-size</code>-property comes <em>after</em> the <code>background-position</code>-property and <em>it must be separated by a <code>/</code></em>.</p>
<p>What you're trying to do is to set the position, but it will fail as <code>auto</code> is not a valid value for it.</p>
<p>To get it to work in shorthand notation it has to look like this:</p>
<pre><code>background: url([URL]) 0 0 / auto 749px;
</code></pre>
<p>Also note that there's a value called <code>cover</code>, which may be suitable and more flexible here:</p>
<pre><code>background: url([URL]) 0 0 / cover;
</code></pre>
<p>The <strong>support</strong> for <code>background-size</code> in the shorthand notation is also not very broad, as it's supported in Firefox 18+, Chrome 21+, IE9+ and Opera. It is not supported in Safari at all. Regarding this, I would suggest to always use:</p>
<pre><code>background: url("background1.png");
background-size: auto 749px; /* or cover */
</code></pre>
<p>Here are a few examples and a demo, to demonstrate that behavior. You'll see that Firefox for example shows every image except the fist one. Safari on the other hand shows only the last.</p>
<p><strong>CSS</strong></p>
<pre><code>section {
width: 200px;
height: 100px;
border: 1px solid grey;
}
#section1 {
background: url(http://placehold.it/350x150) auto 100px;
}
#section2 {
background: url(http://placehold.it/350x150) 0 0 / auto 100px;
}
#section3 {
background: url(http://placehold.it/350x150) 0 0 / cover;
}
#section4 {
background: url(http://placehold.it/350x150) 0 0;
background-size: cover;
}
</code></pre>
<p><strong>Demo</strong></p>
<p><a href="http://jsfiddle.net/kDjNA/" rel="nofollow noreferrer">Try before buy</a></p>
<p><strong>Further reading</strong></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background" rel="nofollow noreferrer">MDN CSS reference "background"</a><br>
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-size" rel="nofollow noreferrer">MDN CSS reference "background-size"</a></p>
<blockquote>
<p><strong><'background-size'></strong><br>
See <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-size" rel="nofollow noreferrer">background-size</a>.
This property must be specified after background-position, separated with the '/' character.</p>
</blockquote> |
46,989,454 | class vs className in React 16 | <p>I saw that React 16 allows for attributes to be passed through to the DOM. So, that means 'class' can be used instead of className, right?</p>
<p>I'm just wondering if there are advantages to still using className over class, besides being backwards compatible with previous versions of React. </p> | 46,991,278 | 12 | 1 | null | 2017-10-28 11:56:37.233 UTC | 16 | 2022-05-09 00:27:56.767 UTC | null | null | null | null | 8,847,897 | null | 1 | 105 | reactjs | 68,693 | <p><code>class</code> is a keyword in javascript and JSX is an extension of javascript. That's the principal reason why React uses <code>className</code> instead of <code>class</code>.</p>
<p>Nothing has changed in that regard.</p>
<p>To expand this a bit more. A <em>keyword</em> means that a token has a special meaning in a language syntax. For example in:</p>
<pre><code>class MyClass extends React.Class {
</code></pre>
<p>Token <code>class</code> denotes that the next token is an identifier and what follows is a class declaration. See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords" rel="nofollow noreferrer">Javascript Keywords + Reserved Words</a>.</p>
<p>The fact that a token is a keyword means that we cannot use it in some expressions, e.g.</p>
<pre><code>// invalid in older versions on Javascript, valid in modern javascript
const props = {
class: 'css class'
}
// valid in all versions of Javascript
const props = {
'class': 'css class'
};
// invalid!
var class = 'css';
// valid
var clazz = 'css';
// valid
props.class = 'css';
// valid
props['class'] = 'css';
</code></pre>
<p>One of the problems is that nobody can know whether some other problem won't arise in the future. Every programming language is still evolving and <code>class</code> can be actually used in some new conflicting syntax.</p>
<p>No such problems exist with <code>className</code>.</p> |
25,549,177 | Change composer global path (Windows) | <p>Composer uses <code>%APPDATA%\Composer</code> directory by default for global packages.<br>
So I need to add <code>%APPDATA%\Composer\vendor\bin</code> path to my user PATH environment variable.</p>
<p>Can I change installation directory to something like <code>C:\php\composer</code>? How can I do it?</p> | 25,569,354 | 3 | 0 | null | 2014-08-28 12:45:08.48 UTC | 7 | 2019-11-24 11:12:57.67 UTC | null | null | null | null | 966,972 | null | 1 | 25 | php|windows|path|composer-php | 101,519 | <p>I found an answer in the source code: <a href="https://github.com/composer/composer/blob/master/src/Composer/Factory.php#L45" rel="noreferrer">https://github.com/composer/composer/blob/master/src/Composer/Factory.php#L45</a></p>
<p>So environment variable <code>COMPOSER_HOME</code> must be defined as <code>C:\php\composer</code>.</p> |
8,678,674 | How to extract date part from a datetime in vb.net | <p>I have a sql query which extract a field of datatype <code>smalldatetime</code>. I read this field using datareader, convert it to string and store it in a string variable.</p>
<p>I get the string as <strong>1/1/2012 12:00:00 AM</strong> ,here i want to use only date part of this string and i have nothing to do with the time.</p>
<p>How can i cut only the date from the string and get the output as <strong>1/1/2012</strong>?</p> | 8,678,694 | 4 | 0 | null | 2011-12-30 10:52:40.233 UTC | null | 2018-02-28 20:29:58.807 UTC | null | null | null | null | 243,680 | null | 1 | 6 | asp.net|vb.net|datetime|date | 57,329 | <p>You may convert string to date type using Date.Parse() and use <code>ToShortDateString()</code></p>
<pre><code>Dim dt as Date = Date.Parse(dateString)
Dim dateString=dt.ToShortDateString()
</code></pre>
<p>As you said the type of field is smalldatetime then use <code>DataReader.GetDateTime(column_ordinal).ToString("d")</code> method or <code>DataReader.GetDateTime(column_ordinal).ToShortDateString()</code></p> |
8,448,179 | Mongodb -- include or exclude certain elements with c# driver | <p>How would I translate this mongo query to a Query.EQ statement in C#?</p>
<pre><code>db.users.find({name: 'Bob'}, {'_id': 1});
</code></pre>
<p>In other words, I don't want everything returned to C# -- Just the one element I need, the _id. As always, the <a href="http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-FindandFindAsmethods" rel="noreferrer">Mongo C# Driver tutorial</a> is not helpful.</p> | 8,448,633 | 4 | 0 | null | 2011-12-09 16:01:04.21 UTC | 15 | 2019-05-23 11:37:53.29 UTC | 2011-12-23 10:47:29.56 UTC | null | 508,601 | null | 789,476 | null | 1 | 34 | c#|mongodb|mongodb-.net-driver | 26,658 | <p><strong>Update:</strong> With new driver version (1.6+) you can avoid fields names hard-coding by using linq instead:</p>
<pre><code>var users = usersCollection.FindAllAs<T>()
.SetFields(Fields<T>.Include(e => e.Id, e => e.Name));
</code></pre>
<hr>
<p>You can do it via <code>SetFields</code> method of mongodb cursor:</p>
<pre><code>var users = usersCollection.FindAllAs<T>()
.SetFields("_id") // include only _id
.ToList();
</code></pre>
<p>By default <code>SetFields</code> includes specified fields. If you need exclude certain fields you can use:</p>
<pre><code>var users = usersCollection.FindAllAs<T>()
.SetFields(Fields.Exclude("_id")) // exclude _id field
.ToList();
</code></pre>
<p>Or you can use them together:</p>
<pre><code>var users = usersCollection.FindAllAs<T>()
.SetFields(Fields.Exclude("_id") // exclude _id field
.Include("name")) // include name field
.ToList();
</code></pre> |
8,641,251 | How do I center list items inside a UL element? | <p>How do I center list items inside a ul without using extra divs or elements. I have the following. I thought <code>text-align:center</code> would do the trick. I can't seem to figure it out. </p>
<pre><code><style>
ul {
width:100%;
background:red;
height:20px;
text-align:center;
}
li {
display:block;
float:left;
background:blue;
color:white;
margin-right:10px;
}
</style>
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</code></pre>
<p>Check jsfiddle <a href="http://jsfiddle.net/3Ezx2/1/" rel="noreferrer">http://jsfiddle.net/3Ezx2/1/</a></p> | 8,641,277 | 14 | 0 | null | 2011-12-27 04:45:11.247 UTC | 17 | 2021-05-09 04:17:53.31 UTC | 2011-12-27 05:00:59.677 UTC | null | 234,175 | null | 635,300 | null | 1 | 65 | html|css | 253,145 | <p>write <code>display:inline-block</code> instead of <code>float:left</code>.</p>
<pre><code>li {
display:inline-block;
*display:inline; /*IE7*/
*zoom:1; /*IE7*/
background:blue;
color:white;
margin-right:10px;
}
</code></pre>
<h2><a href="http://jsfiddle.net/3Ezx2/3/" rel="noreferrer">http://jsfiddle.net/3Ezx2/3/</a></h2> |
26,873,401 | difference between cin.get() and cin.getline() | <p>I am new to programming, and I have some questions on <code>get()</code> and <code>getline()</code> functions in C++.</p>
<p>My understanding for the two functions:</p>
<p>The <code>getline()</code> function reads a whole line, and using the newline character transmitted by the Enter key to mark the end of input. The <code>get()</code> function is much like <code>getline()</code> but rather than read and discard the newline character, <code>get()</code> leaves that character in the input queue.</p>
<p>The book(C++ Primer Plus) that I am reading is suggesting using <code>get()</code> over <code>getline()</code>. My confusion is that isn't <code>getline()</code> safer than <code>get()</code> since it makes sure to end line with <code>'\n'</code>. On the other hand, <code>get()</code> will just hangs the character in the input queue, thus potentially causing problem? </p> | 26,873,726 | 5 | 0 | null | 2014-11-11 19:58:22.62 UTC | 8 | 2021-09-29 17:15:41.56 UTC | 2014-11-11 20:10:09.623 UTC | null | 2,586,447 | null | 4,072,443 | null | 1 | 14 | c++|get|cin|getline | 60,801 | <p>There are an equivalent number of advantages and drawbacks, and -essentially- all depends on what you are reading: <code>get()</code> leaves the delimiter in the queue thus letting you able to consider it as part of the next input. <code>getline()</code> discards it, so the next input will be just after it.</p>
<p>If you are talking about the newline character from a console input,it makes perfectly sense to discard it, but if we consider an input from a file, you can use as "delimiter" the beginning of the next field.</p>
<p>What is "good" or "safe" to do, depends on what you are doing.</p> |
30,331,806 | Test expected exceptions in Kotlin | <p>In Java, the programmer can specify expected exceptions for JUnit test cases like this:</p>
<pre><code>@Test(expected = ArithmeticException.class)
public void omg()
{
int blackHole = 1 / 0;
}
</code></pre>
<p>How would I do this in Kotlin? I have tried two syntax variations, but none of them worked:</p>
<pre><code>import org.junit.Test
// ...
@Test(expected = ArithmeticException) fun omg()
Please specify constructor invocation;
classifier 'ArithmeticException' does not have a companion object
@Test(expected = ArithmeticException.class) fun omg()
name expected ^
^ expected ')'
</code></pre> | 30,575,351 | 12 | 0 | null | 2015-05-19 17:01:27.41 UTC | 14 | 2021-12-01 21:53:22.743 UTC | 2020-10-15 20:17:45.453 UTC | null | 252,000 | null | 252,000 | null | 1 | 131 | unit-testing|kotlin|testing|exception|junit4 | 77,559 | <p>The Kotlin translation of the Java example for <strong>JUnit 4.12</strong> is:</p>
<pre><code>@Test(expected = ArithmeticException::class)
fun omg() {
val blackHole = 1 / 0
}
</code></pre>
<p>However, <strong>JUnit 4.13</strong> <a href="https://github.com/junit-team/junit4/blob/HEAD/doc/ReleaseNotes4.13.md" rel="noreferrer">introduced</a> two <code>assertThrows</code> methods for finer-granular exception scopes:</p>
<pre><code>@Test
fun omg() {
// ...
assertThrows(ArithmeticException::class.java) {
val blackHole = 1 / 0
}
// ...
}
</code></pre>
<p>Both <code>assertThrows</code> methods return the expected exception for additional assertions:</p>
<pre><code>@Test
fun omg() {
// ...
val exception = assertThrows(ArithmeticException::class.java) {
val blackHole = 1 / 0
}
assertEquals("/ by zero", exception.message)
// ...
}
</code></pre> |
43,689,271 | Where's docker's daemon.json? (missing) | <p>From <a href="https://docs.docker.com/engine/reference/commandline/dockerd//" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>The default location of the configuration file on Linux is
/etc/docker/daemon.json</p>
</blockquote>
<p>But I don't have it on my fresh docker installation:</p>
<pre><code># docker --version
Docker version 17.03.1-ce, build c6d412e
# ls -la /etc/docker/
total 12
drwx------ 2 root root 4096 Apr 28 17:58 .
drwxr-xr-x 96 root root 4096 Apr 28 17:58 ..
-rw------- 1 root root 244 Apr 28 17:58 key.json
# lsb_release -cs
trusty
</code></pre> | 43,689,496 | 7 | 0 | null | 2017-04-28 21:40:03.083 UTC | 10 | 2022-03-23 11:05:56.143 UTC | 2018-09-18 02:08:59.95 UTC | null | 5,556,676 | null | 1,943,849 | null | 1 | 82 | ubuntu|docker|ubuntu-14.04 | 92,821 | <p>The default config file path on Linux is <code>/etc/docker/daemon.json</code> like you said, but it doesn't exist by default. You can write one yourself and put additional docker daemon configuration stuff in there instead of passing in those configuration options into the command line. You don't even have to do <code>dockerd --config-file /etc/docker/daemon.json</code> since that's the default path, but it can be useful to make it explicit for others who are inspecting the system.</p>
<p>Also ensure that any configuration you set in <code>/etc/docker/daemon.json</code> doesn't conflict with options passed into the command line evocation of <code>dockerd</code>. For reference:</p>
<blockquote>
<p>The options set in the configuration file must not conflict with options set via flags. The docker daemon fails to start if an option is duplicated between the file and the flags, regardless their value.</p>
</blockquote> |
123,335 | What causes java.lang.IllegalStateException: Post too large in tomcat / mod_jk | <p>what configuration needs to be tweaked, and where does it live, in order to increase the maximum allowed post size?</p> | 123,383 | 3 | 0 | null | 2008-09-23 19:45:55.517 UTC | 4 | 2014-07-29 18:45:08.883 UTC | null | null | null | masukomi | 13,973 | null | 1 | 8 | java|tomcat|mod-jk | 42,632 | <p>Apache Tomcat by default sets a limit on the maximum size of HTTP POST requests it accepts. In Tomcat 5, this limit is set to 2 MB. When you try to upload files larger than 2 MB, this error can occur.</p>
<p>The solution is to reconfigure Tomcat to accept larger POST requests, either by increasing the limit, or by disabling it. This can be done by editing [TOMCAT_DIR]/conf/server.xml. Set the Tomcat configuration parameter maxPostSize for the HTTPConnector to a larger value (in bytes) to increase the limit. Setting it to 0 in will disable the size check. See the <a href="http://tomcat.apache.org/tomcat-5.5-doc/config/http.html" rel="noreferrer">Tomcat Configuration Reference</a> for more information. </p> |
480,083 | What is a Lisp image? | <p>Essentially, I would like to know what a Lisp image is? Is it a slice of memory containing the Lisp interpreter and one or more programs or what?</p> | 585,784 | 3 | 2 | null | 2009-01-26 15:09:23.653 UTC | 9 | 2017-04-06 07:14:56.37 UTC | 2013-06-05 17:31:04.603 UTC | mac | 133,203 | mac | 53,943 | null | 1 | 28 | lisp|common-lisp | 6,181 | <p><strong>The Lisp image as dumped memory</strong></p>
<p>The image is usually a file. It is a dump of the memory of a Lisp system. It contains all functions (often compiled to machine code), variable values, symbols, etc. of the Lisp system. It is a snapshot of a running Lisp. </p>
<p>To create an image, one starts the Lisp, uses it for a while and then one dumps an image (the name of the function to do that depends on the implementation).</p>
<p><strong>Using a Lisp image</strong></p>
<p>Next time one restarts Lisp, one can use the dumped image and gets a state back roughly where one was before. When dumping an image one can also tell the Lisp what it should do when the dumped image is started. That way one can reconnect to servers, open files again, etc.</p>
<p>To start such a Lisp system, one needs a kernel and an image. Sometimes the Lisp can put both into a single file, so that an executable file contains both the kernel (with some runtime functionality) and the image data.</p>
<p>On a Lisp Machine (a computer, running a Lisp operating system) a kind of boot loader (the FEP, Front End Processor) may load the image (called 'world') into memory and then start this image. In this case there is no kernel and all that is running on the computer is this Lisp image, which contains all functionality (interpreter, compiler, memory management, GC, network stack, drivers, ...). Basically it is an OS in a single file.</p>
<p>Some Lisp systems will optimize the memory before dumping an image. They may do a garbage collection, order the objects in memory, etc.</p>
<p><strong>Why use images?</strong></p>
<p>Why would one use images? It saves time to load things and one can give preconfigured Lisp systems with application code and data to users. Starting a Common Lisp implementation with a saved image is usually fast - a few milliseconds on a current computer.</p>
<p>Since the Lisp image may contain a lot of functionality (a compiler, even a development environment, lots of debugging information, ...) it is typically several megabytes in size.</p>
<p>Using images in Lisp is very similar to what Smalltalk systems do. Squeak for example also uses an image of Smalltalk code and data and a runtime executable. There is a practical difference: most current Lisp systems use compiled machine code. Thus the image is not portable between different processor architectures (x86, x86-64, SPARC, POWER, ARM, ...) or even operating systems.</p>
<p><strong>History</strong></p>
<p>Such Lisp images have been in use since a long time. For example the function <code>SYSOUT</code> in BBN Lisp from 1967 created such an image. <code>SYSIN</code> would read such an image at start.</p>
<p><strong>Examples for functions saving images</strong></p>
<p>For an example see the function <a href="http://www.lispworks.com/documentation/lw51/LWRM/html/lwref-240.htm#marker-1041670" rel="noreferrer">save-image</a> of <a href="http://www.lispworks.com/" rel="noreferrer">LispWorks</a> or read the <a href="http://www.sbcl.org" rel="noreferrer">SBCL</a> manual on <a href="http://www.sbcl.org/manual/#Saving-a-Core-Image" rel="noreferrer">saving core images</a>.</p> |
895,444 | Java Garbage Collection Log messages | <p>I have configured java to dump garbage collection information into the logs (<a href="http://wiki.zimbra.com/index.php?title=When_to_Turn_On_Verbose_GC" rel="noreferrer">verbose GC</a>). I am unsure of what the garbage collection entries in the logs mean. A sample of these entries are posted below. I've searched around on <a href="http://www.google.com/search?q=PSYoungGen" rel="noreferrer">Google</a> and have not found solid explanations.</p>
<p>I have some reasonable guesses, but I'm looking for answers which provide strict definitions of what the numbers in the entries mean, backed up by credible sources. An automatic +1 to all answers which cite sun documentation. My questions are:</p>
<ol>
<li>What does PSYoungGen refer to? I assume it has something to do with the previous (younger?) generation, but what exactly?</li>
<li>What is the difference between the second triplet of numbers and the first?</li>
<li>Why is a name(PSYoungGen) specified for the first triplet of numbers but not the second?</li>
<li>What does each number (memory size) in the triplet mean. For example in 109884K->14201K(139904K), is the memory before GC 109884k and then it is reduced to 14201K. How is the third number relevant? Why would we require a second set of numbers?</li>
</ol>
<blockquote>
<p>8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)]
691015K->595332K(1119040K), 0.0454530
secs]</p>
<p>8112.111: [GC [PSYoungGen: 126649K->15528K(142336K)]
707780K->605892K(1121472K), 0.0934560
secs]</p>
<p>8112.802: [GC [PSYoungGen: 130344K->3732K(118592K)]
720708K->607895K(1097728K), 0.0682690
secs]</p>
</blockquote> | 895,489 | 3 | 1 | null | 2009-05-21 22:03:26.413 UTC | 71 | 2017-09-18 08:30:51.107 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 74,359 | null | 1 | 98 | java|logging|garbage-collection | 172,116 | <p>Most of it is explained in the <a href="http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html" rel="noreferrer">GC Tuning Guide</a> (which you would do well to read anyway).</p>
<blockquote>
<p>The command line option <code>-verbose:gc</code> causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application: </p>
<pre><code>[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]
</code></pre>
<p>Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., <code>325407K->83000K</code> from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations. </p>
<p>The next number in parentheses (e.g., <code>(776768K)</code> again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine. </p>
<p>The last item on the line (e.g., <code>0.2300771 secs</code>) indicates the time taken to perform the collection; in this case approximately a quarter of a second. </p>
<p>The format for the major collection in the third line is similar. </p>
<p><strong>The format of the output produced by <code>-verbose:gc</code> is subject to change in future releases.</strong> </p>
</blockquote>
<p>I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?</p> |
6,414,152 | Navigating / scraping hashbang links with javascript (phantomjs) | <p>I'm trying to download the HTML of a website that is almost entirely generated by JavaScript. So, I need to simulate browser access and have been playing around with <a href="http://code.google.com/p/phantomjs/" rel="nofollow noreferrer">PhantomJS</a>. Problem is, the site uses hashbang URLs and I can't seem to get PhantomJS to process the hashbang -- it just keeps calling up the homepage.</p>
<p>The site is <a href="http://www.regulations.gov" rel="nofollow noreferrer">http://www.regulations.gov</a>. The default takes you to #!home. I've tried using the following code (from <a href="https://stackoverflow.com/questions/5490438/phantomjs-and-getting-modified-dom">here</a>) to try and process different hashbangs.</p>
<pre><code>if (phantom.state.length === 0) {
if (phantom.args.length === 0) {
console.log('Usage: loadreg_1.js <some hash>');
phantom.exit();
}
var address = 'http://www.regulations.gov/';
console.log(address);
phantom.state = Date.now().toString();
phantom.open(address);
} else {
var hash = phantom.args[0];
document.location = hash;
console.log(document.location.hash);
var elapsed = Date.now() - new Date().setTime(phantom.state);
if (phantom.loadStatus === 'success') {
if (!first_time) {
var first_time = true;
if (!document.addEventListener) {
console.log('Not SUPPORTED!');
}
phantom.render('result.png');
var markup = document.documentElement.innerHTML;
console.log(markup);
phantom.exit();
}
} else {
console.log('FAIL to load the address');
phantom.exit();
}
}
</code></pre>
<p>This code produces the correct hashbang (for instance, I can set the hash to '#!contactus') but it doesn't dynamically generate any different HTML--just the default page. It does, however, correctly output that has when I call <code>document.location.hash</code>.</p>
<p>I've also tried to set the initial address to the hashbang, but then the script just hangs and doesn't do anything. For example, if I set the url to <code>http://www.regulations.gov/#!searchResults;rpp=10;po=0</code> the script just hangs after printing the address to the terminal and nothing ever happens.</p> | 6,472,837 | 1 | 5 | null | 2011-06-20 16:04:06.043 UTC | 9 | 2015-03-10 14:58:35.577 UTC | 2017-05-23 12:08:01.54 UTC | null | -1 | null | 321,838 | null | 1 | 9 | javascript|web-scraping|hashbang|phantomjs | 3,201 | <p>The issue here is that the content of the page loads asynchronously, but you're expecting it to be available as soon as the page is loaded. </p>
<p>In order to scrape a page that loads content asynchronously, you need to wait to scrape until the content you're interested in has been loaded. Depending on the page, there might be different ways of checking, but the easiest is just to check at regular intervals for something you expect to see, until you find it.</p>
<p>The trick here is figuring out what to look for - you need something that won't be present on the page until your desired content has been loaded. In this case, the easiest option I found for top-level pages is to manually input the H1 tags you expect to see on each page, keying them to the hash:</p>
<pre><code>var titleMap = {
'#!contactUs': 'Contact Us',
'#!aboutUs': 'About Us'
// etc for the other pages
};
</code></pre>
<p>Then in your success block, you can set a recurring timeout to look for the title you want in an <code>h1</code> tag. When it shows up, you know you can render the page:</p>
<pre><code>if (phantom.loadStatus === 'success') {
// set a recurring timeout for 300 milliseconds
var timeoutId = window.setInterval(function () {
// check for title element you expect to see
var h1s = document.querySelectorAll('h1');
if (h1s) {
// h1s is a node list, not an array, hence the
// weird syntax here
Array.prototype.forEach.call(h1s, function(h1) {
if (h1.textContent.trim() === titleMap[hash]) {
// we found it!
console.log('Found H1: ' + h1.textContent.trim());
phantom.render('result.png');
console.log("Rendered image.");
// stop the cycle
window.clearInterval(timeoutId);
phantom.exit();
}
});
console.log('Found H1 tags, but not ' + titleMap[hash]);
}
console.log('No H1 tags found.');
}, 300);
}
</code></pre>
<p>The above code works for me. But it won't work if you need to scrape search results - you'll need to figure out an identifying element or bit of text that you can look for without having to know the title ahead of time.</p>
<p><strong>Edit</strong>: Also, it looks like the <a href="http://code.google.com/p/phantomjs/wiki/Interface" rel="noreferrer">newest version of PhantomJS</a> now triggers an <code>onResourceReceived</code> event when it gets new data. I haven't looked into this, but you might be able to bind a listener to this event to achieve the same effect.</p> |
35,097,193 | Can I bundle the Visual Studio 2015 C++ Redistributable DLL's with my application? | <p>I've built a C++ application using Microsoft Visual Studio 2015 Community Edition. I'm using Advanced Installer to make sure that the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48145">Visual C++ Redistributable for Visual Studio 2015</a> is a prerequisite.</p>
<p>However, the redistributable's installer isn't perfect. Some of my users have reported that the redistributable installer hangs, or it fails to install when it says it does, and then users get the "This program can't start because MSVCP140.dll is missing from your computer" error.</p>
<p>According to Microsoft, <a href="https://msdn.microsoft.com/en-us/library/ms235299.aspx">I can now package the redistributable DLLs along with my application, though they don't recommend it:</a></p>
<blockquote>
<p>To deploy redistributable Visual C++ files, you can use the Visual C++ Redistributable Packages (VCRedist_x86.exe, VCRedist_x64.exe, or VCRedist_arm.exe) that are included in Visual Studio. ... It's also possible to directly install redistributable Visual C++ DLLs in the application local folder, which is the folder that contains your executable application file. For servicing reasons, we do not recommend that you use this installation location.</p>
</blockquote>
<p>There are 4 files in <code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\x64\Microsoft.VC140.CRT</code>. Does that mean I just need to copy them to my application's directory during the install process?</p>
<ul>
<li>MyApp.exe</li>
<li>concrt140.dll</li>
<li>msvcp140.dll</li>
<li>vccorlib140.dll</li>
<li>vcruntime140.dll</li>
</ul>
<p>Is this OK to do? Do I need to show a license? Why aren't more people doing this instead of requiring yet another preinstall of the redistributable?</p> | 35,098,577 | 3 | 2 | null | 2016-01-30 02:10:00.163 UTC | 13 | 2022-09-08 10:27:38.46 UTC | null | null | null | null | 102,704 | null | 1 | 40 | c++|windows|visual-studio|dll|visual-studio-2015 | 21,253 | <blockquote>
<p>There are 4 files in <code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\x64\Microsoft.VC140.CRT</code>. Does that mean I just need to copy them to my application's directory during the install process?</p>
</blockquote>
<p>Yes, and the paragraph you quoted means just that.</p>
<blockquote>
<p>Is this OK to do? Do I need to show a license? Why aren't more people doing this instead of requiring yet another preinstall of the redistributable?</p>
</blockquote>
<p>Technically, that's OK to do. If you want to be pedantic about it, you may include a note in the <code>readme</code> or <code>help/about</code> to the effect that <code>VC++ 2015 redistributables provided in "local deployment" mode</code> as explicitly allowed by Microsoft's <a href="https://docs.microsoft.com/en-us/cpp/windows/deployment-in-visual-cpp?view=msvc-160" rel="nofollow noreferrer">Deployment in Visual C++</a> (with more links to the file lists and licenses at <a href="https://docs.microsoft.com/en-us/cpp/windows/redistributing-visual-cpp-files?view=msvc-160" rel="nofollow noreferrer">Redistributing Visual C++ Files</a>).</p>
<p>As to why more people don't do it, I'd guess that (among those who care at all):</p>
<ul>
<li>for a single module app like <code>MyApp.exe</code> it's easier to build it with everything linked statically as to eliminate external dependencies to begin with;</li>
<li><em>not</em> including those files saves 1+ MB from the distribution (presumably download) size;</li>
<li>running with private copies of the runtime (<code>"local deployment"</code>) shifts the responsibility of updates to the maintainer, so that in case of a critical/security fix the package would have to be reissued timely - as opposed to <code>"central deployment"</code> where it would likely be delivered via Windows Update, with both the good <em>and</em> bad that may bring.</li>
</ul> |
20,818,858 | Sort Eloquent Collection by created_at | <p>I have a table named 'posts' with the columns: 'post_id int primary increments', 'poster_id int' and 'status text' as well as an array named friends with the columns: 'user_id int primary' and 'friend_ids text'.</p>
<p>I need to grab all the IDs in the friends text column which is easy enough using:</p>
<pre><code>$friends = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);
</code></pre>
<p>Where the data in the text column would look like '1,2,3,' etc.</p>
<p>Then I create an Eloquent Collection object which is also easily done via:</p>
<pre><code>$posts = new \Illuminate\Database\Eloquent\Collection();
</code></pre>
<p>But the problem is I can't figure out how to populate the collection and sort its contents by the Post object's 'created_at' column.</p>
<p>This is what I have at the moment:</p>
<pre><code>foreach ($friends as $id) {
$posts_ = \Post::where('poster_id', $id)->getQuery()
->orderBy('created_at', 'desc')
->get();
foreach($posts_ as $post) {
$posts->add($post);
}
}
</code></pre>
<p>I can't figure out if this code would work or not for sorting the entire collection of posts by the 'created_at' column. I would also need to be able to paginate the entire collection easily.</p>
<p>What is the recommended way of sorting the collection?</p> | 20,819,078 | 3 | 0 | null | 2013-12-28 20:08:12.72 UTC | 3 | 2021-04-06 04:01:25.55 UTC | 2018-07-10 21:07:37.837 UTC | null | 7,142,322 | null | 1,988,708 | null | 1 | 30 | php|collections|laravel|laravel-4|eloquent | 55,997 | <p>If you want to sort a <code>collection</code> you can use the <code>sortBy</code> method by given key</p>
<pre><code>$sorted = $posts->sortBy('created_at');
</code></pre>
<p>Also you can apply a callback function on the <code>collection</code></p>
<pre><code>$sorted = $posts->sortBy(function($post)
{
return $post->created_at;
});
</code></pre>
<p>Hope this helps. For more information on <code>collections</code> you can read the <a href="https://laravel.com/docs/eloquent-collections" rel="noreferrer">docs</a></p> |
1,566,188 | Converting TIFF files to PNG in .Net | <p>I have to build an application in .Net (3.5) to pick up a TIFF file saved from another piece of software and convert it into a PNG so that it can be rendered easily in Internet Explorer. Does anyone know of any libraries (preferably freeware/open source) that will do this conversion for me?</p>
<p>If there aren't any simple ways of getting it to a PNG are there any libraries that I can use to transform it to another IE friendly image format?</p>
<p>I know I can pass a TIFF to the browser and use a plugin to render it but the PCs this is aimed at are locked down and can't install plugins.</p> | 1,566,194 | 2 | 0 | null | 2009-10-14 13:20:44.193 UTC | 9 | 2014-07-07 18:55:33.993 UTC | null | null | null | null | 166,896 | null | 1 | 21 | .net|png|tiff | 24,557 | <pre><code>System.Drawing.
Bitmap.FromFile("your image.tif")
.Save("your image.png", System.Drawing.Imaging.ImageFormat.Png);
</code></pre>
<p>Please, also check this: <a href="http://bytes.com/topic/c-sharp/answers/267798-convert-tiff-images-gif-jpeg" rel="noreferrer">Convert Tiff Images to Gif/Jpeg</a></p> |
45,786,955 | How to compose functions in Rust? | <p>I'm trying to write a function that composes two functions. The initial design is pretty simple: a function that takes two functions and returns a composed function which I can then compose with other functions, since Rust doesn't have rest parameters. I've run into a wall built with frustrating non-helpful compiler errors.</p>
<p>My compose function:</p>
<pre><code>fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
where
F: 'a + Fn(A) -> B + Sized,
G: 'a + Fn(B) -> C + Sized,
{
Box::new(move |x| g(f(x)))
}
</code></pre>
<p>How I would like to use it:</p>
<pre><code>fn main() {
let addAndMultiply = compose(|x| x * 2, |x| x + 2);
let divideAndSubtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(*addAndMultiply, *divideAndSubtract);
println!("Result is {}", finally(10));
}
</code></pre>
<p>The compiler doesn't like that, no matter what I try, the trait bounds are never satisfied. The error is:</p>
<pre class="lang-none prettyprint-override"><code>error[E0277]: the size for values of type `dyn std::ops::Fn(_) -> _` cannot be known at compilation time
--> src/main.rs:13:19
|
13 | let finally = compose(*addAndMultiply, *divideAndSubtract);
| ^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::ops::Fn(_) -> _`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `compose`
--> src/main.rs:1:1
|
1 | / fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
2 | | where
3 | | F: 'a + Fn(A) -> B + Sized,
4 | | G: 'a + Fn(B) -> C + Sized,
5 | | {
6 | | Box::new(move |x| g(f(x)))
7 | | }
| |_^
</code></pre> | 45,792,463 | 3 | 2 | null | 2017-08-20 21:27:35.823 UTC | 37 | 2021-06-14 21:56:33.13 UTC | 2019-04-07 12:58:20.823 UTC | null | 155,423 | null | 6,394,734 | null | 1 | 84 | functional-programming|rust | 15,966 | <p>As <a href="https://stackoverflow.com/a/45792346/5903309">@ljedrz points out</a>, to make it work you only need to reference the composed functions again: </p>
<pre><code>let finally = compose(&*multiply_and_add, &*divide_and_subtract);
</code></pre>
<p>(Note that in Rust, convention dictates that variable names should be in snake_case) </p>
<hr>
<p>However, we can make this better!</p>
<p>Since Rust 1.26, we can use <a href="https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md" rel="noreferrer">abstract return types</a> (previously featured gated as <code>#![feature(conservative_impl_trait)]</code>). This can help you simplify your example greatly, as it allows you to skip the lifetimes, references, <code>Sized</code> constraints and <code>Box</code>es:</p>
<pre><code>fn compose<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| g(f(x))
}
fn main() {
let multiply_and_add = compose(|x| x * 2, |x| x + 2);
let divide_and_subtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(multiply_and_add, divide_and_subtract);
println!("Result is {}", finally(10));
}
</code></pre>
<hr>
<p>Finally, since you mention rest parameters, I suspect that what you actually want is to have a way to chain-compose as many functions as you want in a flexible manner. I wrote this macro for this purpose:</p>
<pre><code>macro_rules! compose {
( $last:expr ) => { $last };
( $head:expr, $($tail:expr), +) => {
compose_two($head, compose!($($tail),+))
};
}
fn compose_two<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| g(f(x))
}
fn main() {
let add = |x| x + 2;
let multiply = |x| x * 2;
let divide = |x| x / 2;
let intermediate = compose!(add, multiply, divide);
let subtract = |x| x - 2;
let finally = compose!(intermediate, subtract);
println!("Result is {}", finally(10));
}
</code></pre> |
29,618,363 | Override debug build type signing config with flavor signing config | <p>I've got an Android app that has 2 flavors: <code>internal</code> and <code>production</code>, and there are 2 build types as well: <code>debug</code> and <code>release</code>.</p>
<p>I'm trying to assign signing configs based on the flavor, which according to the documentation is doable. I've looked and found other answers to this, but none of them seem to work. Everything compiles, but the app is being signed with the debug keystore local to my machine.</p>
<p>Here is my gradle file:</p>
<pre><code>android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
versionCode 1
versionName "1.0.0"
}
signingConfigs {
internal {
storeFile file("../internal.keystore")
storePassword "password"
keyAlias "user"
keyPassword "password"
}
production {
storeFile file("../production.keystore")
storePassword "password"
keyAlias "user"
keyPassword "password"
}
}
productFlavors {
internal {
signingConfig signingConfigs.internal
applicationId 'com.test.test.internal'
}
production {
signingConfig signingConfigs.production
applicationId 'com.test.test'
}
}
buildTypes {
debug {
applicationIdSuffix ".d"
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
variantFilter { variant ->
if (variant.buildType.name.equals('debug')
&& variant.getFlavors().get(0).name.equals('production')) {
variant.setIgnore(true);
}
}
}
</code></pre>
<p>Note: I'm also compiling with <code>classpath 'com.android.tools.build:gradle:1.1.3'</code></p> | 29,618,981 | 1 | 1 | null | 2015-04-14 02:50:04.16 UTC | 9 | 2018-03-02 15:17:28.33 UTC | 2018-03-02 15:17:28.33 UTC | null | 471,744 | null | 471,744 | null | 1 | 23 | android|android-gradle-plugin | 7,978 | <p>It seems that by default, Android has a <code>signingConfig</code> set on the debug build type (the android debug keystore), and when the <code>signingConfig</code> is set for the build type, the <code>signingConfig</code> is ignored for the flavor.</p>
<p>The solution is to set the <code>signingConfig</code> to <code>null</code> on the debug build type. Then the <code>signingConfig</code> given for the flavor will be used instead:</p>
<pre><code>buildTypes {
debug {
// Set to null to override default debug keystore and defer to the product flavor.
signingConfig null
applicationIdSuffix ".d"
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
</code></pre> |
32,365,271 | What's the difference between `git diff --patience` and `git diff --histogram`? | <p><a href="https://stackoverflow.com/questions/19949526/examples-of-different-results-produced-by-the-standard-myers-minimal-patienc">This earlier question</a> asked for the differences between 4 different Git diff strategies, but the only difference that was explained was the difference between <code>myers</code> and <code>patience</code>, which is pretty well explained <a href="http://alfedenzo.livejournal.com/170301.html" rel="noreferrer">elsewhere</a>.</p>
<p>How does the <code>histogram</code> strategy work? What differentiates it from <code>patience</code>? The <a href="https://www.kernel.org/pub/software/scm/git/docs/git-diff.html" rel="noreferrer">git-diff man page</a> only says that it "extends the patience algorithm to "support low-occurrence common elements"." Other pages mention that it's faster, and that it comes from JGit, but they don't explain <em>where or how its algorithm or results will differ from <code>patience</code></em>.</p>
<p><strong>Where can I find a description of the <code>histogram</code> algorithm relative to the <code>patience</code> algorithm</strong>, with the same level of detail as <a href="http://bramcohen.livejournal.com/73318.html" rel="noreferrer">Bram Cohen's original description of the <code>patience</code> algorithm</a>?</p>
<p>(If it's just a matter of implementation performance with no case that will produce different results, why wasn't it just implemented as a new backend for <code>patience</code>?)</p> | 32,367,597 | 1 | 1 | null | 2015-09-03 00:36:00.1 UTC | 23 | 2022-03-30 08:20:29.547 UTC | 2017-05-23 11:54:46.753 UTC | null | -1 | null | 34,799 | null | 1 | 84 | git|algorithm|diff|git-diff | 25,531 | <p>This histogram strategy was introduced in <a href="https://github.com/git/git/blob/77bd3ea9f54f1584147b594abc04c26ca516d987/Documentation/RelNotes/1.7.7.txt#L68-L70" rel="nofollow noreferrer">git 1.7.7 (Sept 2011)</a>, with the following description (as mentioned by the OP)</p>
<blockquote>
<p>"<code>git diff</code>" learned a "<code>--histogram</code>" option to use a different diff generation machinery stolen from <a href="https://github.com/eclipse/jgit" rel="nofollow noreferrer">jgit</a>, which might give better performance.</p>
</blockquote>
<p>JGit includes <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java" rel="nofollow noreferrer"><code>src/org/eclipse/jgit/diff/HistogramDiff.java</code></a> and <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/HistogramDiffTest.java" rel="nofollow noreferrer"><code>tst/org/eclipse/jgit/diff/HistogramDiffTest.java</code></a></p>
<p>The description there is fairly complete:</p>
<blockquote>
<h1>HistogramDiff</h1>
</blockquote>
<blockquote>
<h2>An extended form of Bram Cohen's patience diff algorithm.</h2>
<p>This implementation was derived by using the 4 rules that are outlined in <a href="http://bramcohen.livejournal.com/73318.html" rel="nofollow noreferrer">Bram Cohen's blog</a>, and then was further extended to support low-occurrence common elements.</p>
<p>The basic idea of the algorithm is to <strong>create a histogram of occurrences for each element of sequence A</strong>. Each element of sequence B is then considered in turn. If the element also exists in sequence A, and has a lower occurrence count, the positions are considered as a candidate for the longest common subsequence (LCS).<br />
After scanning of B is complete the LCS that has the lowest number of occurrences is chosen as a split point. The region is split around the LCS, and the algorithm is recursively applied to the sections before and after the LCS.</p>
<p><strong>By always selecting a LCS position with the lowest occurrence count, this algorithm behaves exactly like Bram Cohen's patience diff whenever there is a unique common element available between the two sequences.<br />
When no unique elements exist, the lowest occurrence element is chosen instead</strong>.<br />
This offers more readable diffs than simply falling back on the standard Myers' <code>O(ND)</code> algorithm would produce.</p>
<p>To prevent the algorithm from having an <code>O(N^2)</code> running time, an upper limit on the number of unique elements in a histogram bucket is configured by <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java#L119-L131" rel="nofollow noreferrer"><code>#setMaxChainLength(int)</code></a>.<br />
If sequence A has more than this many elements that hash into the same hash bucket, the algorithm passes the region to <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java#L108-L117" rel="nofollow noreferrer"><code>#setFallbackAlgorithm(DiffAlgorithm)</code></a>.<br />
If no fallback algorithm is configured, the region is emitted as a replace edit.</p>
<p>During scanning of sequence B, any element of A that occurs more than <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java#L119-L131" rel="nofollow noreferrer"><code>#setMaxChainLength(int)</code></a> times is never considered for an LCS match position, even if it is common between the two sequences. This limits the number of locations in sequence A that must be considered to find the LCS,and helps maintain a lower running time bound.</p>
<p>So long as <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java#L119-L131" rel="nofollow noreferrer"><code>#setMaxChainLength(int)</code></a> is a small constant (such as 64), the algorithm runs in <code>O(N * D)</code> time, where <code>N</code> is the sum of the input lengths and <code>D</code> is the number of edits in the resulting <code>EditList</code>.<br />
If the supplied <a href="https://github.com/eclipse/jgit/blob/ebfd62433a58d23af221adfdffed56d9274f4268/org.eclipse.jgit/src/org/eclipse/jgit/diff/HistogramDiff.java#L140" rel="nofollow noreferrer"><code>SequenceComparator</code></a> has a good hash function, this implementation typically out-performs <a href="https://github.com/eclipse/jgit/blob/48b67012d610f9151b425a27a4287eeedfbff0a4/org.eclipse.jgit/src/org/eclipse/jgit/diff/MyersDiff.java" rel="nofollow noreferrer"><code>MyersDiff</code></a>, even though its theoretical running time is the same.</p>
<p>This implementation has an internal limitation that prevents it from handling sequences with more than 268,435,456 (2^28) elements</p>
</blockquote>
<hr />
<p>Note that this kind of algo was <a href="https://github.com/git/git/commit/473ab1659bc6b2483544e404661e4349dc249355" rel="nofollow noreferrer">already used for pack_check, back in 2006 (git 1.3)</a>, for <code>git-verify-pack -v</code>. It was <a href="https://github.com/git/git/commit/d1a0ed187cbea2941a5cc10dcc43f3a7052ce32d" rel="nofollow noreferrer">reused for index-pack in git 1.7.7</a></p>
<hr />
<p><a href="https://github.com/git/git/commit/8c912eea94a2138e8bc608f7c390eb0b313effb0" rel="nofollow noreferrer">Commit 8c912ee</a> actually introduced <code>--histogram</code> to diff:</p>
<blockquote>
<p>Port JGit's HistogramDiff algorithm over to C. Rough numbers (TODO) show
that it is faster than its <code>--patience</code> cousin, as well as the default Meyers algorithm.</p>
<p>The implementation has been reworked to <strong>use structs and pointers,
instead of bitmasks, thus doing away with JGit's <code>2^28</code> line limit</strong>.</p>
<p>We also use <code>xdiff</code>'s default hash table implementation (<code>xdl_hash_bits()</code>
with <code>XDL_HASHLONG()</code>) for convenience.</p>
</blockquote>
<p><a href="https://github.com/git/git/commit/85551232b56e763ecfcc7222e0858bac4e962c80" rel="nofollow noreferrer">commit 8555123 (git 1.7.10, April 2012)</a> added:</p>
<blockquote>
<p>8c912ee (teach <code>--histogram</code> to <code>diff</code>, 2011-07-12) claimed histogram diff
was faster than both Myers and patience.</p>
<p>We have since incorporated a performance testing framework, so add a
test that compares the various diff tasks performed in a real '<code>log -p</code>'
workload.<br />
This does indeed show that histogram diff slightly beats Myers, while patience is much slower than the others.</p>
</blockquote>
<p>Finally, <a href="https://github.com/git/git/commit/07ab4dec80f1c24660ed4bc371849fb4f11a4ee3" rel="nofollow noreferrer">commit 07ab4de (git 1.8.2, March 2013)</a> add</p>
<blockquote>
<h2><code>config</code>: Introduce <code>diff.algorithm</code> variable</h2>
</blockquote>
<blockquote>
<p>Some users or projects prefer different algorithms over others, e.g. patience over myers or similar.<br />
However, specifying appropriate argument every time diff is to be used is impractical. Moreover, creating an alias doesn't play nicely with other tools based on diff (<code>git-show</code> for instance).</p>
<p>Hence, a configuration variable which is able to set specific algorithm is needed.<br />
For now, these four values are accepted:</p>
<ul>
<li>'<code>myers</code>' (which has the same effect as not setting the config variable at all),</li>
<li>'<code>minimal</code>',</li>
<li>'<code>patience</code>' and</li>
<li>'<code>histogram</code>'.</li>
</ul>
</blockquote>
<p><a href="https://github.com/git/git/commit/07924d4d50e5304fb53eb60aaba8aef31d4c4e5e" rel="nofollow noreferrer">Commit 07924d4</a> added concurrently the <code>--diff-algorithm</code> command line option.<br />
As the OP <a href="https://stackoverflow.com/users/34799/stuart-p-bentley">Stuart P. Bentley</a> mentions <a href="https://stackoverflow.com/questions/32365271/whats-the-difference-between-git-diff-patience-and-git-diff-histogram/32367597?noredirect=1#comment52640649_32367597">in the comments</a>:</p>
<blockquote>
<p><strong>you can configure Git to use histogram by default</strong> with:</p>
<pre><code>git config --global diff.algorithm histogram
</code></pre>
</blockquote>
<hr />
<p>Update: Git 2.12 (Q1 2017) will retire the "fast hash" that had disastrous performance issues in some corner cases.</p>
<p>See <a href="https://github.com/git/git/commit/1f7c9261320576fcaaa5b4e50ad73336b17183e8" rel="nofollow noreferrer">commit 1f7c926</a> (01 Dec 2016) by <a href="https://github.com/peff" rel="nofollow noreferrer">Jeff King (<code>peff</code>)</a>.
<sup>(Merged by <a href="https://github.com/gitster" rel="nofollow noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/731490bf06792a4c96b61965cba2a0e430118e78" rel="nofollow noreferrer">commit 731490b</a>, 19 Dec 2016)</sup></p>
<blockquote>
<h2><code>xdiff</code>: drop <code>XDL_FAST_HASH</code></h2>
</blockquote>
<blockquote>
<p><strong>The <code>xdiff</code> code hashes every line of both sides of a diff, and then compares those hashes to find duplicates</strong>. The overall performance depends both on how fast we can compute the hashes, but also on how many hash collisions we see.</p>
<p>The idea of <code>XDL_FAST_HASH</code> is to speed up the hash computation.<br />
But the generated hashes have worse collision behavior. This means that in some cases it speeds diffs up (running "<code>git log -p</code>" on <code>git.git</code> improves by <code>~8%</code> with it), but in others it can slow things down. <a href="http://public-inbox.org/git/[email protected]/" rel="nofollow noreferrer">One pathological case saw over a 100x slowdown</a>.</p>
<p>There may be a better hash function that covers both properties, but in the meantime we are better off with the original hash. It's slightly slower in the common case, but it has fewer surprising pathological cases.</p>
</blockquote>
<hr />
<p>Note: "<code>git diff --histogram</code>" had a bad memory usage pattern, which has
been rearranged to reduce the peak usage, with Git 2.19 (Q3 2018).</p>
<p>See <a href="https://github.com/git/git/commit/79cb2ebb92c18af11edf5eea238425d86eef173d" rel="nofollow noreferrer">commit 79cb2eb</a>, <a href="https://github.com/git/git/commit/64c4e8bccde9d357f6b7adf5277c3157b2bd0d42" rel="nofollow noreferrer">commit 64c4e8b</a>, <a href="https://github.com/git/git/commit/c671d4b5990f07ca40b0914ca9be65c626608fca" rel="nofollow noreferrer">commit c671d4b</a>, <a href="https://github.com/git/git/commit/282098506ffb42d151a3c8d324b6b5393a4342a4" rel="nofollow noreferrer">commit 2820985</a> (19 Jul 2018) by <a href="https://github.com/stefanbeller" rel="nofollow noreferrer">Stefan Beller (<code>stefanbeller</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="nofollow noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/57fbd8efb0ac6d85bde612eb06b9ff4415e21503" rel="nofollow noreferrer">commit 57fbd8e</a>, 15 Aug 2018)</sup></p>
<blockquote>
<h2><code>xdiff/xhistogram</code>: move index allocation into <code>find_lcs</code></h2>
</blockquote>
<blockquote>
<p>This fixes a memory issue when recursing a lot, which can be reproduced as</p>
<pre><code>seq 1 100000 >one
seq 1 4 100000 >two
git diff --no-index --histogram one two
</code></pre>
<p>Before this patch, <code>histogram_diff</code> would call itself recursively before
calling <code>free_index</code>, which would mean a lot of memory is allocated during
the recursion and only freed afterwards.</p>
<p>By moving the memory allocation (and its free call) into <code>find_lcs</code>, the memory is free'd before we recurse, such that memory is reused in the next step of the recursion instead of using new memory.</p>
<p>This addresses only the memory pressure, not the run time complexity,
that is also awful for the corner case outlined above.</p>
</blockquote>
<hr />
<p>Note: the patience and histogram algorithms had memory leaks, fixed with Git 2.36 (Q2 2022)</p>
<p>See <a href="https://github.com/git/git/commit/43ad3af380702d9e304140f259480de59320e587" rel="nofollow noreferrer">commit 43ad3af</a>, <a href="https://github.com/git/git/commit/4a37b80e88f8f26a2f56d77c5ad6caa41d572ea8" rel="nofollow noreferrer">commit 4a37b80</a>, <a href="https://github.com/git/git/commit/61f883965f79308b849a55936bee69a33c476c5c" rel="nofollow noreferrer">commit 61f8839</a>, <a href="https://github.com/git/git/commit/9df0fc3d578acfdeb7fa1914fcf0507adb021fa5" rel="nofollow noreferrer">commit 9df0fc3</a> (16 Feb 2022) by <a href="https://github.com/phillipwood" rel="nofollow noreferrer">Phillip Wood (<code>phillipwood</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="nofollow noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/47be28e51e6a3b390e694d868b7da04181e99e96" rel="nofollow noreferrer">commit 47be28e</a>, 09 Mar 2022)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/9df0fc3d578acfdeb7fa1914fcf0507adb021fa5" rel="nofollow noreferrer"><code>xdiff</code></a>: fix a memory leak</h2>
<p><sup>Reported-by: Junio C Hamano</sup><br />
<sup>Signed-off-by: Phillip Wood</sup></p>
</blockquote>
<blockquote>
<p>Although the patience and histogram algorithms initialize the environment they do not free it if there is an error.<br />
In contrast for the Myers algorithm the environment is initalized in <code>xdl_do_diff()</code> and it is freed if there is an error.<br />
Fix this by always initializing the environment in <code>xdl_do_diff()</code> and freeing it there if there is an error.</p>
</blockquote> |
32,503,327 | Glide listener doesn't work | <p>I'm using Glide to load images and I added a listener to know when resource is ready or if there was an error of any type:</p>
<pre><code>Glide.with(mContext)
.load(url)
.placeholder(R.drawable.glide_placeholder)
// use dontAnimate and not crossFade to avoid a bug with custom views
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// do something
return true;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// do something
return true;
}
})
.into(mCustomImageView);
</code></pre>
<p>The app never runs inside <code>onResourceReady</code> or <code>onException</code> but if I remove the listener and let the async download without a callback, it runs correctly:</p>
<pre><code>Glide.with(mContext)
.load(url)
.placeholder(R.drawable.glide_placeholder)
// use dontAnimate and not crossFade to avoid a bug with custom views
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(mCustomImageView);
</code></pre>
<p>I tried also with <code>GlideDrawableImageViewTarget</code> instead of listener to receive callbacks but app runs inside <code>onLoadStarted</code> but never runs inside <code>onLoadCleared</code>, <code>onLoadFailed</code> and <code>onResourceReady</code>.</p> | 32,517,644 | 7 | 2 | null | 2015-09-10 13:31:19.48 UTC | 6 | 2020-09-19 02:21:56.123 UTC | 2015-09-10 14:13:44.487 UTC | null | 4,237,609 | null | 4,237,609 | null | 1 | 52 | android|callback|imageview|android-glide | 50,768 | <p>It seems to be a bug with ImageView's visibility if it's invisible or gone. I opened an issue here: <a href="https://github.com/bumptech/glide/issues/618">https://github.com/bumptech/glide/issues/618</a></p> |
6,101,084 | Division in C++ not working as expected | <p>I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.</p>
<pre><code>#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
</code></pre>
<p>What am I missing?</p> | 6,101,094 | 6 | 0 | null | 2011-05-23 18:06:06.533 UTC | 4 | 2019-04-01 13:31:28.197 UTC | null | null | null | null | 754,499 | null | 1 | 36 | c++|division | 70,505 | <p>You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:</p>
<pre><code> double f = 3.0 / 5;
</code></pre> |
5,764,499 | Decompress gz file using R | <p>I have used <code>?unzip</code> in the past to get at contents of a zipped file using R. This time around, I am having a hard time extracting the files from a .gz file which can be found <a href="http://sourceforge.net/projects/chadwick/files/chadwick-0.5/0.5.3/chadwick-0.5.3.tar.gz/download">here</a>.</p>
<p>I have tried <code>?gzfile</code> and <code>?gzcon</code> but have not been able to get it to work. Any help you can provide will be greatly appreciated.</p> | 5,770,352 | 6 | 0 | null | 2011-04-23 13:45:00.487 UTC | 12 | 2022-02-11 15:14:03.72 UTC | null | null | null | null | 155,406 | null | 1 | 76 | r|gzip | 119,006 | <p>If you really want to uncompress the file, just use the <code>untar</code> function which does support <em>gzip</em>.
E.g.:</p>
<pre><code>untar('chadwick-0.5.3.tar.gz')
</code></pre> |
5,983,845 | PHPExcel very slow - ways to improve? | <p>I am generating reports in .xlsx using PHPExcel. It was okay in the initial testing stages with small data sets (tens of rows, 3 sheets), but now when using it on a real production data with over 500 rows in each sheet, it becomes incredibly slow. 48 seconds to generate a file, and when running a report that combines more information, the whole thing fails with <code>Fatal error: Maximum execution time of 30 seconds exceeded in PHPExcel/Worksheet.php on line 1041</code>. Sometimes it's in another PHPExcel file, so I doubt the exact location is that relevant.</p>
<p>Ideally, I would want to speed it up somehow, if possible. If not, then at least increase the execution limit for this script.</p>
<p>The only suggestions I have seen so far was to style in ranges instead of individual cells. Unfortunately, I already do my styling in ranges and it is rather minimal too. Any other suggestions?</p> | 5,984,286 | 8 | 6 | null | 2011-05-12 20:08:46.26 UTC | 23 | 2021-01-07 09:46:07.983 UTC | null | null | null | null | 362,657 | null | 1 | 51 | php|spreadsheet|phpexcel | 61,675 | <p>Is it populating the worksheet? or saving? that you find too slow?</p>
<p>How are you populating the spreadsheet with the data?</p>
<ul>
<li>Using the <code>fromArray()</code> method is more efficient than populating each individual cell, especially if you use the Advanced Value Binder to set cell datatypes automatically.</li>
<li><p>If you're setting values for every individual cell in a sheet using </p>
<pre><code>$objPHPExcel->getActiveSheet()->setCellValue('A1',$x);
$objPHPExcel->getActiveSheet()->setCellValue('B1',$y);
</code></pre>
<p>use</p>
<pre><code>$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('A1',$x);
$sheet->setCellValue('B1',$y);
</code></pre>
<p>so that you're only accessing the <code>getActiveSheet()</code> method once;
or take advantage of the fluent interface to set multiple cells with only a single call to <code>$objPHPExcel->getActiveSheet()</code></p>
<pre><code>$objPHPExcel->getActiveSheet()->setCellValue('A1',$x)
->setCellValue('B1',$y);
</code></pre></li>
</ul>
<p>You've commented on applying styles to ranges of cells: </p>
<ul>
<li>You also have the option to use <code>applyFromArray()</code> to set a whole variety of style settings in one go.</li>
<li>It's a lot more efficient if you can apply styles to a column or a row rather than simply to a range</li>
</ul>
<p>If you're using formulae in your workbook, when saving:</p>
<ul>
<li><p>Use </p>
<pre><code>$objWriter->setPreCalculateFormulas(false)
</code></pre>
<p>to disable calculating the formulae within PHPExcel itself.</p></li>
</ul>
<p>Those are just a few hints to help boost performance, and there's plenty more suggested in the forum threads. They won't all necessarily help, too much depends on your specific workbook to give any absolutes, but you should be able to improve that slow speed. Even the little notebook that I use for development can write a 3 worksheet, 20 column, 2,000 row Excel 2007 file faster than your production server.</p>
<p><strong>EDIT</strong></p>
<p>If it was possible to simply improve the speed of PHPExcel itself, I'd have done so long ago. As it is, I'm constantly performance testing to see how its speed can be improved. If you want faster speeds than PHPExcel itself can give, then there's a <a href="https://stackoverflow.com/questions/3930975/alternative-for-php-excel">list of alternative libraries here</a>.</p> |
6,286,847 | How do I create an Android Spinner as a popup? | <p>I want to bring up a spinner dialog when the user taps a menu item to allow the user to select an item.</p>
<p>Do I need a separate dialog for this or can I use Spinner directly? I see <a href="http://developer.android.com/reference/android/widget/Spinner.html">this link,</a> mentions a MODE_DIALOG option but it doesn't seem to be defined anymore. AlertDialog may be OK but all the options say "clicking on an item in the list will not dismiss the dialog" which is what I want. Any suggestion?</p>
<p>Ideally, the code would be similar to the case where the spinner is shown on the screen:</p>
<pre><code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(adapter);
// myspinner.showAsDialog() <-- what i want
</code></pre> | 6,288,030 | 11 | 0 | null | 2011-06-09 00:32:56.737 UTC | 20 | 2021-02-26 15:36:11.74 UTC | 2014-03-11 12:08:52.593 UTC | null | 2,902,007 | null | 602,543 | null | 1 | 76 | android|dialog|spinner | 120,563 | <p>You can use an alert dialog</p>
<pre><code> AlertDialog.Builder b = new Builder(this);
b.setTitle("Example");
String[] types = {"By Zip", "By Category"};
b.setItems(types, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
onZipRequested();
break;
case 1:
onCategoryRequested();
break;
}
}
});
b.show();
</code></pre>
<p>This will close the dialog when one of them is pressed like you are wanting. Hope this helps!</p> |
39,049,653 | How to clean old deployed versions in Firebase hosting? | <p>Every time you deploy to Firebase hosting a new deploy version is created so you can roll back and see who deployed. This means that each time every file you deploy is stored and occupying more space.</p>
<p>Other than manually deleting each deployed version one by one, is there any automated way to clean those useless files?</p> | 55,187,864 | 8 | 1 | null | 2016-08-20 01:31:53.78 UTC | 7 | 2020-10-16 16:05:14.723 UTC | 2016-08-20 06:19:54.387 UTC | null | 816,478 | null | 816,478 | null | 1 | 38 | firebase|firebase-hosting | 13,979 | <p>Firebase <strong>finally</strong> implemented a solution for this.</p>
<p>It is now possible to set a limit of retained versions.</p>
<p><a href="https://firebase.google.com/docs/hosting/deploying#set_limit_for_retained_versions" rel="nofollow noreferrer">https://firebase.google.com/docs/hosting/deploying#set_limit_for_retained_versions</a></p>
<p>EDIT: previous link is outdated. Here is a new link that works:</p>
<p><a href="https://firebase.google.com/docs/hosting/usage-quotas-pricing#control-storage-usage" rel="nofollow noreferrer">https://firebase.google.com/docs/hosting/usage-quotas-pricing#control-storage-usage</a></p> |
33,278,246 | flexbox space-between and align right | <p>I have a div with 1 to 3 items and I want them to behave like this : </p>
<ol>
<li><p>Three items : take the whole line with <code>justify-content: space-between</code></p>
<pre><code>+-----------+
| 1 | 2 | 3 |
+-----------+
</code></pre></li>
<li><p>If there is only 1 item, align it to the right.</p>
<pre><code>+-----------+
| | 3 |
+-----------+
</code></pre></li>
</ol>
<p>Here's my code :</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: flex;
width: 300px;
justify-content: space-between;
/* Styling only */
padding: 10px;
background: #ccc;
margin-bottom: 10px;
}
.container div {
/* Styling only */
background: white;
padding: 20px 40px;
width: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div>
1
</div>
<div>
2
</div>
<div>
3
</div>
</div>
<div class="container">
<div>
3
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I've found a solution with <code>direction: rtl</code>, but I hope there's a less hacky solution, and I prefer not to reorder my dom. </p>
<p>Any ideas?</p> | 33,278,430 | 3 | 1 | null | 2015-10-22 09:56:21.567 UTC | 6 | 2020-06-14 08:49:56.03 UTC | 2016-02-16 12:03:35.833 UTC | null | 1,847,249 | null | 1,847,249 | null | 1 | 51 | css|flexbox | 19,844 | <p>There is a selector for that.</p>
<pre><code>.container div:only-child {
margin-left: auto;
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: flex;
width: 300px;
justify-content: space-between;
/* Styling only */
padding: 10px;
background: #ccc;
margin-bottom: 10px;
}
.container div {
/* Styling only */
background: white;
padding: 20px 40px;
width: 10px;
}
.container div:only-child {
align-self: flex-end;
margin-left: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div>
1
</div>
<div>
2
</div>
<div>
3
</div>
</div>
<div class="container">
<div>
3
</div>
</div></code></pre>
</div>
</div>
</p> |
33,448,675 | Babel 6 CLI: Unexpected token export? | <p>I'm trying to run Babel through it's CLI using <code>babel-node</code> but I keep getting the <code>Unexpected token export</code> error. I understand that Babel 6 is all about plugins and that I need to set the plugin through <code>.babelrc</code> but it doesn't seem to work properly. </p>
<p>So here are my questions:</p>
<ul>
<li>Should I be using the <a href="http://babeljs.io/docs/plugins/syntax-export-extensions/#usage" rel="noreferrer">syntax-export-extensions plugin</a>? I've also tried using the alternative method which is <a href="http://babeljs.io/docs/usage/babelrc/#use-via-package-json" rel="noreferrer">setting the plugin through <code>package.json</code></a> but still no luck. </li>
<li>Also, does Babel 6's CLI have a global <code>.babelrc</code> option? It seems tedious if I have to install the plugins for every project that requires it...</li>
</ul>
<p>For those who are curious of what I'm trying to export, then here is the class:</p>
<pre><code>'use strict';
class Factorial {
static solve (num) {
if(num === 0) return 1;
else return num * Factorial.solve(num - 1);
}
}
console.log(Factorial.solve(5))
export default Factorial;
</code></pre> | 33,458,598 | 2 | 2 | null | 2015-10-31 06:17:50.8 UTC | 9 | 2017-05-28 11:53:31.847 UTC | 2015-10-31 06:24:58.35 UTC | null | 1,251,031 | null | 1,251,031 | null | 1 | 11 | javascript|node.js|npm|ecmascript-6|babeljs | 51,575 | <p>The easiest way to get started is to use a <strong>preset</strong>.</p>
<p>First let's install our dependencies:</p>
<pre><code>$ npm install --save-dev babel-cli babel-preset-es2015
</code></pre>
<p>Then add a <code>build</code> script to your package.json that runs Babel: (this is important because it will use your local version of <code>babel-cli</code> instead of a globally installed one)</p>
<pre><code>"build": "babel input.js"
</code></pre>
<p>Your <code>package.json</code> should look like this:</p>
<pre><code>{
"name": "my-module",
"devDependencies": {
"babel-cli": "^6.x.x",
"babel-preset-es2015": "^6.x.x"
},
"scripts": {
"build": "babel input.js -o compiled.js"
}
}
</code></pre>
<p>Finally you want to update your local <code>.babelrc</code> like this:</p>
<pre><code>{
"presets": ["es2015"]
}
</code></pre>
<p>Then you run <code>npm run build</code> and you're all set to go.</p>
<blockquote>
<p>Also, does Babel 6's CLI have a global .babelrc option? It seems tedious if I have to install the plugins for every project that requires it...</p>
</blockquote>
<p>That's a bad idea as it means you can't ever update it without updating every single one of your projects code. Having local versions means this potential error is less likely to occur.</p> |
9,097,201 | How to get current process name in linux? | <p>How can I get the process name in C? The same name, which is in <code>/proc/$pid/status</code>. I do not want to parse that file. Is there any programmatic way of doing this?</p> | 9,097,248 | 8 | 0 | null | 2012-02-01 14:11:10.6 UTC | 12 | 2021-02-28 13:08:13.27 UTC | 2013-06-05 12:37:07.757 UTC | null | 577,603 | null | 649,910 | null | 1 | 30 | c|linux | 69,940 | <p>It's either pointed to by the <code>argv[0]</code> or indeed you can read <code>/proc/self/status</code>. Or you can use <code>getenv("_")</code>, not sure who sets that and how reliable it is.</p> |
9,174,514 | App submission failed due to icon dimensions (0 x 0) | <p>I am trying to submit an app which is only for iPhone. </p>
<p>The error showed " iPhone/iPod Touch: Icon.png: icon dimensions (0 x 0) don't meet the size requirement. The icon file must be 57x57 pixels, in .png format. </p>
<p>May I know why this happens? I try to change the plist setting and i am sure my icon is at the right size. It shows perfectly on my iPhones. </p>
<p>I have searched for few post here but still cannot find the solution. </p>
<p>Could anyone knows the problem? </p>
<p>Thanks </p> | 9,174,614 | 4 | 0 | null | 2012-02-07 10:22:58.413 UTC | 11 | 2012-02-23 21:32:41.083 UTC | null | null | null | null | 794,575 | null | 1 | 36 | iphone|ios|xcode4.2 | 5,403 | <p>According to this solution <a href="https://devforums.apple.com/message/612098#612098" rel="noreferrer">https://devforums.apple.com/message/612098#612098</a> make this steps:</p>
<ol>
<li>Install <a href="https://itunesconnect.apple.com/apploader/ApplicationLoader_2.5.1.dmg" rel="noreferrer">ApplicationLoader_2.5.1.dmg</a> (Just install it, you don't need to launch/use it)</li>
<li>Quit & restart Xcode</li>
<li>Clean Project</li>
<li>Archive (again)</li>
<li>Validate/Submit now works</li>
</ol>
<p>This solution fixed my problems with submission.</p> |
9,387,839 | MySQL IF NOT NULL, then display 1, else display 0 | <p>I'm working with a little display complication here. I'm sure there's an IF/ELSE capability I'm just overlooking.</p>
<p>I have 2 tables I'm querying (customers, addresses). The first has the main record, but the second may or may not have a record to LEFT JOIN to.</p>
<p>I want to display a zero if there is no record in the addresses table.
And I want to only display 1, if a record exists.</p>
<p>What I've attempted so far:</p>
<pre><code>SELECT c.name, COALESCE(a.addressid,0) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123
</code></pre>
<p>This first example does not do it. But I may be utilizing COALESCE wrong.</p>
<p>How can I display a 0, if null, and a 1, if something exists?</p> | 9,387,864 | 7 | 0 | null | 2012-02-22 01:13:18.28 UTC | 29 | 2020-07-15 23:46:00.373 UTC | null | null | null | null | 271,619 | null | 1 | 131 | mysql|if-statement | 411,048 | <p>Instead of <code>COALESCE(a.addressid,0) AS addressexists</code>, use <code>CASE</code>:</p>
<pre><code>CASE WHEN a.addressid IS NOT NULL
THEN 1
ELSE 0
END AS addressexists
</code></pre>
<p>or the simpler:</p>
<pre><code>(a.addressid IS NOT NULL) AS addressexists
</code></pre>
<p>This works because <code>TRUE</code> is displayed as <code>1</code> in MySQL and <code>FALSE</code> as <code>0</code>.</p> |
10,366,402 | Binary Search Tree in C# Implementation | <pre><code>class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class BinaryTreeImp
{
Node root;
static int count = 0;
public BinaryTreeImp()
{
root = null;
}
public Node addNode(int data)
{
Node newNode = new Node(data);
if (root == null)
{
root = newNode;
}
count++;
return newNode;
}
public void insertNode(Node root,Node newNode )
{
Node temp;
temp = root;
if (newNode.data < temp.data)
{
if (temp.left == null)
{
temp.left = newNode;
}
else
{
temp = temp.left;
insertNode(temp,newNode);
}
}
else if (newNode.data > temp.data)
{
if (temp.right == null)
{
temp.right = newNode;
}
else
{
temp = temp.right;
insertNode(temp,newNode);
}
}
}
public void displayTree(Node root)
{
Node temp;
temp = root;
if (temp == null)
return;
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
static void Main(string[] args)
{
BinaryTreeImp btObj = new BinaryTreeImp();
Node iniRoot= btObj.addNode(5);
btObj.insertNode(btObj.root,iniRoot);
btObj.insertNode(btObj.root,btObj.addNode(6));
btObj.insertNode(btObj.root,btObj.addNode(10));
btObj.insertNode(btObj.root,btObj.addNode(2));
btObj.insertNode(btObj.root,btObj.addNode(3));
btObj.displayTree(btObj.root);
System.Console.WriteLine("The sum of nodes are " + count);
Console.ReadLine();
}
}
</code></pre>
<p>This is the code for implementation.The code works fine but if in the displayTree function , i replace it with </p>
<pre><code>public void displayTree(Node root)
{
Node temp;
temp = root;
while(temp!=null)
{
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
}
</code></pre>
<p>an infinite loop is caused. I don't understand what is causing this.Also i would like to know if there is a better way of implementing a BST in C#.</p> | 10,366,538 | 7 | 1 | null | 2012-04-28 18:34:24.417 UTC | 4 | 2018-08-23 13:11:08.02 UTC | 2015-02-25 21:57:09.333 UTC | null | 41,956 | null | 522,497 | null | 1 | 7 | c#|binary-tree | 40,722 | <p>I'm not sure why you need this loop, but answering your question: </p>
<pre><code>while(temp!=null)
{
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
</code></pre>
<p>this code checks if <code>temp</code> is not <code>null</code>, but it will never become null, cause <em>inside</em> the loop you act <strong>only</strong> on the leafs of the temp. That's why you have an infinit loop.</p> |
10,727,699 | Is HTTP 404 an appropriate response for a PUT operation where some linked resource is not found? | <p>Imagine a REST webservice where you are adding items to some type of container. For example, lets say we could add a attendee #789 to a event #456 like this:</p>
<pre><code>PUT http://..../api/v1/events/456/attendees/789
</code></pre>
<p>If either event #456 or attendee #789 do not exist, is it correct to return an HTTP 404 (along with a detailed error payload explaining what the problem was, e.g. <code>{ "error" : { "message" : "Event 456 does not exist" , "code" : "404" } }</code>?</p>
<p>Similarly, what if I am creating something new which refers to another object, but the other object does not exist? For example, imagine I am creating an event at Location #123</p>
<pre><code>PUT http://..../api/v1/event
{ "location": 123, "name": "Party", "date": "2012-05-23", ...etc... }
</code></pre>
<p>If Location #123 does not exist, is it also correct to return 404 (along with detail in response)? If not, what would be appropriate -- just a 400?</p>
<p>According to the HTTP 1.1 spec <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a></p>
<blockquote>
<p><strong>9.6 PUT</strong> ... If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem</p>
</blockquote>
<p>So that would seem to be a good vote for responding with 404. <em>However</em> for some reason I can't quite put my finger on, responding to PUT (or POST) with a 404 seems odd to me... Perhaps it's because 404 means that the resource cannot be found, but in this case our resource is actually a linkage between two other resources, and it's one of those two resources that can't be found.</p>
<p>Don't get too worried about my exact examples here -- they are made up to illustrate the point. The main question is: is 404 an appropriate response to a PUT operation that fails because a linked resource is not found?</p>
<p>It would be excellent if you can point to references -- I'm having a hard time finding any that get into this level of detail and are also sufficiently credible. Especially as regards treatment of resource relationships in REST API design.</p>
<p><strong>Updated thinking</strong> I'm thinking that possibly the first example should return 404, the second should not. The reasoning being that in the first case the resource we're adding uses event 456 and attendee 789 as it's composite primary key; the second case location is only a foreign key. In the second case an error should be returned, but not a 404 -- possibly a 412 Precondition Failed or maybe just a 400 Bad Request. Thoughts? </p> | 10,728,099 | 1 | 1 | null | 2012-05-23 20:55:34.557 UTC | 3 | 2022-06-09 07:21:58.66 UTC | 2012-05-24 15:46:50.41 UTC | null | 77,244 | null | 77,244 | null | 1 | 32 | api|http|rest | 27,470 | <p>There are a number of 4xx <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.5" rel="nofollow noreferrer">HTTP status codes</a>. The most likely are either 404 or 409:</p>
<blockquote>
<p><strong>404 Not Found</strong></p>
<p>The server has not found anything matching the effective request URI.
No indication is given of whether the condition is temporary or
permanent. The 410 (Gone) status code SHOULD be used if the server
knows, through some internally configurable mechanism, that an old
resource is permanently unavailable and has no forwarding address.
This status code is commonly used when the server does not wish to
reveal exactly why the request has been refused, or when no other
response is applicable.</p>
</blockquote>
<blockquote>
<p><strong>409 Conflict</strong></p>
<p>The request could not be completed due to a conflict with the current
state of the resource. This code is only allowed in situations where
it is expected that the user might be able to resolve the conflict
and resubmit the request. The response body SHOULD include enough
information for the user to recognize the source of the conflict.
Ideally, the response representation would include enough information
for the user or user agent to fix the problem; however, that might
not be possible and is not required.</p>
<p>Conflicts are most likely to occur in response to a PUT request. For
example, if versioning were being used and the representation being
PUT included changes to a resource which conflict with those made by
an earlier (third-party) request, the server might use the 409
response to indicate that it can't complete the request. In this
case, the response representation would likely contain a list of the
differences between the two versions.</p>
</blockquote>
<p>Either of those would be suitable, but I think I'd go for 409. 404 is used for <em>URI not found</em> but 409 indicates the current state of the resource doesn't allow the operation requested. In your case, the request can't be satisfied because something is amiss which doesn't allow it.</p> |
10,271,373 | Node.js - How to add timestamp to logs using Winston library? | <p>I want to add timestamp to logs.</p>
<p>What is the best way to achieve this?</p>
<p>Thanks.</p> | 10,341,078 | 9 | 1 | null | 2012-04-22 19:33:58.567 UTC | 11 | 2022-09-14 08:00:58.44 UTC | 2022-09-14 08:00:58.44 UTC | null | 5,918,539 | null | 14,540 | null | 1 | 120 | node.js|logging|winston | 86,887 | <p>I was dealing with the same issue myself. There are two ways I was able to do this.</p>
<p>When you include Winston, it usually defaults to adding a Console transport. In order to get timestamps to work in this default case, I needed to either:</p>
<ol>
<li>Remove the console transport and add again with the timestamp option.</li>
<li>Create your own Logger object with the timestamp option set to true.</li>
</ol>
<p>The first:</p>
<pre><code>var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp':true});
</code></pre>
<p>The second, and cleaner option:</p>
<pre><code>var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({'timestamp':true})
]
});
</code></pre>
<p>Some of the other options for Console transport can be found <a href="https://github.com/winstonjs/winston#console-transport" rel="noreferrer" title="here">here</a>:</p>
<ul>
<li>level: Level of messages that this transport should log (default 'debug'). </li>
<li>silent: Boolean flag indicating whether to suppress output (default false). </li>
<li>colorize: Boolean flag indicating if we should colorize output (default false). </li>
<li>timestamp: Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.</li>
</ul> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.