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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,639,769 | Print a pdf without visually opening it | <p>The thing I want to build is that by clicking a button I want to trigger the print of a PDF file, but without opening it.</p>
<pre><code>+-----------+
| Print PDF |
+-----------+
^ Click *---------> printPdf(pdfUrl)
</code></pre>
<p>The way how I first tried it is to use an iframe:</p>
<pre><code>var $iframe = null;
// This is supposed to fix the onload bug on IE, but it's not fired
window.printIframeOnLoad = function() {
if (!$iframe.attr("src")) { return; }
var PDF = $iframe.get(0);
PDF.focus();
try {
// This doesn't work on IE anyways
PDF.contentWindow.print();
// I think on IE we can do something like this:
// PDF.document.execCommand("print", false, null);
} catch (e) {
// If we can't print it, we just open it in the current window
window.location = url;
}
};
function printPdf(url) {
if ($iframe) {
$iframe.remove();
}
$iframe = $('<iframe>', {
class: "hide",
id: "idPdf",
// Supposed to be a fix for IE
onload: "window.printIframeOnLoad()",
src: url
});
$("body").prepend($iframe);
}
</code></pre>
<p>This works on Safari (desktop & iOS) and Chrome (can we generalize it maybe to webkit?).</p>
<p>On Firefox, <code>PDF.contentWindow.print()</code> ends with a <code>permission denied</code> error (even the pdf is loaded from the same domain).</p>
<p>On IE (11), the <code>onload</code> handler is just not working.</p>
<hr>
<p>Now, my question is: is there another better way to print the pdf without visually opening it to the user?</p>
<p>The cross browser thing is critical here. We should support as many browsers as possible.</p>
<p>What's the best way to achieve this? Is my start a good one? How to complete it?</p>
<p><sub>We are now in 2016 and I feel like this is still a pain to implement across the browsers.</sub></p> | 38,814,826 | 3 | 8 | null | 2016-07-28 14:46:58.683 UTC | 15 | 2021-03-08 16:21:22.93 UTC | null | null | null | null | 1,420,197 | null | 1 | 34 | javascript|jquery|pdf|printing | 69,336 | <p><strong>UPDATE</strong>: This <a href="http://nvision.co/blog/tips-and-tricks/auto-print-pdf-file-open/" rel="noreferrer">link</a> details an elegant solution that involves editing the page properties for the first page and adding an action on Page Open. Works across all browsers (as browsers will execute the JavaScript placed in the actions section). Requires Adobe Acrobat Pro.</p>
<hr>
<p>It seems 2016 brings no new advancements to the printing problem. Had a similar issue and to make the printing cross-browser I solved it using <a href="https://mozilla.github.io/pdf.js/" rel="noreferrer">PDF.JS</a> but had to make a one-liner addition to the source (they ask you to build upon it in anyways).</p>
<p>The idea:</p>
<ul>
<li>Download the pre-built stable release from <a href="https://mozilla.github.io/pdf.js/getting_started/#download" rel="noreferrer">https://mozilla.github.io/pdf.js/getting_started/#download</a> and add the "build" and "web" folders to the project.</li>
<li>The <code>viewer.html</code> file is what renders out PDFs with a rich interface and contains print functionality. I added a link in that file to my own JavaScript that simply triggers window.print() after a delay.</li>
</ul>
<p>The link added to viewer:</p>
<pre><code> <script src="viewer.js"></script>
<!-- this autoPrint.js was added below viewer.js -->
<script src="autoPrint.js"></script>
</head>
</code></pre>
<p>The <code>autoPrint.js</code> javascript:</p>
<pre><code>(function () {
function printWhenReady() {
if (PDFViewerApplication.initialized) {
window.print();
}
else {
window.setTimeout(printWhenReady, 3000);
}
};
printWhenReady();
})();
</code></pre>
<ul>
<li><p>I could then put calls to <code>viewer.html?file=</code> in the src of an iframe and hide it. Had to use visibility, not display styles because of Firefox:</p>
<pre><code><iframe src="web/viewer.html?file=abcde.pdf" style="visibility: hidden">
</code></pre></li>
</ul>
<p>The result: the print dialog showed after a short delay with the PDF being hidden from the user.</p>
<p>Tested in Chrome, IE, Firefox.</p> |
46,102,428 | Get orders shipping items details in WooCommerce 3 | <p>How can I get the <strong>order shipping method id</strong>.?</p>
<p>For example 'flate_rate'.</p>
<p>Since WooCommerce 3 it is now complicated as everything has changed.</p>
<p>I have tried it with <strong><code>$order->get_data()</code></strong> in a foreach loop but the data is protected.</p> | 46,106,700 | 1 | 0 | null | 2017-09-07 17:51:54.127 UTC | 11 | 2021-03-26 14:18:50.797 UTC | 2021-03-26 14:18:50.797 UTC | null | 3,730,754 | null | 5,358,573 | null | 1 | 13 | php|woocommerce|orders|shipping|shipping-method | 36,339 | <p>If you want to get the Order Items Shipping data, you need first to get them in a foreach loop (for <strong><code>'shipping'</code></strong> item type) and to use <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item_Shipping.html" rel="noreferrer">WC_Order_Item_Shipping</a> methods to access data</p>
<pre><code>$order_id = 528; // For example
// An instance of
$order = wc_get_order($order_id);
// Iterating through order shipping items
foreach( $order->get_items( 'shipping' ) as $item_id => $item ){
$order_item_name = $item->get_name();
$order_item_type = $item->get_type();
$shipping_method_title = $item->get_method_title();
$shipping_method_id = $item->get_method_id(); // The method ID
$shipping_method_instance_id = $item->get_instance_id(); // The instance ID
$shipping_method_total = $item->get_total();
$shipping_method_total_tax = $item->get_total_tax();
$shipping_method_taxes = $item->get_taxes();
}
</code></pre>
<p>You can also get an array of this (unprotected and accessible) data using the <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Data.html#methods" rel="noreferrer"><strong><code>WC_Data</code></strong></a> method <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Data.html#methods" rel="noreferrer"><strong><code>get_data()</code></strong></a> inside this foreach loop:</p>
<pre><code>$order_id = 528; // For example
// An instance of
$order = wc_get_order($order_id);
// Iterating through order shipping items
foreach( $order->get_items( 'shipping' ) as $item_id => $item ){
// Get the data in an unprotected array
$item_data = $item->get_data();
$shipping_data_id = $item_data['id'];
$shipping_data_order_id = $item_data['order_id'];
$shipping_data_name = $item_data['name'];
$shipping_data_method_title = $item_data['method_title'];
$shipping_data_method_id = $item_data['method_id'];
$shipping_data_instance_id = $item_data['instance_id'];
$shipping_data_total = $item_data['total'];
$shipping_data_total_tax = $item_data['total_tax'];
$shipping_data_taxes = $item_data['taxes'];
}
</code></pre>
<p>To finish you can use the following <a href="https://docs.woocommerce.com/wc-apidocs/class-WC_Abstract_Order.html#methods" rel="noreferrer"><strong><code>WC_Abstract_Order</code></strong></a> methods related to "Shipping data", like in this examples:</p>
<pre><code>// Get an instance of the WC_Order object
$order = wc_get_order(522);
// Return an array of shipping costs within this order.
$order->get_shipping_methods(); // same thing than $order->get_items('shipping')
// Conditional function based on the Order shipping method
if( $order->has_shipping_method('flat_rate') ) {
// Output formatted shipping method title.
echo '<p>Shipping method name: '. $order->get_shipping_method()) .'</p>';
</code></pre> |
2,633,272 | Using Hadoop, are my reducers guaranteed to get all the records with the same key? | <p>I'm running a Hadoop job using Hive actually that is supposed to <code>uniq</code> lines in many text files. In the reduce step, it chooses the most recently timestamped record for each key.</p>
<p><strong>Does Hadoop guarantee that every record with the same key, output by the map step, will go to a single reducer, even if many reducers are running across a cluster?</strong></p>
<p>I worry that the mapper output might be split after the shuffle happens in the middle of a set of records with the same key.</p> | 2,633,746 | 3 | 0 | null | 2010-04-13 21:16:17.853 UTC | 9 | 2015-07-19 17:27:16.89 UTC | 2015-05-05 21:33:39.337 UTC | null | 2,932,774 | null | 211,136 | null | 1 | 14 | hadoop|mapreduce|hive|uniq | 6,234 | <p>All values for a key are sent to the same reducer. See this <a href="http://developer.yahoo.com/hadoop/tutorial/module4.html" rel="noreferrer">Yahoo! tutorial</a> for more discussion.</p>
<p>This behavior is determined by the partitioner, and might not be true if you use a partitioner other than the default.</p> |
3,165,449 | Confusing behaviour of const_get in Ruby? | <p>According to the documentation <code>mod.const_get(sym)</code> "Returns the value of the named constant in mod."</p>
<p>I also know that <code>const_get</code> by default may look up the inheritance chain of the receiver. So the following works:</p>
<pre><code>class A; HELLO = :hello; end
class B < A; end
B.const_get(:HELLO) #=> :hello
</code></pre>
<p>I also know that classes in Ruby subclass <code>Object</code>, so that you can use <code>const_get</code> to look up 'global' constants even though the receiver is a normal class:</p>
<pre><code>class C; end
C.const_get(:Array) #=> Array
</code></pre>
<p>However, and this is where i'm confused -- modules do not subclass <code>Object</code>. So why can I still look up 'global' constants from a module using <code>const_get</code>? Why does the following work?</p>
<pre><code>module M; end
M.const_get(:Array) #=> Array
</code></pre>
<p>If the documentation is correct - <code>const_get</code> simply looks up the constant defined under the receiver or its superclasses. But in the code immediately above, <code>Object</code> is not a superclass of <code>M</code>, so why is it possible to look up <code>Array</code> ?</p>
<p>Thanks</p> | 3,167,977 | 3 | 1 | null | 2010-07-02 12:01:57.443 UTC | 9 | 2014-11-10 19:45:50.1 UTC | 2010-07-02 12:19:42.27 UTC | null | 66,725 | null | 66,725 | null | 1 | 20 | ruby | 9,981 | <p>You are correct to be confused... The doc didn't state that Ruby makes a special case for lookup of constants in <code>Modules</code> and has been modified <a href="http://ruby-doc.org/core-1.9.3/Module.html#const_get-method" rel="noreferrer">to state this explicitly</a>. If the constant has not been found in the normal hierarchy, Ruby restarts the lookup from <code>Object</code>, as can be <a href="http://github.com/ruby/ruby/blob/v1_9_2_preview3/variable.c#L1594" rel="noreferrer">found in the source</a>.</p>
<p>Constant lookup by itself can be bit confusing. Take the following example:</p>
<pre><code>module M
Foo = :bar
module N
# Accessing Foo here is fine:
p Foo # => bar
end
end
module M::N
# Accessing Foo here isn't
p Foo # => uninitialized constant M::N::Foo
end
p M::N.const_get :Foo # => uninitialized constant M::N::Foo
</code></pre>
<p>In both places, though, accessing <code>Object</code> level constants like <code>Array</code> is fine (thank god!). What's going on is that Ruby maintains a list of "opened Module definitions". If a constant has an explicit scope, say <code>LookHereOnly::Foo</code>, then <strong>only</strong> <code>LookHereOnly</code> and its included modules will be searched. If no scope is specified (like <code>Foo</code> in the example above), Ruby will look through the opened module definitions to find the constant <code>Foo</code>: <code>M::N</code>, then <code>M</code> and finally <code>Object</code>. The topmost opened module definition is always <code>Object</code>.</p>
<p>So <code>M::N.const_get :Foo</code> is equivalent to accessing <code>Foo</code> when the opened classes are only <code>M::N</code> and <code>Object</code>, like in the last part of my example.</p>
<p>I hope I got this right, coz I'm still confused by constant lookups myself :-)</p> |
1,102,485 | Tables and charts using PDFsharp | <p>I just started with a project that requires me to write to PDF file. After some googling I decided on using PDFsharp which looks simple enough, however I have a few questions regarding drawing tables and charts.</p>
<p>Is PDFsharp a good choice for writing PDF files that contain tables and charts? If no, can you recommend a better alternative? If yes, where could I find some good literature on the subject? A tutorial would be nice (doesn't have to be a sample project, just something I can use to familiarise myself with the library and its classes).</p>
<p>Can anyone tell me what MigraDoc is all about? I just took a glimpse and it seems perfect for what I need, however I would like some more information about it.</p> | 1,327,257 | 2 | 1 | null | 2009-07-09 08:10:43.113 UTC | 2 | 2016-09-29 21:09:27.883 UTC | 2016-09-29 21:09:27.883 UTC | null | 4,370,109 | null | 55,377 | null | 1 | 13 | c#|charts|pdf-generation|pdfsharp | 41,892 | <p>PDFsharp is a "low level" PDF generator, while MigraDoc is a "high level" document generator that uses PDFsharp to create PDF files, but can also create e. g. RTF.</p>
<p>Visit the PDFsharp/MigraDoc Foundation Website for further information:<br />
<a href="http://www.pdfsharp.net/" rel="noreferrer">http://www.pdfsharp.net/</a></p> |
1,275,633 | Elegantly replace iPhone keyboard with UIPickerView | <p>I have a table view that has embedded UITextFields for entering some data. It also has two other fields that popup a UIPickerView and a UIDatePicker - as demonstrated in the DateCell example from Apple.</p>
<p>Mostly it works but I can't figure out how to cleanly transition from the text field keyboard to the other pickers - one slides out, one slides in - it looks weird and the scroll position on the table view sometimes gets screwed up - with everything scrolled off the top.</p>
<p>What I'd like to do is replace the text field keyboard without it animating away and without it growing the table view back to full size.</p>
<p>Any clues?</p> | 1,990,319 | 2 | 0 | null | 2009-08-14 01:41:18.47 UTC | 20 | 2012-11-05 05:25:09.537 UTC | null | null | null | null | 77,002 | null | 1 | 14 | iphone|uitextfield|uipickerview|uidatepicker | 26,932 | <p>First, here is a <a href="http://screencast.com/t/NDViMjYxZGEt" rel="noreferrer">screencapture showing how this looks</a>.</p>
<p>Implement UITextFieldDelegate and display a "popup" containing a UIPickerView.</p>
<pre><code>- (void)textFieldDidEndEditing:(UITextField *)textField {
UIPickerView *picker = [[UIPickerView alloc]
initWithFrame:CGRectMake(0, 244, 320, 270)];
picker.delegate = self;
picker.dataSource = self;
[self.view addSubview:picker];
[picker release];
}
</code></pre>
<p>When the keyboard disappears, a picker view is then visible.</p>
<p>If you want to take this a bit further, you can animate the UIPickerView "slide in" like the keyboard. </p>
<pre><code>- (void)viewDidLoad {
//picker exists in the view, but is outside visible range
picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 480, 320, 270)];
picker.delegate = self;
picker.dataSource = self;
[self.view addSubview:picker];
[picker release];
}
//animate the picker into view
- (void)textFieldDidEndEditing:(UITextField *)textField {
[UIView beginAnimations:@"picker" context:nil];
[UIView setAnimationDuration:0.5];
picker.transform = CGAffineTransformMakeTranslation(0,-236);
[UIView commitAnimations];
}
//animate the picker out of view
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[UIView beginAnimations:@"picker" context:nil];
[UIView setAnimationDuration:0.5];
picker.transform = CGAffineTransformMakeTranslation(0,236);
[UIView commitAnimations];
}
//just hide the keyboard in this example
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
</code></pre> |
618,618 | How to create an ArrayList from an Array in PowerShell? | <p>I've got a list of files in an array. I want to enumerate those files, and remove specific files from it. Obviously I can't remove items from an array, so I want to use an <code>ArrayList</code>.
But the following doesn't work for me:</p>
<pre><code>$temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($temp)
</code></pre>
<p>Where <code>$temp</code> is an Array.</p>
<p>How can I achieve that?</p> | 618,675 | 2 | 0 | null | 2009-03-06 12:04:09.107 UTC | 10 | 2016-01-05 01:23:47.193 UTC | 2015-02-05 00:40:06.417 UTC | null | 3,829,407 | Mark Ingram | 986 | null | 1 | 24 | powershell | 107,555 | <p>I can't get that constructor to work either. This however seems to work:</p>
<pre><code># $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
</code></pre>
<p>You can also pass an integer in the constructor to set an initial capacity.</p>
<p>What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?</p>
<p><strong>Edit:</strong></p>
<p>It seems that you can use the array constructor like this:</p>
<pre><code>$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
</code></pre>
<p>Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on. </p> |
3,135,112 | android nested listview | <p>is it possible/advisable to have a nested listview?</p>
<p>i.e. a listView that's contained within a row of another listview?</p>
<p>an example would be where my main list is displaying blog posts, and then in each row, you'd have another list view for the comments for each post (that would be collapsible) </p> | 5,983,743 | 5 | 0 | null | 2010-06-28 18:31:17.103 UTC | 10 | 2017-02-22 12:48:31.653 UTC | null | null | null | null | 372,405 | null | 1 | 28 | android|listview|nested | 32,429 | <p>I had the same problem today, so this is what I did to solve it:</p>
<p>I have a ListView, with a CustomAdapter, and on the getView of the customAdapter, I have something like this:</p>
<pre><code>LinearLayout list = (LinearLayout) myView.findViewById(R.id.list_musics);
list.removeAllViews();
for (Music music : albums.get(position).musics) {
View line = li.inflate(R.layout.inside_row, null);
/* nested list's stuff */
list.addView(line);
}
</code></pre>
<p>So, resuming, It's not possible to nest to ListViews, but you can create a list inside a row using LinearLayout and populating it with code.</p> |
2,700,039 | How to collect all files in a Folder and its Subfolders that match a string | <p>In C# how can I search through a Folder and its Subfolders to find files that match a string value. My string value could be "ABC123" and a matching file might be ABC123_200522.tif. Can an Array collect these?</p> | 2,700,090 | 6 | 0 | null | 2010-04-23 15:59:37.733 UTC | 3 | 2022-01-26 17:33:53.517 UTC | 2022-01-26 17:33:53.517 UTC | null | 107,625 | null | 316,824 | null | 1 | 21 | c#|.net | 42,520 | <pre><code>void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, sMatch))
{
lstFilesFound.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
</code></pre>
<p>where <code>sMatch</code> is the criteria of what to search for.</p> |
2,624,159 | Centering a percent-based div | <p>Recently, a client asked that his site be percent-based rather than pixel-based. The percent was to be set to 80%. As you guys know, it is very easy to center the container if it is pixel-based but how do you center a percent-based main container?</p>
<pre><code>#container
{
width:80%;
margin:0px auto;
}
</code></pre>
<p>That does not center the container :(</p> | 2,624,193 | 6 | 6 | null | 2010-04-12 17:53:12.523 UTC | 10 | 2016-02-24 21:27:48.28 UTC | 2010-04-12 17:54:33.917 UTC | null | 43,089 | null | 139,459 | null | 1 | 38 | css|html | 42,394 | <p>The margin property supports percentage values:</p>
<pre><code>margin-left: 10%;
margin-right: 10%;
</code></pre> |
2,809,366 | Changing java platform on which netbeans runs | <p>I am using Netbeans 6.7. I had first installed Java 1.5 before installing Netbeans. When i installed Netbeans it took Java 1.5 as the default version. Then i installed Java 1.6 on my machine. I need to change the default JDK of my netbeans to 1.6 not only to a specific project but to the whole Netbeans application.</p> | 2,809,447 | 7 | 0 | null | 2010-05-11 09:14:29.943 UTC | 27 | 2022-06-11 23:12:50.31 UTC | 2014-10-15 10:26:46.377 UTC | null | 1,528,262 | null | 322,897 | null | 1 | 114 | java|netbeans | 160,102 | <p>You can change the JDK for Netbeans by modifying the config file:</p>
<ol>
<li>Open <code>netbeans.conf</code> file available under <code>etc</code> folder inside the NetBeans installation. </li>
<li>Modify the <code>netbeans_jdkhome</code> variable to point to new JDK path, and then </li>
<li>Restart your Netbeans.</li>
</ol> |
2,693,021 | How to count JavaScript array objects? | <p>When I have a JavaScript object like this:</p>
<pre><code>var member = {
"mother": {
"name" : "Mary",
"age" : "48"
},
"father": {
"name" : "Bill",
"age" : "50"
},
"brother": {
"name" : "Alex",
"age" : "28"
}
}
</code></pre>
<p><strong>How to count objects in this object?!</strong><br />
I mean how to get a counting result 3, because there're only 3 objects inside: mother, father, brother?!</p>
<p><strong>If it's not an array, so how to convert it into JSON array?</strong></p> | 2,693,037 | 8 | 2 | null | 2010-04-22 17:24:35.303 UTC | 10 | 2020-04-13 05:48:57.893 UTC | 2020-04-13 05:48:57.893 UTC | null | 1,446,177 | null | 309,031 | null | 1 | 18 | javascript|oop|object | 103,485 | <p>That's not an array, is an object literal, you should iterate over the own properties of the object and count them, e.g.:</p>
<pre><code>function objectLength(obj) {
var result = 0;
for(var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// or Object.prototype.hasOwnProperty.call(obj, prop)
result++;
}
}
return result;
}
objectLength(member); // for your example, 3
</code></pre>
<p>The <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer"><code>hasOwnProperty</code></a> method should be used to avoid iterating over inherited properties, e.g.</p>
<pre><code>var obj = {};
typeof obj.toString; // "function"
obj.hasOwnProperty('toString'); // false, since it's inherited
</code></pre> |
2,749,441 | Fastest way possible to read contents of a file | <p>Ok, I'm looking for the fastest possible way to read all of the contents of a file via php with a filepath on the server, also these files can be huge. So it's very important that it does a READ ONLY to it as fast as possible.</p>
<p>Is reading it line by line faster than reading the entire contents? Though, I remember reading up on this some, that reading the entire contents can produce errors for huge files. Is this true?</p> | 2,749,458 | 9 | 3 | null | 2010-05-01 09:36:00.533 UTC | 13 | 2015-07-07 13:21:44.723 UTC | 2014-01-22 09:25:38.257 UTC | null | 321,731 | null | 304,853 | null | 1 | 31 | php|file-io | 57,541 | <p>If you want to load the full-content of a file to a PHP variable, the easiest <em>(and, probably fastest)</em> way would be <a href="http://fr.php.net/file_get_contents" rel="noreferrer"><strong><code>file_get_contents</code></strong></a>.</p>
<p>But, if you are working with big files, loading the whole file into memory might not be such a good idea : you'll probably end up with a <a href="http://fr.php.net/manual/en/ini.core.php#ini.memory-limit" rel="noreferrer"><strong><code>memory_limit</code></strong></a> error, as PHP will not allow your script to use more than <em>(usually)</em> a couple mega-bytes of memory.</p>
<p><br>
So, even if it's not the fastest solution, reading the file line by line <em>(<a href="http://fr2.php.net/manual/en/function.fopen.php" rel="noreferrer"><strong><code>fopen</code></strong></a>+<a href="http://fr2.php.net/fgets" rel="noreferrer"><strong><code>fgets</code></strong></a>+<a href="http://fr2.php.net/fclose" rel="noreferrer"><strong><code>fclose</code></strong></a>)</em>, and working with those lines on the fly, without loading the whole file into memory, might be necessary...</p> |
2,664,740 | Extract file basename without path and extension in bash | <p>Given file names like these:</p>
<pre><code>/the/path/foo.txt
bar.txt
</code></pre>
<p>I hope to get:</p>
<pre><code>foo
bar
</code></pre>
<p>Why this doesn't work?</p>
<pre><code>#!/bin/bash
fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname
</code></pre>
<p>What's the right way to do it?</p> | 2,664,746 | 9 | 6 | null | 2010-04-19 01:25:28.833 UTC | 147 | 2020-01-10 07:52:19.657 UTC | 2017-11-16 20:02:02.613 UTC | null | 3,474,146 | null | 67,405 | null | 1 | 418 | linux|bash|unix|filenames | 603,874 | <p>You don't have to call the external <code>basename</code> command. Instead, you could use the following commands:</p>
<pre><code>$ s=/the/path/foo.txt
$ echo "${s##*/}"
foo.txt
$ s=${s##*/}
$ echo "${s%.txt}"
foo
$ echo "${s%.*}"
foo
</code></pre>
<p>Note that this solution should work in all recent (<em>post 2004</em>) <em>POSIX</em> compliant shells, (e.g. <code>bash</code>, <code>dash</code>, <code>ksh</code>, etc.).</p>
<p>Source: <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">Shell Command Language 2.6.2 Parameter Expansion</a></p>
<p>More on bash String Manipulations: <a href="http://tldp.org/LDP/LG/issue18/bash.html" rel="noreferrer">http://tldp.org/LDP/LG/issue18/bash.html</a></p> |
2,661,764 | How to check if a socket is connected/disconnected in C#? | <p>How can you check if a network socket (System.Net.Sockets.Socket) is still connected if the other host doesn't send you a packet when it disconnects (e.g. because it disconnected ungracefully)?</p> | 2,661,876 | 11 | 0 | null | 2010-04-18 09:35:52.443 UTC | 49 | 2020-10-17 12:50:39.557 UTC | 2013-02-12 18:16:01.693 UTC | null | 319,611 | null | 319,611 | null | 1 | 77 | c#|sockets|connection | 165,027 | <p>As <a href="https://stackoverflow.com/users/138578/programming-hero">Paul Turner</a> answered <code>Socket.Connected</code> cannot be used in this situation. You need to poll connection every time to see if connection is still active. This is code I used:</p>
<pre><code>bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
</code></pre>
<p>It works like this:</p>
<ul>
<li><strong><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.poll.aspx" rel="noreferrer"><code>s.Poll</code></a></strong> returns true if
<ul>
<li>connection is closed, reset, terminated or pending (meaning no active connection)</li>
<li>connection is active and there is data available for reading</li>
</ul></li>
<li><strong><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.available.aspx" rel="noreferrer"><code>s.Available</code></a></strong> returns number of bytes available for reading</li>
<li>if both are true:
<ul>
<li>there is no data available to read so connection is not active</li>
</ul></li>
</ul> |
2,437,452 | How to get the list of files in a directory in a shell script? | <p>I'm trying to get the contents of a directory using shell script.</p>
<p>My script is:</p>
<pre><code>for entry in `ls $search_dir`; do
echo $entry
done
</code></pre>
<p>where <code>$search_dir</code> is a relative path. However, <code>$search_dir</code> contains many files with whitespaces in their names. In that case, this script does not run as expected.</p>
<p>I know I could use <code>for entry in *</code>, but that would only work for my current directory.</p>
<p>I know I can change to that directory, use <code>for entry in *</code> then change back, but my particular situation prevents me from doing that.</p>
<p>I have two relative paths <code>$search_dir</code> and <code>$work_dir</code>, and I have to work on both simultaneously, reading them creating/deleting files in them etc.</p>
<p>So what do I do now?</p>
<p>PS: I use bash.</p> | 2,437,466 | 11 | 0 | null | 2010-03-13 06:03:45.363 UTC | 56 | 2022-07-19 23:49:52.227 UTC | 2010-03-13 06:18:52.627 UTC | null | 275,737 | null | 2,119,053 | null | 1 | 246 | bash|shell|directory-listing | 833,434 | <pre><code>search_dir=/the/path/to/base/dir/
for entry in "$search_dir"/*
do
echo "$entry"
done
</code></pre> |
2,573,521 | How do I output an ISO 8601 formatted string in JavaScript? | <p>I have a <code>Date</code> object. <strong>How do I render the <code>title</code> portion of the following snippet?</strong></p>
<pre><code><abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
</code></pre>
<p><em>I have the "relative time in words" portion from another library.</em></p>
<p>I've tried the following:</p>
<pre><code>function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
</code></pre>
<p>But that gives me:</p>
<pre><code>"2010-4-2T3:19"
</code></pre> | 8,563,517 | 14 | 0 | null | 2010-04-04 04:04:13.217 UTC | 65 | 2022-03-01 11:29:41.437 UTC | 2016-03-25 19:26:03.247 UTC | null | 293,280 | null | 1,190 | null | 1 | 307 | javascript|datetime|iso8601 | 344,682 | <p>There is already a function called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString" rel="noreferrer"><code>toISOString()</code></a>:</p>
<pre><code>var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
</code></pre>
<p>If, somehow, you're on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString#Browser_compatibility" rel="noreferrer">a browser</a> that doesn't support it, I've got you covered:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if (!Date.prototype.toISOString) {
(function() {
function pad(number) {
var r = String(number);
if (r.length === 1) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
'Z';
};
}());
}
console.log(new Date().toISOString())</code></pre>
</div>
</div>
</p> |
2,709,253 | Converting a string to an integer on Android | <p>How do I convert a string into an integer?</p>
<p>I have a textbox I have the user enter a number into:</p>
<pre><code>EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
</code></pre>
<p>And the value is assigned to the string <code>hello</code>.</p>
<p>I want to convert it to a integer so I can get the number they typed; it will be used later on in code.</p>
<p>Is there a way to get the <code>EditText</code> to a integer? That would skip the middle man. If not, string to integer will be just fine.</p> | 2,709,269 | 14 | 1 | null | 2010-04-25 17:57:55.373 UTC | 36 | 2022-04-20 06:00:51.547 UTC | 2015-01-16 08:33:22.103 UTC | null | 972,684 | null | 321,763 | null | 1 | 204 | java|android|string|integer|android-edittext | 640,937 | <p>See the Integer class and the static <code>parseInt()</code> method:</p>
<p><a href="http://developer.android.com/reference/java/lang/Integer.html" rel="noreferrer">http://developer.android.com/reference/java/lang/Integer.html</a></p>
<pre><code>Integer.parseInt(et.getText().toString());
</code></pre>
<p>You will need to catch <code>NumberFormatException</code> though in case of problems whilst parsing, so:</p>
<pre><code>int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
</code></pre> |
2,785,755 | How to split but ignore separators in quoted strings, in python? | <p>I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks.</p>
<p><code>part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5</code></p>
<p>Result should be:</p>
<ul>
<li>part 1</li>
<li>"this is ; part 2;"</li>
<li>'this is ; part 3'</li>
<li>part 4</li>
<li>this "is ; part" 5</li>
</ul>
<p>I suppose this can be done with a regex but if not; I'm open to another approach.</p> | 2,787,064 | 17 | 6 | null | 2010-05-07 02:13:05.663 UTC | 24 | 2021-03-18 01:48:07.283 UTC | 2012-02-09 01:03:26.973 UTC | null | 121,445 | null | 121,445 | null | 1 | 73 | python|regex | 70,689 | <p>Most of the answers seem massively over complicated. You <strong>don't</strong> need back references. You <strong>don't</strong> need to depend on whether or not re.findall gives overlapping matches. Given that the input cannot be parsed with the csv module so a regular expression is pretty well the only way to go, all you need is to call re.split with a pattern that matches a field.</p>
<p>Note that it is much easier here to match a field than it is to match a separator:</p>
<pre><code>import re
data = """part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5"""
PATTERN = re.compile(r'''((?:[^;"']|"[^"]*"|'[^']*')+)''')
print PATTERN.split(data)[1::2]
</code></pre>
<p>and the output is:</p>
<pre><code>['part 1', '"this is ; part 2;"', "'this is ; part 3'", 'part 4', 'this "is ; part" 5']
</code></pre>
<p>As Jean-Luc Nacif Coelho correctly points out this won't handle empty groups correctly. Depending on the situation that may or may not matter. If it does matter it may be possible to handle it by, for example, replacing <code>';;'</code> with <code>';<marker>;'</code> where <code><marker></code> would have to be some string (without semicolons) that you know does not appear in the data before the split. Also you need to restore the data after:</p>
<pre><code>>>> marker = ";!$%^&;"
>>> [r.replace(marker[1:-1],'') for r in PATTERN.split("aaa;;aaa;'b;;b'".replace(';;', marker))[1::2]]
['aaa', '', 'aaa', "'b;;b'"]
</code></pre>
<p>However this is a kludge. Any better suggestions?</p> |
10,650,645 | Python: Calculate Voronoi Tesselation from Scipy's Delaunay Triangulation in 3D | <p>I have about 50,000 data points in 3D on which I have run scipy.spatial.Delaunay from the new scipy (I'm using 0.10) which gives me a very useful triangulation.</p>
<p>Based on: <a href="http://en.wikipedia.org/wiki/Delaunay_triangulation">http://en.wikipedia.org/wiki/Delaunay_triangulation</a> (section "Relationship with the Voronoi diagram")</p>
<p>...I was wondering if there is an easy way to get to the "dual graph" of this triangulation, which is the Voronoi Tesselation.</p>
<p>Any clues? My searching around on this seems to show no pre-built in scipy functions, which I find almost strange!</p>
<p>Thanks,
Edward</p> | 10,657,011 | 4 | 0 | null | 2012-05-18 10:08:15.647 UTC | 18 | 2017-08-09 08:59:12.163 UTC | null | null | null | null | 1,243,969 | null | 1 | 19 | python|3d|scipy|delaunay|voronoi | 19,752 | <p>The adjacency information can be found in the <code>neighbors</code> attribute of the Delaunay object. Unfortunately, the code does not expose the circumcenters to the user at the moment, so you'll have to recompute those yourself.</p>
<p>Also, the Voronoi edges that extend to infinity are not directly obtained in this way. It's still probably possible, but needs some more thinking.</p>
<pre><code>import numpy as np
from scipy.spatial import Delaunay
points = np.random.rand(30, 2)
tri = Delaunay(points)
p = tri.points[tri.vertices]
# Triangle vertices
A = p[:,0,:].T
B = p[:,1,:].T
C = p[:,2,:].T
# See http://en.wikipedia.org/wiki/Circumscribed_circle#Circumscribed_circles_of_triangles
# The following is just a direct transcription of the formula there
a = A - C
b = B - C
def dot2(u, v):
return u[0]*v[0] + u[1]*v[1]
def cross2(u, v, w):
"""u x (v x w)"""
return dot2(u, w)*v - dot2(u, v)*w
def ncross2(u, v):
"""|| u x v ||^2"""
return sq2(u)*sq2(v) - dot2(u, v)**2
def sq2(u):
return dot2(u, u)
cc = cross2(sq2(a) * b - sq2(b) * a, a, b) / (2*ncross2(a, b)) + C
# Grab the Voronoi edges
vc = cc[:,tri.neighbors]
vc[:,tri.neighbors == -1] = np.nan # edges at infinity, plotting those would need more work...
lines = []
lines.extend(zip(cc.T, vc[:,:,0].T))
lines.extend(zip(cc.T, vc[:,:,1].T))
lines.extend(zip(cc.T, vc[:,:,2].T))
# Plot it
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
lines = LineCollection(lines, edgecolor='k')
plt.hold(1)
plt.plot(points[:,0], points[:,1], '.')
plt.plot(cc[0], cc[1], '*')
plt.gca().add_collection(lines)
plt.axis('equal')
plt.xlim(-0.1, 1.1)
plt.ylim(-0.1, 1.1)
plt.show()
</code></pre> |
10,648,828 | see values of chart points when the mouse is on points | <p>I have a chart and I want the user to see the values when the pointer is on the points.
By using digEmAll's help in the page <a href="https://stackoverflow.com/questions/9647666/finding-the-value-of-the-points-in-a-chart">finding the value of the points in a chart</a> ,I could write the following code:</p>
<pre><code>Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
void chart1_MouseMove(object sender, MouseEventArgs e)
{
var pos = e.Location;
if (prevPosition.HasValue && pos == prevPosition.Value)
return;
tooltip.RemoveAll();
prevPosition = pos;
var results = chart1.HitTest(pos.X, pos.Y, false, ChartElementType.PlottingArea);
foreach (var result in results)
{
if (result.ChartElementType == ChartElementType.PlottingArea)
{
chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";
}
}
}
</code></pre>
<p>by the above code,the user can see the values when the pointer is <strong>near to</strong> a series.But now How can I let the user to see the values only when the pointer is <strong>on</strong> the points?
I replaced </p>
<pre><code>int k = result.PointIndex;
if (k >= 0)
{
chart1.Series[0].Points[k].ToolTip = "X=#VALX, Y=#VALY";
}
</code></pre>
<p>instead of </p>
<pre><code>chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";
</code></pre>
<p>to solve my problem.But It wasn't usefull.</p> | 10,649,892 | 3 | 0 | null | 2012-05-18 07:55:52.6 UTC | 9 | 2018-07-27 18:44:53.4 UTC | 2017-05-23 12:26:37.537 UTC | null | -1 | null | 973,562 | null | 1 | 21 | c#|winforms|mschart | 56,852 | <p>You should modify the code in this way:</p>
<pre><code>Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
void chart1_MouseMove(object sender, MouseEventArgs e)
{
var pos = e.Location;
if (prevPosition.HasValue && pos == prevPosition.Value)
return;
tooltip.RemoveAll();
prevPosition = pos;
var results = chart1.HitTest(pos.X, pos.Y, false,
ChartElementType.DataPoint);
foreach (var result in results)
{
if (result.ChartElementType == ChartElementType.DataPoint)
{
var prop = result.Object as DataPoint;
if (prop != null)
{
var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);
// check if the cursor is really close to the point (2 pixels around the point)
if (Math.Abs(pos.X - pointXPixel) < 2 &&
Math.Abs(pos.Y - pointYPixel) < 2)
{
tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
pos.X, pos.Y - 15);
}
}
}
}
}
</code></pre>
<p>The idea is to check if the mouse is very close to the point e.g. <code>2</code> pixels around it (because is really unlikely to be <strong>exactly</strong> on the point) and show the tooltip in that case.</p>
<p><a href="http://pastebin.com/PzhHtfMu" rel="noreferrer">Here's a complete working example.</a></p> |
10,807,765 | node.js sequelize: multiple 'where' query conditions | <p>How do i query a table with multiple conditions?
Here are the examples both working:</p>
<pre><code>Post.findAll({ where: ['deletedAt IS NULL'] }).success()
</code></pre>
<p>and</p>
<pre><code>Post.findAll({ where: {topicId: req.params.id} }).success()
</code></pre>
<p>Then, if i need conditions combined, i feel like i need to do something like</p>
<pre><code>Post.findAll({ where: [{topicId: req.params.id}, 'deletedAt IS NULL'] }).success()
</code></pre>
<p>, but it doesn't work.<br>
What is the syntax the sequelize waits for?</p>
<p>node debug says:</p>
<blockquote>
<p>DEBUG: TypeError: Object # has no method 'replace'</p>
</blockquote>
<p>if it matters...</p> | 29,952,146 | 5 | 0 | null | 2012-05-29 22:42:56.43 UTC | 7 | 2021-07-09 08:21:42.8 UTC | null | null | null | null | 1,389,265 | null | 1 | 24 | node.js|sequelize.js | 64,597 | <p>Please note that as of this posting and the 2015 version of sequelize, the above answers are out of date. I am posting the solution that I got working in hopes of saving someone some time.</p>
<pre><code>filters["State"] = {$and: [filters["State"], {$not: this.filterSBM()}] };
</code></pre>
<p>Note the $ and array inside the JSON object and lack of ? token replacement.</p>
<p>Or put in a more general way, since that might help someone wrap their head around it:</p>
<pre><code>{ $and: [{"Key1": "Value1"}, {"Key2": "Value2"}] }
</code></pre> |
10,839,151 | Convert mysql DATETIME column to epoch seconds | <p>I have a column mysql <code>datetime</code> that is in DATETIME format. </p>
<p>Is there a way to <code>SELECT</code> this column in epoch seconds? If not, what would be the best way of converting the datetime format to epoch seconds? What type of field would be the best to capture this?</p> | 10,839,181 | 2 | 0 | null | 2012-05-31 18:27:19.767 UTC | null | 2018-11-27 01:53:00.343 UTC | 2018-11-27 01:53:00.343 UTC | null | 6,862,601 | null | 651,174 | null | 1 | 27 | mysql|sql|datetime|epoch | 48,210 | <p>Use MySQL's <a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp"><code>UNIX_TIMESTAMP</code></a> function</p> |
10,806,790 | Generating Symmetric Matrices in Numpy | <p>I am trying to generate symmetric matrices in numpy. Specifically, these matrices are to have random places entries, and in each entry the contents can be random. Along the main diagonal we are not concerned with what entries are in there, so I have randomized those as well.</p>
<p>The approach I have taken is to first generate a nxn all zero matrix and simply loop over the indices of the matrices.
How can I do this more efficiently using numpy?</p>
<pre><code>import numpy as np
import random
def empty(x, y):
return x*0
b = np.fromfunction(empty, (n, n), dtype = int)
for i in range(0, n):
for j in range(0, n):
if i == j:
b[i][j] = random.randrange(-2000, 2000)
else:
switch = random.random()
random.seed()
if switch > random.random():
a = random.randrange(-2000, 2000)
b[i][j] = a
b[j][i] = a
else:
b[i][j] = 0
b[j][i] = 0
</code></pre> | 10,806,947 | 7 | 0 | null | 2012-05-29 21:12:11.593 UTC | 12 | 2022-04-22 10:56:07.667 UTC | 2022-04-22 10:56:07.667 UTC | null | 365,102 | null | 1,424,707 | null | 1 | 39 | python|random|matrix|numpy|adjacency-matrix | 52,296 | <p>You could just do something like:</p>
<pre><code>import numpy as np
N = 100
b = np.random.random_integers(-2000,2000,size=(N,N))
b_symm = (b + b.T)/2
</code></pre>
<p>Where you can choose from whatever distribution you want in the <code>np.random</code> or equivalent scipy module.</p>
<p><strong>Update:</strong> If you are trying to build graph-like structures, definitely check out the networkx package: </p>
<p><a href="http://networkx.lanl.gov" rel="noreferrer">http://networkx.lanl.gov</a></p>
<p>which has a number of built-in routines to build graphs:</p>
<p><a href="http://networkx.lanl.gov/reference/generators.html" rel="noreferrer">http://networkx.lanl.gov/reference/generators.html</a></p>
<p>Also if you want to add some number of randomly placed zeros, you can always generate a random set of indices and replace the values with zero.</p> |
10,559,275 | How is -march different from -mtune? | <p>I tried to scrub the GCC man page for this, but still don't get it, really.</p>
<p>What's the difference between <code>-march</code> and <code>-mtune</code>?</p>
<p>When does one use just <code>-march</code>, vs. both? Is it ever possible to just <code>-mtune</code>?</p> | 10,559,360 | 2 | 0 | null | 2012-05-11 22:12:18.843 UTC | 22 | 2022-07-17 20:36:00.397 UTC | 2022-07-17 20:36:00.397 UTC | null | 1,161,484 | null | 695,787 | null | 1 | 97 | gcc|optimization|compiler-construction|flags | 35,991 | <p>If you use <code>-march</code> then GCC will be free to generate instructions that work on the specified CPU, but (typically) not on earlier CPUs in the architecture family.</p>
<p>If you just use <code>-mtune</code>, then the compiler will generate code that works on any of them, but will favour instruction sequences that run fastest on the specific CPU you indicated. e.g. setting loop-unrolling heuristics appropriately for that CPU.</p>
<hr />
<p><code>-march=foo</code> implies <code>-mtune=foo</code> unless you also specify a different <code>-mtune</code>. This is one reason why using <code>-march</code> is better than just enabling options like <code>-mavx</code> without doing anything about tuning.</p>
<p>Caveat: <code>-march=native</code> on a CPU that GCC doesn't specifically recognize will still enable new instruction sets that GCC can detect, but will leave <code>-mtune=generic</code>. Use a new enough GCC that knows about your CPU if you want it to make good code.</p> |
10,394,857 | How to use @Transactional with Spring Data? | <p>I just started working on a Spring-data, Hibernate, MySQL, JPA project. I switched to spring-data so that I wouldn't have to worry about creating queries by hand.</p>
<p>I noticed that the use of <code>@Transactional</code> isn't required when you're using spring-data since I also tried my queries without the annotation.</p>
<p>Is there a specific reason why I should/shouldn't be using the <code>@Transactional</code> annotation?</p>
<p>Works:</p>
<pre><code>@Transactional
public List listStudentsBySchool(long id) {
return repository.findByClasses_School_Id(id);
}
</code></pre>
<p>Also works:</p>
<pre><code>public List listStudentsBySchool(long id) {
return repository.findByClasses_School_Id(id);
}
</code></pre> | 10,466,591 | 5 | 0 | null | 2012-05-01 07:33:58.38 UTC | 56 | 2022-06-07 22:58:15.163 UTC | 2022-06-07 22:58:15.163 UTC | null | 1,839,439 | null | 1,244,652 | null | 1 | 102 | java|spring|jpa|spring-data|spring-data-jpa | 112,879 | <p>What is your question actually about? The usage of the <code>@Repository</code> annotation or <code>@Transactional</code>.</p>
<p><code>@Repository</code> is not needed at all as the interface you declare will be backed by a proxy the Spring Data infrastructure creates and activates exception translation for anyway. So using this annotation on a Spring Data repository interface does not have any effect at all.</p>
<p><code>@Transactional</code> - for the JPA module we have this annotation on the implementation class backing the proxy (<a href="https://github.com/SpringSource/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java"><code>SimpleJpaRepository</code></a>). This is for two reasons: first, persisting and deleting objects requires a transaction in JPA. Thus we need to make sure a transaction is running, which we do by having the method annotated with <code>@Transactional</code>. </p>
<p>Reading methods like <code>findAll()</code> and <code>findOne(…)</code> are using <code>@Transactional(readOnly = true)</code> which is not strictly necessary but triggers a few optimizations in the transaction infrastructure (setting the <code>FlushMode</code> to <code>MANUAL</code> to let persistence providers potentially skip dirty checks when closing the <code>EntityManager</code>). Beyond that the flag is set on the JDBC Connection as well which causes further optimizations on that level. </p>
<p>Depending on what database you use it can omit table locks or even reject write operations you might trigger accidentally. Thus we recommend using <code>@Transactional(readOnly = true)</code> for query methods as well which you can easily achieve adding that annotation to you repository interface. Make sure you add a plain <code>@Transactional</code> to the manipulating methods you might have declared or re-decorated in that interface.</p> |
5,739,830 | Simple Log to File example for django 1.3+ | <p>The release notes say:</p>
<blockquote>
<p>Django 1.3 adds framework-level
support for Python’s logging module.</p>
</blockquote>
<p>That's nice. I'd like to take advantage of that. Unfortunately <a href="http://docs.djangoproject.com/en/1.11/topics/logging/" rel="noreferrer">the documentation</a> doesn't hand it all to me on a silver platter in the form of complete working example code which demonstrates how simple and valuable this is.</p>
<p>How do I set up this funky new feature such that I can pepper my code with</p>
<pre><code>logging.debug('really awesome stuff dude: %s' % somevar)
</code></pre>
<p>and see the file "/tmp/application.log" fill up with</p>
<pre><code>18:31:59 Apr 21 2011 awesome stuff dude: foobar
18:32:00 Apr 21 2011 awesome stuff dude: foobar
18:32:01 Apr 21 2011 awesome stuff dude: foobar
</code></pre>
<p>What's the difference between the default Python logging and this 'framework-level support'?</p> | 7,045,981 | 2 | 0 | null | 2011-04-21 05:12:07.733 UTC | 60 | 2017-12-03 10:25:12.997 UTC | 2017-12-03 10:25:12.997 UTC | null | 1,705,829 | null | 75,033 | null | 1 | 102 | django|django-settings | 53,336 | <p>I truly love this so much here is your working example! Seriously this is awesome!</p>
<p>Start by putting this in your <code>settings.py</code></p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': SITE_ROOT + "/logfile",
'maxBytes': 50000,
'backupCount': 2,
'formatter': 'standard',
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers':['console'],
'propagate': True,
'level':'WARN',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'MYAPP': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
}
}
</code></pre>
<p>Now what does all of this mean?</p>
<ol>
<li>Formaters I like it to come out as the same style as ./manage.py runserver</li>
<li>Handlers - I want two logs - a debug text file, and an info console. This allows me to really dig in (if needed) and look at a text file to see what happens under the hood.</li>
<li>Loggers - Here is where we nail down what we want to log. In general django gets WARN and above - the exception (hence propagate) is the backends where I love to see the SQL calls since they can get crazy.. Last is my app were I have two handlers and push everything to it.</li>
</ol>
<p>Now how do I enable MYAPP to use it...</p>
<p>Per the <a href="https://docs.djangoproject.com/en/dev/topics/logging/#using-logging" rel="noreferrer">documentation</a> put this at the top of your files (views.py)..</p>
<pre><code>import logging
log = logging.getLogger(__name__)
</code></pre>
<p>Then to get something out do this.</p>
<pre><code>log.debug("Hey there it works!!")
log.info("Hey there it works!!")
log.warn("Hey there it works!!")
log.error("Hey there it works!!")
</code></pre>
<p>Log levels are explained <a href="https://docs.djangoproject.com/en/dev/topics/logging/#making-logging-calls" rel="noreferrer">here</a> and for pure python <a href="http://docs.python.org/library/logging.html" rel="noreferrer">here</a>.</p> |
6,181,464 | Do c++11 lambdas capture variables they don't use? | <p>When I use <code>[=]</code> to indicate that I would like all local variables to be captured by value in a lambda, will that result in <em>all</em> local variables in the function being copied, or just all local variables <em>that are used by the lambda</em>?</p>
<p>So, for example, if i I have:</p>
<pre><code>vector<int> my_huge_vector(100000);
int my_measly_int;
some_function([=](int i){ return my_measly_int + i; });
</code></pre>
<p>Will my_huge_vector be copied, even though I don't use it in the lambda?</p> | 6,181,507 | 2 | 0 | null | 2011-05-30 23:02:44.607 UTC | 20 | 2014-02-19 23:16:24.557 UTC | 2014-02-19 23:16:24.557 UTC | null | 24,874 | null | 141,719 | null | 1 | 136 | c++|lambda|c++11 | 25,904 | <p>Each variable expressly named in the capture list is captured. The default capture will only capture variables that are both (a) not expressly named in the capture list and (b) <em>used</em> in the body of the lambda expression. If a variable is not expressly named and you don't use the variable in the lambda expression, then the variable is not captured. In your example, <code>my_huge_vector</code> is not captured.</p>
<p>Per C++11 §5.1.2[expr.prim.lambda]/11:</p>
<blockquote>
<p>If a <em>lambda-expression</em> has an associated <em>capture-default</em> and its <em>compound-statement</em> <em>odr-uses</em> <code>this</code> or a variable with automatic storage duration and the <em>odr-used</em> entity is not explicitly captured, then the <em>odr-used</em> entity is said to be implicitly captured.</p>
</blockquote>
<p>Your lambda expression has an associated capture default: by default, you capture variables by value using the <code>[=]</code>.</p>
<p>If and only if a variable is used (in the One Definition Rule sense of the term "used") is a variable implicitly captured. Since you don't use <code>my_huge_vector</code> at all in the body (the "compound statement") of the lambda expression, it is not implicitly captured.</p>
<p>To continue with §5.1.2/14</p>
<blockquote>
<p>An entity is captured by copy if</p>
<ul>
<li>it is implicitly captured and the <em>capture-default</em> is <code>=</code> or if</li>
<li>it is explicitly captured with a capture that does not include an <code>&</code>.</li>
</ul>
</blockquote>
<p>Since your <code>my_huge_vector</code> is not implicitly captured and it is not explicitly captured, it is not captured at all, by copy or by reference.</p> |
30,802,595 | How Do I Create Sub-Sub-Domain on Cloudflare DNS? | <p>I've let cloudflare manage the DNS of my <code>example.com</code></p>
<p>I have created <code>id.example.com</code> for country's specific customer. I've done it by created cname <code>id</code> with alias <code>example.com</code></p>
<p>I need to create customer portal: <code>my.id.example.com</code>. How?</p> | 31,362,889 | 4 | 0 | null | 2015-06-12 12:01:44.527 UTC | 9 | 2022-07-05 15:14:04.24 UTC | 2022-07-05 15:14:04.24 UTC | null | 1,145,388 | user4804299 | null | null | 1 | 36 | cloudflare | 38,127 | <ul>
<li>In Cloudflare, open the DNS records for <code>domain.example</code></li>
<li>Create a A record for <code>example.id</code> and enter the IP where <code>my.id.domain.example</code> will be hosted, and add record <img src="https://i.stack.imgur.com/5ekPk.jpg" alt="" /></li>
<li>Setup the site <code>my.id.domain.example</code> at the IP you specified</li>
</ul>
<p>If <code>domain.example</code> is on Cloudflare and the Cloudflare nameservers have propagated, the sub-sub domain propagation should be more or less instant</p>
<p>As correctly noted by <a href="https://stackoverflow.com/users/1695680/thorsummoner">ThorSummoner</a> and <a href="https://stackoverflow.com/users/2965260/user296526">user296526</a>, this will work on the Cloudflare free plan if you aren't using SSL.</p>
<p>If you want to have a sub sub domain <strong>with</strong> SSL on Cloudflare, you need to a dedicated Cloudflare dedicated SSL certificate which is available as a paid plan. To quote from the <a href="https://support.cloudflare.com/hc/en-us/articles/228009108" rel="nofollow noreferrer">Cloudflare site</a>:</p>
<blockquote>
<p>Cloudflare Dedicated Certificate with Custom Hostname: $10 per domain
per month</p>
<p>Includes all benefits mentioned above for Dedicated Certificates
Protects your domain, subdomains (<code>*.example.com</code>), as well as up to 50
additional hostnames Can extend protection beyond first-level
subdomains (<code>*.www.example.com</code>, not just <code>*.example.com</code>) Dedicated SSL
certificates typically provision within a few minutes but can take up
to 24 hours.</p>
</blockquote>
<p><a href="https://support.cloudflare.com/hc/en-us/articles/228009108-Dedicated-SSL-Certificates" rel="nofollow noreferrer">Full details here</a></p> |
34,001,751 | How to increase/reduce the fontsize of x and y tick labels | <p>I seem to have a problem in figuring out how to increase or decrease the <code>fontsize</code> of both the x and y tick labels while using <code>matplotlib</code>.</p>
<p>I am aware that there is the <code>set_xticklabels(labels, fontdict=None, minor=False, **kwargs)</code> function, but I failed to understand how to control the <code>fontsize</code> in it. </p>
<p>I expected something somehow explicit, like </p>
<pre><code>title_string=('My Title')
plt.suptitle(title_string, y=1.0, fontsize=17)
</code></pre>
<p>but I haven't found anything like that so far. What am I missing?</p> | 34,004,236 | 4 | 0 | null | 2015-11-30 15:10:41.727 UTC | 21 | 2022-08-02 21:31:10.033 UTC | 2022-08-02 21:31:10.033 UTC | null | 7,758,804 | null | 5,110,870 | null | 1 | 46 | python|text|matplotlib|axis-labels|keyword-argument | 141,453 | <p>You can set the fontsize directly in the call to <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html#matplotlib.axes.Axes.set_xticklabels" rel="noreferrer"><code>set_xticklabels</code></a> and <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_yticklabels.html#matplotlib.axes.Axes.set_yticklabels" rel="noreferrer"><code>set_yticklabels</code></a> (as noted in previous answers). This will only affect one <code>Axes</code> at a time.</p>
<pre><code>ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
</code></pre>
<p>Note this method should only be used if you are fixing the positions of the ticks first (e.g. using <code>ax.set_xticks</code>). If you are not changing the tick positions from the default ones, you can just change the font size of the tick labels without changing the text using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.tick_params.html" rel="noreferrer"><code>ax.tick_params</code></a></p>
<pre><code>ax.tick_params(axis='x', labelsize=8)
ax.tick_params(axis='y', labelsize=8)
</code></pre>
<p>or</p>
<pre><code>ax.tick_params(axis='both', labelsize=8)
</code></pre>
<p>You can also set the <code>ticklabel</code> font size globally (i.e. for all figures/subplots in a script) using <a href="http://matplotlib.org/users/customizing.html" rel="noreferrer"><code>rcParams</code></a>:</p>
<pre><code>import matplotlib.pyplot as plt
plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)
</code></pre>
<p>Or, equivalently:</p>
<pre><code>plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8
</code></pre>
<p>Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two <code>rcParams</code> in your <code>matplotlibrc</code> file:</p>
<pre><code>xtick.labelsize : 8 # fontsize of the x tick labels
ytick.labelsize : 8 # fontsize of the y tick labels
</code></pre> |
53,238,230 | How to update globally installed npm packages | <p>Command: <code>npm outdated -g</code></p>
<p>Output: </p>
<pre><code>Package Current Wanted Latest Location
@angular/cli 1.3.1 1.7.4 7.0.5
create-react-app 1.5.2 1.5.2 2.1.1
eslint 5.6.0 5.9.0 5.9.0
expo-cli 2.2.0 2.3.8 2.3.8
gulp-cli 1.4.0 1.4.0 2.0.1
how-to-npm 2.5.0 2.5.1 2.5.1
mocha 3.5.0 3.5.3 5.2.0
nodemon 1.18.3 1.18.6 1.18.6
now 11.4.6 11.5.2 12.0.1
serve 10.0.1 10.0.2 10.0.2
typescript 2.4.2 2.9.2 3.1.6
yarn 1.9.4 1.12.3 1.12.3
</code></pre>
<p>How do I update these outdated packages in npm?</p> | 53,238,253 | 3 | 0 | null | 2018-11-10 10:54:35.94 UTC | 9 | 2021-06-01 13:21:08.14 UTC | 2020-03-24 14:20:25.153 UTC | null | 124,946 | null | 5,048,891 | null | 1 | 105 | npm|npm-install|npm-start | 38,910 | <p>If you want to update all global packages</p>
<pre><code>npm update -g
</code></pre>
<p>If you want to update specific global package</p>
<pre><code>npm update -g <package_name>
</code></pre> |
43,333,542 | What is video timescale, timebase, or timestamp in ffmpeg? | <p>There does not seem to be any explanation online as to what these are. People talk about them a lot. I just want to know what they are and why they are significant. Using -video_track_timescale, how would I determine a number for it? Is it random? Should it be 0?</p> | 43,337,235 | 1 | 0 | null | 2017-04-10 21:58:34.083 UTC | 42 | 2020-02-28 20:08:46.31 UTC | 2017-04-11 05:28:29.733 UTC | null | 1,109,017 | null | 7,835,200 | null | 1 | 72 | video|ffmpeg|codec | 38,371 | <p>Modern containers govern the time component of presentation of video (and audio) frames using timestamps, rather than framerate. So, instead of recording a video as 25 fps, and thus implying that each frame should be drawn 0.04 seconds apart, they store a timestamp for each frame e.g.</p>
<pre><code> Frame pts_time
0 0.00
1 0.04
2 0.08
3 0.12
...
</code></pre>
<p>For the sake of precise resolution of these time values, a timebase is used i.e. a unit of time which represents one tick of a clock, as it were. So, a timebase of <code>1/75</code> represents 1/75th of a second. The <strong>P</strong>resentation <strong>T</strong>ime<strong>S</strong>tamps are then denominated in terms of this timebase. Timescale is simply the reciprocal of the timebase. FFmpeg shows the timescale as the <code>tbn</code> value in the readout of a stream.</p>
<pre><code>Timebase = 1/75; Timescale = 75
Frame pts pts_time
0 0 0 x 1/75 = 0.00
1 3 3 x 1/75 = 0.04
2 6 6 x 1/75 = 0.08
3 9 9 x 1/75 = 0.12
...
</code></pre>
<p>This method of regulating time allows variable frame-rate video.</p> |
8,632,705 | How to close a GUI when I push a JButton? | <p>Does anyone know how to make a jbutton close a gui? I think it is like <code>System.CLOSE(0);</code> but that didnt work. it also could be <code>exitActionPerformed(evt);</code>, but that didn't work either. just the line of code will work.</p>
<p>EDIT: never mind guys. the answer was <code>System.exit(0);</code>. thanks for the help though!</p> | 8,632,722 | 7 | 0 | null | 2011-12-26 03:14:49.407 UTC | 2 | 2020-12-15 11:06:38.947 UTC | 2020-12-15 11:06:38.947 UTC | null | 1,783,163 | null | 1,102,109 | null | 1 | 18 | java|swing|user-interface|jbutton | 191,068 | <p>Add your button:</p>
<pre><code>JButton close = new JButton("Close");
</code></pre>
<p>Add an ActionListener:</p>
<pre><code>close.addActionListner(new CloseListener());
</code></pre>
<p>Add a class for the Listener implementing the ActionListener interface and override its main function:</p>
<pre><code>private class CloseListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
System.exit(0);
}
}
</code></pre>
<p>This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.</p> |
8,820,553 | How can I do a SQL UPDATE in batches, like an Update Top? | <p>Is it possible to add a TOP or some sort of paging to a SQL Update statement?</p>
<p>I have an <code>UPDATE</code> query, that comes down to something like this:</p>
<pre><code>UPDATE XXX SET XXX.YYY = #TempTable.ZZZ
FROM XXX
INNER JOIN (SELECT SomeFields ... ) #TempTable ON XXX.SomeId=#TempTable.SomeId
WHERE SomeConditions
</code></pre>
<p>This update will affect millions of records, and I need to do it in batches. Like 100.000 at the time (the ordering doesn't matter)</p>
<p>What is the easiest way to do this?</p> | 8,820,594 | 5 | 0 | null | 2012-01-11 14:01:33.647 UTC | 4 | 2020-09-03 14:20:39.517 UTC | null | null | null | null | 579,690 | null | 1 | 18 | sql|sql-server-2008|tsql | 54,740 | <p>Yes, I believe you can use TOP in an update statement, like so:</p>
<pre><code>UPDATE TOP (10000) XXX SET XXX.YYY = #TempTable.ZZZ
FROM XXX
INNER JOIN (SELECT SomeFields ... ) #TempTable ON XXX.SomeId=#TempTable.SomeId
WHERE SomeConditions
</code></pre> |
8,742,249 | How to set prefixed CSS3 transitions using JavaScript? | <p>How can I set CSS using javascript (I don't have access to the CSS file)?</p>
<pre><code>#fade div {
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
-ms-transition: opacity 1s;
transition: opacity 1s;
opacity: 0;
position: absolute;
height: 500px;
width: 960px;
}
</code></pre>
<p>For example:</p>
<pre><code>document.getElementById('fade').HOW-TO-TYPE-webkit-transition = 'opacity 1s';
</code></pre> | 8,742,302 | 6 | 0 | null | 2012-01-05 12:08:16.163 UTC | 10 | 2022-05-09 20:12:43.463 UTC | 2022-05-09 20:12:43.463 UTC | null | 1,264,804 | null | 673,108 | null | 1 | 36 | javascript|css | 81,817 | <p>You should look here: <a href="http://www.javascriptkit.com/javatutors/setcss3properties.shtml" rel="noreferrer">http://www.javascriptkit.com/javatutors/setcss3properties.shtml</a></p>
<p>As you can see setting CSS Properties with "-" just results in the next character to be capital:</p>
<pre><code>document.getElementById('fade').style.WebkitTransition = 'opacity 1s';
document.getElementById('fade').style.MozTransition = 'opacity 1s';
</code></pre> |
8,647,024 | How to apply a disc shaped mask to a NumPy array? | <p>I have an array like this:</p>
<pre><code>>>> np.ones((8,8))
array([[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
</code></pre>
<p>I'm creating a disc shaped mask with radius 3 thus:</p>
<pre><code>y,x = np.ogrid[-3: 3+1, -3: 3+1]
mask = x**2+y**2 <= 3**2
</code></pre>
<p>This gives:</p>
<pre><code>>> mask
array([[False, False, False, True, False, False, False],
[False, True, True, True, True, True, False],
[False, True, True, True, True, True, False],
[ True, True, True, True, True, True, True],
[False, True, True, True, True, True, False],
[False, True, True, True, True, True, False],
[False, False, False, True, False, False, False]], dtype=bool)
</code></pre>
<p>Now, I want to be able to apply this mask to my array, using any element as a center point.
So, for example, with center point at (1,1), I want to get an array like:</p>
<pre><code>>>> new_arr
array([[ True, True, True, True, 1., 1., 1., 1.],
[ True, True, True, True, True, 1., 1., 1.],
[ True, True, True, True, 1., 1., 1., 1.],
[ True, True, True, True, 1., 1., 1., 1.],
[ 1., True, 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
</code></pre>
<p>Is there an easy way to apply this mask?</p>
<p><strong>Edit: I shouldn't have mixed booleans and floats - it was misleading.</strong></p>
<pre><code>>>> new_arr
array([[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 255., 255., 255., 255., 255., 1., 1., 1.],
[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 255., 255., 255., 255., 1., 1., 1., 1.],
[ 1., 255., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1.]])
</code></pre>
<p>This is more the result I require. </p>
<pre><code>array[mask] = 255
</code></pre>
<p>will mask the array using center point (0+radius,0+radius). </p>
<p>However, I'd like to be able to place any size mask at any point (y,x) and have it automatically trimmed to fit.</p> | 8,650,741 | 7 | 0 | null | 2011-12-27 16:44:38.333 UTC | 21 | 2021-05-03 21:53:28.09 UTC | 2019-07-17 14:15:58.957 UTC | null | 7,851,470 | null | 816,555 | null | 1 | 38 | python|arrays|numpy|mask | 37,426 | <p>I would do it like this, where (a, b) is the center of your mask:</p>
<pre><code>import numpy as np
a, b = 1, 1
n = 7
r = 3
y,x = np.ogrid[-a:n-a, -b:n-b]
mask = x*x + y*y <= r*r
array = np.ones((n, n))
array[mask] = 255
</code></pre> |
8,575,281 | Regex plus vs star difference? | <p>What is the difference between:</p>
<pre><code>(.+?)
</code></pre>
<p>and</p>
<pre><code>(.*?)
</code></pre>
<p>when I use it in my php <code>preg_match</code> regex?</p> | 8,575,344 | 9 | 0 | null | 2011-12-20 12:14:02.957 UTC | 28 | 2020-09-16 02:21:03.367 UTC | null | null | null | null | 533,617 | null | 1 | 122 | php|regex | 117,808 | <p>They are called quantifiers.</p>
<p><code>*</code> 0 or more of the preceding expression</p>
<p><code>+</code> 1 or more of the preceding expression</p>
<p>Per default a quantifier is greedy, that means it matches as many characters as possible.</p>
<p>The <code>?</code> after a quantifier changes the behaviour to make this quantifier "ungreedy", means it will match as little as possible.</p>
<p><strong>Example greedy/ungreedy</strong></p>
<p>For example on the string "<em>abab</em>"</p>
<p><code>a.*b</code> will match "abab" (preg_match_all will return one match, the "abab")</p>
<p>while <code>a.*?b</code> will match only the starting "ab" (preg_match_all will return two matches, "ab")</p>
<p>You can test your regexes online e.g. on Regexr, <a href="http://regexr.com?2vhbb" rel="noreferrer">see the greedy example here</a></p> |
8,388,537 | twig: IF with multiple conditions | <p>It seem I have problem with a twig if statement.</p>
<pre><code>{%if fields | length > 0 || trans_fields | length > 0 -%}
</code></pre>
<p>The error is:</p>
<pre><code>Unexpected token "punctuation" of value "|" ("name" expected) in
</code></pre>
<p>I can't understand why this doesn't work, it's like if twig was lost with all the pipes.</p>
<p>I've tried this :</p>
<pre><code>{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}
</code></pre>
<p>but the if also fail.</p>
<p>Then tried this:</p>
<pre><code>{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}
</code></pre>
<p>And it still doesn't work, same error every time ...</p>
<p>So... that lead me to a really simple question: does Twig support multiple conditions IF ?</p> | 8,388,696 | 2 | 0 | null | 2011-12-05 16:33:41.52 UTC | 26 | 2021-11-24 21:21:49.79 UTC | 2017-10-05 00:43:12.95 UTC | null | 42,223 | null | 613,365 | null | 1 | 140 | php|twig|conditional-operator | 260,009 | <p>If I recall correctly Twig doesn't support <code>||</code> and <code>&&</code> operators, but requires <code>or</code> and <code>and</code> to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.</p>
<pre><code>{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
</code></pre>
<p>Expressions</p>
<pre><code>Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
</code></pre>
<p>For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:</p>
<pre><code>{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
</code></pre> |
55,262,996 | Does awaiting a non-Promise have any detectable effect? | <p>One can <code>await</code> a non-Promise and <a href="https://github.com/Microsoft/TypeScript/issues/8310" rel="noreferrer">that's good so</a>.</p>
<p>All these expressions are valid and cause no error:</p>
<pre><code>await 5
await 'A'
await {}
await null
await undefined
</code></pre>
<p>Is there any <strong>detectable effect</strong> of awaiting a non-Promise? Is there any difference in behavior one should be aware of to avoid a potential error? Any performance differences?</p>
<p>Are the following two lines completely same or do they <em>theoretically</em> differ?:</p>
<pre><code>var x = 5
var x = await 5
</code></pre>
<p>How? Any example to demonstrate the difference? </p>
<p>PS: According <a href="https://github.com/Microsoft/TypeScript/issues/8310#issuecomment-214892918" rel="noreferrer">TypeScript authors</a>, there is a difference:</p>
<blockquote>
<p><code>var x = await 5;</code> is not the same as <code>var x = 5;</code>; <code>var x = await 5;</code> will assign x 5 in the next tern, where as <code>var x = 5;</code> will evaluate immediately.</p>
</blockquote> | 55,263,084 | 2 | 0 | null | 2019-03-20 14:19:47.373 UTC | 16 | 2019-03-21 08:49:28.157 UTC | 2019-03-20 14:25:18.74 UTC | null | 2,190,498 | null | 2,190,498 | null | 1 | 83 | javascript|ecmascript-2017 | 18,832 | <p><code>await</code> is not a no-op. If the awaited thing is not a promise, it is wrapped in a promise, that promise is awaited. Therefore <code>await</code> changes the execution order (but you should not rely on it nevertheless):</p>
<pre><code>console.log(1);
(async function() {
var x = await 5; // remove await to see 1,3,2
console.log(3);
})();
console.log(2);
</code></pre>
<p>Additionally <code>await</code> does not only work on <code>instanceof Promise</code>s but on every object with a <code>.then</code> method:</p>
<pre><code>await { then(cb) { /* nowhere */ } };
console.log("will never happen");
</code></pre>
<blockquote>
<p>Is there any detectable effect of awaiting a non-Promise? </p>
</blockquote>
<p>Sure, <code>.then</code> gets called if it exists on the awaited thing.</p>
<blockquote>
<p>Is there any difference in behavior one should be aware of to avoid a potential error?</p>
</blockquote>
<p>Don't name a method "then" if you don't want it to be a Promise.</p>
<blockquote>
<p>Any performance differences?</p>
</blockquote>
<p>Sure, if you await things you will always defer the continuation to a microtask. But as always: You won't probably notice it (as a human observing the outcome).</p> |
1,016,749 | How can I concatinate a subquery result field into the parent query? | <p>DB: Sql Server 2008.</p>
<p>I have a really (fake) groovy query like this:-</p>
<pre><code>SELECT CarId, NumberPlate
(SELECT Owner
FROM Owners b
WHERE b.CarId = a.CarId) AS Owners
FROM Cars a
ORDER BY NumberPlate
</code></pre>
<p>And this is what I'm trying to get...</p>
<pre><code>=> 1 ABC123 John, Jill, Jane
=> 2 XYZ123 Fred
=> 3 SOHOT Jon Skeet, ScottGu
</code></pre>
<p>So, i tried using </p>
<p>AS <code>[Text()] ... FOR XML PATH('')</code> but that was inlcuding weird encoded characters (eg. carriage return). ... so i'm not 100% happy with that.</p>
<p>I also tried to see if there's a COALESCE solution, but all my attempts failed.</p>
<p>So - any suggestions?</p> | 1,016,775 | 3 | 0 | null | 2009-06-19 07:27:41.63 UTC | 1 | 2022-09-23 20:24:16.727 UTC | 2010-05-12 04:28:48.883 UTC | null | 2,391 | null | 30,674 | null | 1 | 4 | sql-server|sql-server-2008|subquery|concatenation | 53,993 | <p>Try the solution to this question:</p>
<p><a href="https://stackoverflow.com/questions/6899/is-there-a-way-to-create-a-mssql-function-to-join-multiple-rows-from-a-subquery">How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?</a> </p>
<p>:)</p> |
397,257 | Force TextBlock to wrap in WPF ListBox | <p>I have a WPF listbox which displays messages. It contains an avatar on the left side and the username and message stacked vertically to the right of the avatar. The layout is fine until the message text should word wrap, but instead I get a horizontal scroll bar on the listbox. </p>
<p>I've Googled and found solutions to similar issues, but none of them worked.</p>
<pre><code><ListBox HorizontalContentAlignment="Stretch" ItemsSource="{Binding Path=FriendsTimeline}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border BorderBrush="DarkBlue" BorderThickness="3" CornerRadius="2" Margin="3" >
<Image Height="32" Width="32" Source="{Binding Path=User.ProfileImageUrl}"/>
</Border>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=User.UserName}"/>
<TextBlock Text="{Binding Path=Text}" TextWrapping="WrapWithOverflow"/> <!-- This is the textblock I'm having issues with. -->
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre> | 397,287 | 3 | 0 | null | 2008-12-29 07:01:49.45 UTC | 12 | 2017-01-11 15:21:10.327 UTC | 2015-09-23 05:46:05.57 UTC | null | 490,018 | EHaskins | 100 | null | 1 | 96 | wpf|listbox|word-wrap|textblock | 54,683 | <p>Contents of the <code>TextBlock</code> can be wrapped using property <code>TextWrapping</code>.
Instead of <code>StackPanel</code>, use <code>DockPanel</code>/<code>Grid</code>.
One more thing - set <code>ScrollViewer.HorizontalScrollBarVisibility</code> property to <code>Disabled</code> value for the <code>ListBox</code>.</p>
<p>Updated <code>Hidden</code> to <code>Disabled</code> based on comment from Matt. Thanks Matt.</p> |
22,143,881 | How to exclude a file extension from IntelliJ IDEA search? | <p>Is there a way to exclude particular file extension from the results in IntelliJ IDEA's "<em>Find in Path</em>" dialog (invoked by <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>F</kbd>)? I want to exclude all <code>.css</code> files.</p> | 37,781,104 | 7 | 0 | null | 2014-03-03 10:13:28.457 UTC | 35 | 2022-03-04 13:20:39.523 UTC | 2017-12-18 10:50:44.063 UTC | null | 479,156 | null | 3,355,252 | null | 1 | 208 | intellij-idea | 59,801 | <p>In intellij 16 there is a section "File name Filter" to exclude an extension use <code>!*.java</code>. You can give more detailed patterns as well for example I use the pattern below to only return .java files except those with a name starting or ending with test.
Pattern: <code>!*test.java,*.java,!Test*.java</code></p>
<p><a href="https://i.stack.imgur.com/HuTg1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HuTg1.png" alt="enter image description here"></a></p>
<p>In recent versions of Intellij the GUI has been updated a bit but the same still applies see the "File mask" on the top right hand corner see image below:</p>
<p><a href="https://i.stack.imgur.com/RNPY1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RNPY1.png" alt="enter image description here"></a></p> |
6,479,999 | Django admin ManyToMany inline "has no ForeignKey to" error | <p>I'm setting up the Django admin to the following models:</p>
<pre class="lang-py prettyprint-override"><code>class Tag(models.Model):
name = models.CharField(max_length=100)
class Quote(models.Model):
author = models.CharField(max_length=100)
quote = models.CharField(max_length=1000)
tags = models.ManyToManyField(Tag)
</code></pre>
<p>With the following code:</p>
<pre><code>class TagInline(admin.TabularInline):
model = Tag
class QuoteAdmin(admin.ModelAdmin):
list_display = ('author', 'quote')
inlines = (TagInline,)
class TagAdmin(admin.ModelAdmin):
pass
admin.site.register(Quote, QuoteAdmin)
admin.site.register(Tag, TagAdmin)
</code></pre>
<p>When trying to view the admin page to add a <code>Quote</code>, the page shows an error saying <code><class 'quotes.models.Tag'> has no ForeignKey to <class 'quotes.models.Quote'></code>. This didn't happen before I added an inline. What's the problem? How do I correctly add a <code>Tag</code> as an inline?</p>
<p><em>(I spent a good 20 minutes searching for an answer; I found similar questions but none of their answers worked for me.)</em></p> | 6,480,089 | 1 | 1 | null | 2011-06-25 19:23:23.987 UTC | 17 | 2022-03-25 22:30:06.337 UTC | 2022-03-25 22:30:06.337 UTC | null | 8,172,439 | null | 92,272 | null | 1 | 118 | django|django-models | 54,071 | <p><a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-models" rel="noreferrer">Admin documentation</a> has a section dedicated to inlining with many-to-many relationships. You should use <code>Quote.tags.through</code> as a model for <code>TagInline</code>, instead of <code>Tag</code> itself.</p> |
14,556,121 | Java: Print Array: IndexOutOfBoundsException: Index: 2, Size: 2 | <p>I am trying to print the contents of an array using System.out.print() but I encounter this error: </p>
<pre><code>Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Polymorphism.actionPerformed(Polymorphism.java:196)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
</code></pre>
<p>The line the error is referring to is line 3:</p>
<pre><code> else if (e.getSource() == printArray) {
for (int q=0; q<j; q++){
System.out.print("Type: " + itemList.get(j).selectedType + " ");
System.out.print("Width: " + itemList.get(j).selectedWidth + " ");
System.out.print("Length: " + itemList.get(j).selectedLength + " ");
}
}
</code></pre>
<p>I don't have any debugger experience so I appreciate any help, thanks.</p> | 14,556,170 | 7 | 2 | null | 2013-01-28 05:46:07.817 UTC | null | 2018-10-23 14:14:21.387 UTC | null | null | null | null | 2,017,027 | null | 1 | 0 | java|arrays|indexoutofboundsexception | 40,845 | <p>Change to <strong>.get(j)</strong> as Renjith says and you can also make sure to never end up in the situation you're in</p>
<p>instead of</p>
<pre><code>for (int q=0; q<j; q++) {
</code></pre>
<p>do</p>
<pre><code>for (int q=0; q<itemList.size(); q++) {
</code></pre>
<p>This way you cannot .get from anything larger than the size of the list/array</p> |
20,667,473 | Hive Explode / Lateral View multiple arrays | <p>I have a hive table with the following schema: </p>
<pre><code>COOKIE | PRODUCT_ID | CAT_ID | QTY
1234123 [1,2,3] [r,t,null] [2,1,null]
</code></pre>
<p>How can I normalize the arrays so I get the following result </p>
<pre><code>COOKIE | PRODUCT_ID | CAT_ID | QTY
1234123 [1] [r] [2]
1234123 [2] [t] [1]
1234123 [3] null null
</code></pre>
<p>I have tried the following: </p>
<pre><code>select concat_ws('|',visid_high,visid_low) as cookie
,pid
,catid
,qty
from table
lateral view explode(productid) ptable as pid
lateral view explode(catalogId) ptable2 as catid
lateral view explode(qty) ptable3 as qty
</code></pre>
<p>however the result comes out as a Cartesian product.</p> | 20,668,900 | 5 | 0 | null | 2013-12-18 20:11:45.77 UTC | 15 | 2020-06-25 13:00:30.723 UTC | 2018-05-22 12:00:09.203 UTC | null | 119,775 | null | 2,726,995 | null | 1 | 22 | hive|explode|hiveql | 53,224 | <p>You can use the <code>numeric_range</code> and <code>array_index</code> UDFs from Brickhouse ( <a href="http://github.com/klout/brickhouse" rel="noreferrer">http://github.com/klout/brickhouse</a> ) to solve this problem. There is an informative blog posting describing in detail over at <a href="http://brickhouseconfessions.wordpress.com/2013/03/07/exploding-multiple-arrays-at-the-same-time-with-numeric_range/" rel="noreferrer">http://brickhouseconfessions.wordpress.com/2013/03/07/exploding-multiple-arrays-at-the-same-time-with-numeric_range/</a> </p>
<p>Using those UDFs, the query would be something like </p>
<pre><code>select cookie,
array_index( product_id_arr, n ) as product_id,
array_index( catalog_id_arr, n ) as catalog_id,
array_index( qty_id_arr, n ) as qty
from table
lateral view numeric_range( size( product_id_arr )) n1 as n;
</code></pre> |
56,298,481 | how to fix [Object: null prototype] { title: 'product' } | <p>I've started learning <code>node.js</code> with <code>express</code> framework , when I post a form like this :</p>
<pre class="lang-js prettyprint-override"><code>router.get('/add-product',(req,res,next)=>{
res.send('<form action="/product" method="POST" ><input type="text" name="title" /><button type="submit">Submit</button></form>');
});
router.post('/product',(req,res,next)=>{
console.log(req.body);
res.redirect('/');
});
</code></pre>
<p>When I do <code>console.log(req.body)</code> it displays:</p>
<pre><code>[Object: null prototype] { title: 'product' }
</code></pre>
<p>instead of just <code>{ title: 'product' }</code></p>
<p>I'm wondering if this actually is an error with express or just a propriety that its been added to express recently , because I downloaded another project created last year and it used the same approach, when I did <code>console.log(req.body)</code>, it displayed the same output.</p> | 56,298,574 | 11 | 2 | null | 2019-05-24 19:19:21.083 UTC | 14 | 2021-12-07 09:55:35.873 UTC | 2021-02-21 14:17:02.8 UTC | null | 7,619,808 | null | 9,727,465 | null | 1 | 64 | angular|javascript|node.js|express | 80,334 | <p>That’s actually good design. Objects by default inherit the <code>Object.prototype</code> that contains some helper functions (<code>.toString()</code>, <code>.valueOf()</code>). Now if you use <code>req.body</code> and you pass no parameters to the HTTP request, then you'd expect <code>req.body</code> to be empty. If it were just "a regular object", it wouldn't be entirely empty:</p>
<pre><code>console.info(({ "toString": 5 })['toString']); // 5
console.info(({})['toString']); // [Function: toString]
</code></pre>
<p>There is a way to create "empty objects", meaning objects without any properties / prototype, and that is <code>Object.create(null)</code>. You are seeing one of those objects in the console.</p>
<p>So no, this is not a bug that needs to be fixed, that’s just great use of JS' features.</p> |
36,026,424 | what is equivalent of a windows service on azure? | <p>what is the way to have an always running process on azure? on windows it is windows service, but do i have to get a virtual machine just to have a single running process? I have looked at various compute options but none of them seems to match what a windows service does. Is there a different way to achieve what a windows service does on azure? </p> | 36,026,596 | 3 | 1 | null | 2016-03-16 03:45:52.603 UTC | 4 | 2019-12-25 07:16:51.767 UTC | null | null | null | null | 404,160 | null | 1 | 46 | azure | 36,544 | <p>You should look at continuously-running web jobs.
See <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/#CreateContinuous" rel="noreferrer">Running Background tasks with WebJobs on Microsoft Azure</a>.</p>
<p>Other choices are PaaS cloud services worker roles and Azure Service Fabric reliable services - but these are likely overkill if you just want a basic service.</p> |
36,198,278 | Why does the JVM require warmup? | <p>I understand that in the Java virtual machine (JVM), warmup is potentially required as Java loads classes using a lazy loading process and as such you want to ensure that the objects are initialized before you start the main transactions. I am a C++ developer and have not had to deal with similar requirements.</p>
<p>However, the parts I am not able to understand are the following:</p>
<ol>
<li>Which parts of the code should you warm up? </li>
<li>Even if I warm up some parts of the code, how long does it remain warm (assuming this term only means how long your class objects remain in-memory)? </li>
<li>How does it help if I have objects which need to be created each time I receive an event?</li>
</ol>
<p>Consider for an example an application that is expected to receive messages over a socket and the transactions could be New Order, Modify Order and Cancel Order or transaction confirmed.</p>
<p>Note that the application is about High Frequency Trading (HFT) so performance is of extreme importance.</p> | 36,206,246 | 7 | 2 | null | 2016-03-24 10:43:04.15 UTC | 24 | 2016-07-11 15:19:57.603 UTC | 2016-07-11 15:19:57.603 UTC | null | 57,695 | null | 6,108,910 | null | 1 | 54 | java|garbage-collection|jvm|low-latency|hft | 19,776 | <blockquote>
<p>Which parts of the code should you warm up?</p>
</blockquote>
<p>Usually, you don't have to do anything. However for a low latency application, you should warmup the critical path in your system. You should have unit tests, so I suggest you run those on start up to warmup up the code.</p>
<p>Even once your code is warmed up, you have to ensure your CPU caches stay warm as well. You can see a significant slow down in performance after a blocking operation e.g. network IO, for up to 50 micro-seconds. Usually this is not a problem but if you are trying to stay under say 50 micro-seconds most of the time, this will be a problem most of the time.</p>
<p>Note: Warmup can allow Escape Analysis to kick in and place some objects on the stack. This means such objects don't need to be optimised away. It is better to memory profile your application before optimising your code.</p>
<blockquote>
<p>Even if I warm up some parts of the code, how long does it remain warm (assuming this term only means how long your class objects remain in-memory)?</p>
</blockquote>
<p>There is no time limit. It depends on whether the JIt detects whether the assumption it made when optimising the code turned out to be incorrect.</p>
<blockquote>
<p>How does it help if I have objects which need to be created each time I receive an event?</p>
</blockquote>
<p>If you want low latency, or high performance, you should create as little objects as possible. I aim to produce less than 300 KB/sec. With this allocation rate you can have an Eden space large enough to minor collect once a day.</p>
<blockquote>
<p>Consider for an example an application that is expected to receive messages over a socket and the transactions could be New Order, Modify Order and Cancel Order or transaction confirmed.</p>
</blockquote>
<p>I suggest you re-use objects as much as possible, though if it's under your allocation budget, it may not be worth worrying about.</p>
<blockquote>
<p>Note that the application is about High Frequency Trading (HFT) so performance is of extreme importance.</p>
</blockquote>
<p>You might be interested in our open source software which is used for HFT systems at different Investment Banks and Hedge Funds.</p>
<p><a href="http://chronicle.software/">http://chronicle.software/</a></p>
<blockquote>
<p>My production application is used for High frequency trading and every bit of latency can be an issue. It is kind of clear that at startup if you don't warmup your application, it will lead to high latency of few millis. </p>
</blockquote>
<p>In particular you might be interested in <a href="https://github.com/OpenHFT/Java-Thread-Affinity">https://github.com/OpenHFT/Java-Thread-Affinity</a> as this library can help reduce scheduling jitter in your critical threads.</p>
<blockquote>
<p>And also it is said that the critical sections of code which requires warmup should be ran (with fake messages) atleast 12K times for it to work in an optimized manner. Why and how does it work? </p>
</blockquote>
<p>Code is compiled using background thread(s). This means that even though a method might be eligible for compiling to native code, it doesn't mean that it has done so esp on startup when the compiler is pretty busy already. 12K is not unreasonable, but it could be higher.</p> |
66,410,115 | Difference between Variance, Covariance, Contravariance and Bivariance in TypeScript | <p>Could you please explain using small and simple TypeScript examples what is Variance, Covariance, Contravariance and Bivariance?</p>
<p><strong>[CONTINUOUS UPDATE]</strong></p>
<p><strong>Useful links:</strong></p>
<ol>
<li><p><a href="https://stackoverflow.com/questions/67482793/typescript-narrowing-type-with-generic-error">Another</a> one good answer of <a href="https://stackoverflow.com/users/11407695/oleg-valter">Oleg Valter</a> related to the topic</p>
</li>
<li><p><a href="https://www.youtube.com/watch?v=RH49aarW6sU" rel="nofollow noreferrer">Very good explanation</a> of*-riance by <a href="https://stackoverflow.com/users/125734/titian-cernicova-dragomir">Titian-Cernicova-Dragomir</a></p>
</li>
<li><p><a href="https://www.stephanboyer.com/post/132/what-are-covariance-and-contravariance" rel="nofollow noreferrer">Stephan Boyer</a> blog</p>
</li>
<li><p><a href="https://docs.scala-lang.org/tour/variances.html" rel="nofollow noreferrer">Scala documentation</a> - good explanation with examples</p>
</li>
<li><p>@Titian's <a href="https://stackoverflow.com/questions/62496072/difference-between-covariant-and-contravariant-positions-in-typescript">answer 1</a></p>
</li>
<li><p>@Titian's <a href="https://stackoverflow.com/questions/61696173/strictfunctiontypes-restricts-generic-type">answer 2</a></p>
</li>
<li><p><a href="https://vladris.com/blog/2019/12/27/variance.html" rel="nofollow noreferrer">Vlad Riscutia 's blog</a></p>
</li>
<li><p><a href="https://blog.ploeh.dk/2021/09/02/contravariant-functors/" rel="nofollow noreferrer">Mark Seemann 's</a> article</p>
</li>
<li><p>@jcalz <a href="https://stackoverflow.com/questions/68817839/what-does-contravariance-on-abstractrecoilvaluet-mean-in-recoil-source-type">explanation</a></p>
</li>
</ol> | 66,411,491 | 1 | 0 | null | 2021-02-28 14:30:51.763 UTC | 15 | 2022-08-02 22:06:11.877 UTC | 2022-06-14 19:45:27.957 UTC | null | 1,801,403 | null | 8,495,254 | null | 1 | 11 | typescript|covariance|variance|contravariance|invariance | 1,761 | <p><strong>Variance</strong> has to do with how a generic type <code>F<T></code> <em>varies</em> with respect to its type parameter <code>T</code>. If you know that <code>T extends U</code>, then variance will tell you whether you can conclude that <code>F<T> extends F<U></code>, conclude that <code>F<U> extends F<T></code>, or neither, or both.</p>
<hr />
<p><strong>Covariance</strong> means that <code>F<T></code> and <code>T</code> <em>co</em>-<em>vary</em>. That is, <code>F<T></code> <em>varies with</em> (in the same direction as) <code>T</code>. In other words, if <code>T extends U</code>, then <code>F<T> extends F<U></code>. Example:</p>
<ul>
<li><p>Function or method types co-vary with their return types:</p>
<pre><code>type Co<V> = () => V;
function covariance<U, T extends U>(t: T, u: U, coT: Co<T>, coU: Co<U>) {
u = t; // okay
t = u; // error!
coU = coT; // okay
coT = coU; // error!
}
</code></pre>
</li>
</ul>
<p>Other (un-illustrated for now) examples are:</p>
<ul>
<li>objects are covariant in their property types, even though this not sound for mutable properties</li>
<li>class constructors are covariant in their instance types</li>
</ul>
<hr />
<p><strong>Contravariance</strong> means that <code>F<T></code> and <code>T</code> <em>contra</em>-<em>vary</em>. That is, <code>F<T></code> <em>varies counter to</em> (in the opposite direction from) <code>T</code>. In other words, if <code>T extends U</code>, then <code>F<U> extends F<T></code>. Example:</p>
<ul>
<li><p>Function types contra-vary with their parameter types (with <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#strict-function-types" rel="noreferrer"><code>--strictFunctionTypes</code></a> enabled):</p>
<pre><code>type Contra<V> = (v: V) => void;
function contravariance<U, T extends U>(t: T, u: U, contraT: Contra<T>, contraU: Contra<U>) {
u = t; // okay
t = u; // error!
contraU = contraT; // error!
contraT = contraU; // okay
}
</code></pre>
</li>
</ul>
<p>Other (un-illustrated for now) examples are:</p>
<ul>
<li>objects are contravariant in their key types</li>
<li>class constructors are contravariant in their construct parameter types</li>
</ul>
<hr />
<p><strong>Invariance</strong> means that <code>F<T></code> neither varies with nor against <code>T</code>: <code>F<T></code> is neither covariant nor contravariant in <code>T</code>. This is actually what happens in the most general case. Covariance and contravariance are "fragile" in that when you combine covariant and contravariant type functions, its easy to produce invariant results. Example:</p>
<ul>
<li><p>Function types that return the same type as their parameter neither co-vary nor contra-vary in that type:</p>
<pre><code>type In<V> = (v: V) => V;
function invariance<U, T extends U>(t: T, u: U, inT: In<T>, inU: In<U>) {
u = t; // okay
t = u; // error!
inU = inT; // error!
inT = inU; // error!
}
</code></pre>
</li>
</ul>
<hr />
<p><strong>Bivariance</strong> means that <code>F<T></code> varies <em>both</em> with <em>and</em> against <code>T</code>: <code>F<T></code> is both covariant nor contravariant in <code>T</code>. In a sound type system, this essentially <em>never happens</em> for any non-trivial type function. You can demonstrate that only a constant type function like <code>type F<T> = string</code> is truly bivariant (quick sketch: <code>T extends unknown</code> is true for all <code>T</code>, so <code>F<T> extends F<unknown></code> and <code>F<unknown> extends T</code>, and in a sound type system if <code>A extends B</code> and <code>B extends A</code>, then <code>A</code> is the same as <code>B</code>. So if <code>F<T></code> = <code>F<unknown></code> for all <code>T</code>, then <code>F<T></code> is constant).</p>
<p>But Typescript does not have <a href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals" rel="noreferrer">nor does it intend to have</a> a fully sound type system. And there is <a href="https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-function-parameters-bivariant" rel="noreferrer">one notable case</a> where TypeScript treats a type function as bivariant:</p>
<ul>
<li><p>Method types both co-vary and contra-vary with their parameter types (this also happens with all function types with <code>--strictFunctionTypes</code> disabled):</p>
<pre><code>type Bi<V> = { foo(v: V): void };
function bivariance<U, T extends U>(t: T, u: U, biT: Bi<T>, biU: Bi<U>) {
u = t; // okay
t = u; // error!
biU = biT; // okay
biT = biU; // okay
}
</code></pre>
</li>
</ul>
<p><a href="https://www.typescriptlang.org/play?#code/LAKF5AXBPAHBTABAYQPYB4BqA+RBeRACgEp9dMBuUAMwFcA7AY0gEtV7FHUA3AQwCcWvJvHQBVADSIAKongAPSPHoATAM6Ix2QpABcMqbX2TOqafrTpp2KVzEWMW0gG9Qid4lr5EkCogD0-oioANa80G4ekN60foFy-Pyo-ACEEB6mYt5c0nFBoeGR7jnZqGJ5CUmpoAC+EDAIKOyQ-LxYuASE3PqYpHi43KgsKlQgdEys7Kb0Lbx8gsKMoiayCkqqGlo6+tKGxrbNreZNM61WNtOz9iez4tguRZ7evgH5YREgGdEEsa+VyWkwJ8PFxTrwsgRQbNcn94IkAY8oUdSmDyn8Ch86kCGkgAJL0dreLo9PrkUbjZhsDgsejzIQicRSVaKZTqTTaPQGTz7RA047485SGnXAVORCuYHuLwEF7xDGPb6eCpwqqAx7C7x85Xw6qS3n0WQEYXa1W1epwJAAIRYhIIzkQ1FQqGJiF6+kGw0QNXJDEpUwARiw6Ytlky5CyNuztlyjJopIHjtbBYhA9ck2KJRlpT4KvK9YrfvEVQigRlU94E7n3o8ExWWGi5dWQFigA" rel="noreferrer">Playground link to code</a></p> |
20,099,669 | Sort multidimensional array based on 2nd element of the subarray | <p>I have an array like this:</p>
<pre><code>[['G', 10], ['A', 22], ['S', 1], ['P', 14], ['V', 13], ['T', 7], ['C', 0], ['I', 219]]
</code></pre>
<p>I'd like to sort it based on the 2nd element in descending order.
An ideal output would be:</p>
<pre><code>[['I', 219], ['A', 22], ['P', 14], ... ]
</code></pre> | 20,099,713 | 4 | 0 | null | 2013-11-20 15:13:29.56 UTC | 21 | 2021-03-05 03:38:23.46 UTC | 2021-03-05 03:38:23.46 UTC | null | 11,573,842 | null | 2,211,874 | null | 1 | 52 | python|arrays|list|sorting|multidimensional-array | 98,947 | <p><code>list.sort</code>, <a href="http://docs.python.org/2/library/functions.html#sorted" rel="noreferrer"><code>sorted</code></a> accept optional <code>key</code> parameter. <code>key</code> function is used to generate comparison key.</p>
<pre><code>>>> sorted(lst, key=lambda x: x[1], reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
>>> sorted(lst, key=lambda x: -x[1])
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
>>> import operator
>>> sorted(lst, key=operator.itemgetter(1), reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
</code></pre> |
5,909,578 | Rounded corner & elliptical shape button in HTML | <p>I want to create a HTML button with rounded corner and elliptical shape without image.
What is the way to do it?</p> | 5,909,668 | 4 | 1 | null | 2011-05-06 09:43:43.387 UTC | 3 | 2015-07-25 08:37:36.057 UTC | null | null | null | null | 739,268 | null | 1 | 5 | html | 40,845 | <p>This makes all sides rounded:</p>
<pre><code>border-radius:40px;
</code></pre>
<p>This makes them elliptical:</p>
<pre><code>border-radius:40px/24px;
</code></pre>
<p>Have a look here to see:</p>
<p><a href="http://jsfiddle.net/xnTZq/" rel="noreferrer">http://jsfiddle.net/xnTZq/</a></p>
<p>Or with some extra ugly fanciness:</p>
<p><a href="http://jsfiddle.net/xnTZq/6/" rel="noreferrer">http://jsfiddle.net/xnTZq/6/</a></p> |
6,119,373 | no implicit conversion from nil to integer - when trying to add anything to array | <p>I'm trying to build a fairly complex hash and I am strangely getting the error</p>
<pre><code>no implicit conversion from nil to integer
</code></pre>
<p>when I use the line</p>
<pre><code>manufacturer_cols << {:field => 'test'}
</code></pre>
<p>I use the same line later in the same loop, and it works no problem.</p>
<p>The entire code is</p>
<pre><code>manufacturer_cols=[]
manufacturer_fields.each_with_index do |mapped_field, index|
if mapped_field.base_field_name=='exactSKU'
#this is where it is breaking, if I comment this out, all is good
manufacturer_cols << { :base_field=> 'test'}
else
#it works fine here!
manufacturer_cols << { :base_field=>mapped_field.base_field_name }
end
end
</code></pre>
<p>------- value of manufacturer_fields --------</p>
<p>[{"base_field":{"base_field_name":"Category","id":1,"name":"Category"}},{"base_field":{"base_field_name":"Description","id":3,"name":"Short_Description"}},{"base_field":{"base_field_name":"exactSKU","id":5,"name":"Item_SKU"}},{"base_field":{"base_field_name":"Markup","id":25,"name":"Retail_Price"}},{"base_field":{"base_field_name":"Family","id":26,"name":"Theme"}}]</p> | 6,120,326 | 4 | 9 | null | 2011-05-25 03:57:41.98 UTC | 2 | 2015-08-12 18:43:46.15 UTC | 2011-05-25 16:52:19.757 UTC | null | 48,067 | null | 48,067 | null | 1 | 15 | ruby|hash | 55,780 | <h3>Implicit Conversion Errors Explained</h3>
<p>I'm not sure precisely why your code is getting this error but I can tell you exactly what the error means, and perhaps that will help.</p>
<p>There are two kinds of conversions in Ruby: <em>explicit</em> and <em>implicit.</em></p>
<p>Explicit conversions use the short name, like <code>#to_s</code> or <code>#to_i.</code> These are commonly defined in the core, and they are called all the time. They are for objects that are not strings or not integers, but can be converted for debugging or database translation or string interpolation or whatever.</p>
<p>Implicit conversions use the long name, like <code>#to_str</code> or <code>#to_int.</code> This kind of conversion is for objects that are very much like strings or integers and merely need to know when to assume the form of their alter egos. These conversions are never or almost never defined in the core. (Hal Fulton's <em>The Ruby Way</em> identifies <em>Pathname</em> as one of the classes that finds a reason to define <code>#to_str</code>.)</p>
<p>It's quite difficult to get your error, even <code>NilClass</code> defines explicit (short name) converters:</p>
<pre><code>nil.to_i
=> 0
">>#{nil}<<" # this demonstrates nil.to_s
=> ">><<"
</code></pre>
<p>You can trigger it like so:</p>
<pre><code>Array.new nil
TypeError: no implicit conversion from nil to integer
</code></pre>
<p><strong><em>Therefore,</em></strong> your error is coming from the C code inside the Ruby interpreter. A core class, implemented in C, is being handed a <code>nil</code> when it expects an <code>Integer</code>. It may have a <code>#to_i</code> but it doesn't have a <code>#to_int</code> and so the result is the <em>TypeError.</em></p> |
1,606,320 | Android: custom separator (or even item) in ListView depening on content of item | <p>I've a ListView with items containing information about places with a <strong>rating</strong> and the <strong>distance</strong> to the current location.</p>
<p>The items are sorted into groups:</p>
<ul>
<li>Group 1: within 500m</li>
<li>Group 2: 500m - 1km</li>
<li>Group 3: 1km - 1.5km</li>
<li>...</li>
</ul>
<p>Withing these groups the items are sorted by their rating.</p>
<p>Now I put out these items via my custom adapter (extension of <code>BaseAdapter</code>) into the <code>ListView</code>, which works perfectly.</p>
<p>However, what I'd like to do is to put a separator before the each first item of each group. This separator can be a <code>TextView</code> saying e.g. <em>500m - 1km</em> followed by all the <code>ListView</code> items in that group.</p>
<p>Any idea on how to realize this?</p> | 1,606,642 | 2 | 0 | null | 2009-10-22 10:26:25.253 UTC | 17 | 2012-06-09 19:52:45.903 UTC | null | null | null | null | 184,367 | null | 1 | 11 | android|listview|separator | 24,581 | <p><a href="http://github.com/commonsguy/cw-advandroid/tree/master/ListView/Sections/" rel="noreferrer">Here is one implementation</a> that does exactly what you describe.</p>
<p>That one is GPLv3, because it is derived from <a href="http://jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/" rel="noreferrer">this implementation</a>, which was GPLv3.</p>
<p>You can also use my <a href="http://github.com/commonsguy/cwac-merge" rel="noreferrer"><code>MergeAdapter</code></a> for this, which has the advantage of being Apache License 2.0. Just hand it an alternating set of header <code>TextView</code>s and <code>Adapter</code>s containing each section's worth of content.</p>
<p>Or, you can peek at all of these and roll their behaviors into your existing <code>Adapter</code> class. The trick is to return your <code>TextView</code> headers at the right spot, and properly implement methods like <code>getViewTypeCount()</code>, <code>getItemViewType()</code>, <code>areAllItemsEnabled()</code>, and <code>isEnabled()</code>.</p> |
1,405,656 | Apache's mod_php OR FastCGI? Which is good for Wordpress? | <p>I have basic idea about running PHP in different configurations like mod_php, cgi, FastCGI, etc.</p>
<p>In my findings and test I found FastCGI is slightly better. I like FastCGI's support for SuEXEC most. Wait I do not want to get into benchmarking business here again. If you surf web, you will find people proving one way is faster than another in terms of number of requests handled per second. Well its good metrics but I am interested in different factors and here are my questions...</p>
<ol>
<li>Which method of running PHP consumes less memory? </li>
<li>Also which method consumes memory nearly constant. I see with mod_php my servers memory usage fluctuating between 300MB and 800MB, every few seconds.</li>
<li>But with FastCGI, first response from server comes very late. I see with FastCGI there is an initial delay per webpage request. Once first response from server arrives, other items like images, css, js loads pretty faster.</li>
<li>Is it OK to run mix of both? I have 5 sites on dedicated server. Is it ok if I run few with mod_php and rest with FastCGI?</li>
<li>I am sure that my server goes down mostly because of improper memory usage by mod_php. I checked all scripts. Is there any way to make sure memory consumption on server remains nearly constant?</li>
<li>Does complexity of .htaccess affects memory usage significantly? If yes, can it be a single reason to make server run out of memory?</li>
<li>Does apache MPM prefork/worker settings affect memory consumption? Do they affect mod_php and FastCGI mode equally?</li>
<li>When I run "top" command, I see apache (httpd) consuming memory around 40MB. There are many instances of httpd running. Also in addition to that FastCGI forks some processes of similar size. What is normal memory size for httpd process?</li>
<li>As I am running Wordpress on all of our sites, which will be good way in that context?</li>
<li>Does FastCGI/SuExec works fine with APC? Do I need to reconfigure APC to work with SuEXEC and FastCGI.</li>
</ol>
<p>Please note, I am less interested in surviving against DIGG or traffic spikes. I want a way which can make server stable and predictable.</p>
<p>Sorry if I am confusing but I am really in mess. I have 512MB physical RAM, 400MB Swap and my server is running out of memory like crazy. Average memory requirement is around 350MB, it just memory usage spikes makes memory unavailable for few seconds and if few extra hits received in those few second window, apache crashed while mysql and all other fellas keep running fine.</p>
<p>Please help me out guys. I am not gonna buy more RAM or hardware. I am damn sure that problem is in my configuration. Sorry if I sound arrogant or ignorant.</p> | 1,943,706 | 2 | 2 | null | 2009-09-10 14:34:08.713 UTC | 12 | 2015-03-12 08:08:12.713 UTC | 2011-10-21 15:28:56.093 UTC | null | 229,044 | null | 156,336 | null | 1 | 20 | php|apache|wordpress|fastcgi|mod-php | 18,947 | <blockquote>
<p>Which method of running PHP consumes less memory?</p>
</blockquote>
<p>I assume that per PHP-processed request they are more or less the same. But if you have mod_php loaded into apache serving images too, then I assume your memory footprint will be higher due to serving static files.</p>
<blockquote>
<p>Also which method consumes memory nearly constant. I see with mod_php my servers memory usage fluctuating between 300MB and 800MB, every few seconds.</p>
</blockquote>
<p>You can make both pretty constant. If you carefully set MaxClients, MinSpareServers and MaxSpareServers, you pretty much can tell how many processes are running. If you also set memory_limit within your PHP config, you can calculate how much memory you need.
You can do the same for fcgi too, since you can decide how many processes are running.</p>
<blockquote>
<p>But with FastCGI, first response from server comes very late. I see with FastCGI there is an initial delay per webpage request. Once first response from server arrives, other items like images, css, js loads pretty faster.</p>
</blockquote>
<p>This doesn't make sense. I am not sure why it happens in your case.</p>
<blockquote>
<p>Is it OK to run mix of both? I have 5 sites on dedicated server. Is it ok if I run few with mod_php and rest with FastCGI?</p>
</blockquote>
<p>I guess, but it will both be a nightmare to maintain and will probably be harder to configure for <em>saving memory</em>. Quite the contrary I believe.</p>
<blockquote>
<p>I am sure that my server goes down mostly because of improper memory usage by mod_php. I checked all scripts. Is there any way to make sure memory consumption on server remains nearly constant?</p>
</blockquote>
<p>Configure memory and processes as I outlined above, and keep monitoring.</p>
<blockquote>
<p>Does complexity of .htaccess affects memory usage significantly? If yes, can it be a single reason to make server run out of memory?</p>
</blockquote>
<p>I don't think so. per-directory .htaccess can slow things down, but unless there is some serious bug in Apache, it should not cause mass memory consumption.</p>
<blockquote>
<p>Does apache MPM prefork/worker settings affect memory consumption? Do they affect mod_php and FastCGI mode equally?</p>
</blockquote>
<p>It might, but I recommend to stay away from worker, as PHP is mostly not thread safe.</p>
<blockquote>
<p>When I run "top" command, I see apache (httpd) consuming memory around 40MB. There are many instances of httpd running. Also in addition to that FastCGI forks some processes of similar size. What is normal memory size for httpd process?</p>
</blockquote>
<p>30MB is the min. The upper limit depends on your application (I have seen cases where it was ~1GB)</p>
<blockquote>
<p>As I am running Wordpress on all of our sites, which will be good way in that context?</p>
</blockquote>
<p>It is probably a matter of taste. I have recently moved away from apache towards nginx+fastcgi. it takes a bit of time to get used to, but it does work well. No problems whatsoever with wordpress (even not with supercache, which is rather involved in terms of web server).</p>
<blockquote>
<p>Does FastCGI/SuExec works fine with APC? Do I need to reconfigure APC to work with SuEXEC and FastCGI.</p>
</blockquote>
<p>I am not using suExec, but fastcgi works well with APC. No need to configure anything.</p> |
2,263,404 | What package I should install for 'pcre-devel'? | <p>I need to install the <code>pcre-devel</code> package to compile <code>lighttpd</code> on Ubuntu:</p>
<blockquote>
<p>configure: error: pcre-config not found, install the pcre-devel package or build with --without-pcre</p>
</blockquote>
<p>Can you please tell me how to do that?</p> | 2,263,433 | 2 | 0 | null | 2010-02-15 00:10:20.927 UTC | 2 | 2021-04-21 12:53:26.323 UTC | 2017-05-02 22:19:19.483 UTC | null | 3,266,847 | null | 114,970 | null | 1 | 35 | ubuntu | 62,644 | <p>Try using <code>apt-cache search</code>, e.g.,</p>
<pre><code>apt-cache search pcre
</code></pre>
<p>For me this turns up a lot so I grep for the keyword <code>dev</code>.</p>
<p>This turns up <code>libpcre3-dev</code> and <code>libpcre++-dev</code>.</p>
<p><code>lighttpd</code> will use one of those no doubt.</p>
<p>So if your search shows <code>libpcre3-dev</code>, you can install using:<br />
<code>sudo apt install libpcre3-dev</code></p>
<p>However, is there any reason you're compiling lighttpd yourself?<br />
Why not install using <code>apt</code>?<br />
Including <code>lighttpd-dev</code>, <code>lighttpd-doc</code> and some related modules.</p> |
45,807,049 | How to run Vue.js dev serve with https? | <p>I'm using Vue-cli to create vue project with webpack template. how to run it with https in development using: <code>npm run dev</code>?</p> | 45,808,037 | 9 | 1 | null | 2017-08-21 23:57:01.223 UTC | 27 | 2022-07-09 21:01:17.79 UTC | null | null | null | null | 5,297,029 | null | 1 | 89 | https|webpack|vue.js | 88,022 | <p>Webpack template uses <a href="http://expressjs.com/en/api.html" rel="noreferrer"><code>express</code></a> as the server for development. So just replace </p>
<pre><code>var server = app.listen(port)
</code></pre>
<p>with following code in <code>build/dev-server.js</code></p>
<pre><code>var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('/* replace me with key file's location */'),
cert: fs.readFileSync('/* replace me with cert file's location */'))
};
var server = https.createServer(options, app).listen(port);
</code></pre>
<p>Please note that in webpack template, <code>http://localhost:8080</code> will be automatically opened in your browser by using <a href="https://github.com/sindresorhus/opn" rel="noreferrer">opn</a> module. So you'd better replace <code>var uri = 'http://localhost:' + port</code> with <code>var uri = 'https://localhost:' + port</code> for convenience. </p> |
68,481,686 | type 'typeof globalThis' has no index signature | <p>i get this error whenever i try to add a function to the global nodejs global namsepace in a TypeScript environment.</p>
<blockquote>
<p>Element implicitly has an 'any' type because type 'typeof globalThis'
has no index signature</p>
</blockquote>
<p>declaring the global namespace</p>
<pre><code>declare global {
namespace NodeJS {
interface Global {
signin(): string[]
}
}
}
</code></pre>
<p>so if i try this</p>
<pre><code>global.signin = () => {}
</code></pre>
<p>it returns a</p>
<blockquote>
<p>Element implicitly has an 'any' type because type 'typeof globalThis'
has no index signature</p>
</blockquote> | 69,241,623 | 8 | 3 | null | 2021-07-22 08:36:18.24 UTC | 8 | 2022-08-26 15:26:16.443 UTC | 2021-09-13 12:51:53.473 UTC | null | 270,274 | null | 11,730,825 | null | 1 | 32 | node.js|typescript|microservices | 18,732 | <p>in my own case i didn't quite realize until later that the global namespace i declared was case sensitive.</p>
<p>instead of this. before my question was edited it was <code>namespace NODEJS</code></p>
<pre><code>declare global {
namespace NODEJS {
interface Global {
signin(): string[]
}
}
}
</code></pre>
<p>it was supposed to be this</p>
<pre><code>declare global {
namespace NodeJS {
interface Global {
signin(): string[]
}
}
}
</code></pre>
<p>pay attention to <code>NODEJS and NodeJS</code>. After i made these changes, typescript was cool with it and it work the way i expected it to.</p> |
29,329,662 | Are ES6 module imports hoisted? | <p>I know that in the new ES6 module syntax, the JavaScript engine will not have to <strong>evaluate</strong> the code to know about all the imports/exports, it will only <strong>parse</strong> it and “know” what to load.</p>
<p>This sounds like hoisting. Are the ES6 modules hoisted? And if so, will they all be loaded before running the code?</p>
<p>Is this code possible?</p>
<pre class="lang-js prettyprint-override"><code>import myFunc1 from 'externalModule1';
myFunc2();
if (Math.random()>0.5) {
import myFunc2 from 'externalModule2';
}
</code></pre> | 29,334,761 | 3 | 1 | null | 2015-03-29 13:26:00.807 UTC | 6 | 2017-05-06 05:52:07.847 UTC | 2016-11-26 22:33:09.527 UTC | null | 3,853,934 | null | 1,075,401 | null | 1 | 43 | javascript|ecmascript-6|hoisting|es6-modules | 20,123 | <p>After doing some more research, I've found:</p>
<ul>
<li>Imports ARE hoisted! according to the <a href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-module-records" rel="noreferrer">spec</a> of <strong><em>ModuleDeclarationInstantiation</em></strong></li>
<li>ALL the dependent Modules will be loaded before running any code.</li>
</ul>
<p>This code will have no errors, and will work:</p>
<pre><code>localFunc();
import {myFunc1} from 'mymodule';
function localFunc() { // localFunc is hoisted
myFunc1();
}
</code></pre> |
29,245,848 | what are all the dtypes that pandas recognizes? | <p>For pandas, would anyone know, if any datatype apart from</p>
<p>(i) <code>float64</code>, <code>int64</code> (and other variants of <code>np.number</code> like <code>float32</code>, <code>int8</code> etc.)</p>
<p>(ii) <code>bool</code></p>
<p>(iii) <code>datetime64</code>, <code>timedelta64</code></p>
<p>such as string columns, always have a <code>dtype</code> of <code>object</code> ? </p>
<p>Alternatively, I want to know, if there are any datatype apart from (i), (ii) and (iii) in the list above that <code>pandas</code> does not make it's <code>dtype</code> an <code>object</code>?</p> | 29,246,498 | 3 | 2 | null | 2015-03-25 01:14:35.177 UTC | 22 | 2020-12-22 23:39:24.35 UTC | null | null | null | null | 2,526,657 | null | 1 | 86 | python|python-3.x|pandas | 118,863 | <p><strong>EDIT Feb 2020 following pandas 1.0.0 release</strong></p>
<p>Pandas mostly uses NumPy arrays and dtypes for each Series (a dataframe is a collection of Series, each which can have its own dtype). NumPy's documentation further explains <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html#numpy.dtype" rel="noreferrer">dtype</a>, <a href="https://docs.scipy.org/doc/numpy/user/basics.types.html" rel="noreferrer">data types</a>, and <a href="https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#arrays-dtypes" rel="noreferrer">data type objects</a>. In addition, the answer provided by @lcameron05 provides an excellent description of the numpy dtypes. Furthermore, the pandas docs on <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/basics.html?highlight=basics#dtypes" rel="noreferrer">dtypes</a> have a lot of additional information.</p>
<blockquote>
<p>The main types stored in pandas objects are float, int, bool,
datetime64[ns], timedelta[ns], and object. In addition these dtypes
have item sizes, e.g. int64 and int32.</p>
</blockquote>
<blockquote>
<p>By default integer types are int64 and float types are float64,
REGARDLESS of platform (32-bit or 64-bit). The following will all
result in int64 dtypes.</p>
<p>Numpy, however will choose platform-dependent types when creating
arrays. The following WILL result in int32 on 32-bit platform.
One of the major changes to version 1.0.0 of pandas is the introduction of <code>pd.NA</code> to represent scalar missing values (rather than the previous values of <code>np.nan</code>, <code>pd.NaT</code> or <code>None</code>, depending on usage).</p>
</blockquote>
<p>Pandas extends NumPy's type system and also allows users to write their on <a href="https://pandas.pydata.org/pandas-docs/stable/development/extending.html#extending-extension-types" rel="noreferrer">extension types</a>. The following lists all of pandas extension types.</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-timezone" rel="noreferrer"><strong>1) Time zone handling</strong></a></p>
<p>Kind of data: tz-aware datetime (note that NumPy does not support timezone-aware datetimes).</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeTZDtype.html#pandas.DatetimeTZDtype" rel="noreferrer">DatetimeTZDtype</a></p>
<p>Scalar: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html#pandas.Timestamp" rel="noreferrer">Timestamp</a></p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.DatetimeArray.html#pandas.arrays.DatetimeArray" rel="noreferrer">arrays.DatetimeArray</a></p>
<p>String Aliases: 'datetime64[ns, ]'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#categorical" rel="noreferrer"><strong>2) Categorical data</strong></a></p>
<p>Kind of data: Categorical</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.CategoricalDtype.html#pandas.CategoricalDtype" rel="noreferrer">CategoricalDtype</a></p>
<p>Scalar: (none)</p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.html#pandas.Categorical" rel="noreferrer">Categorical</a></p>
<p>String Aliases: 'category'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-periods" rel="noreferrer"><strong>3) Time span representation</strong></a></p>
<p>Kind of data: period (time spans)</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodDtype.html#pandas.PeriodDtype" rel="noreferrer">PeriodDtype</a></p>
<p>Scalar: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Period.html#pandas.Period" rel="noreferrer">Period</a></p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.PeriodArray.html#pandas.arrays.PeriodArray" rel="noreferrer">arrays.PeriodArray</a></p>
<p>String Aliases: 'period[]', 'Period[]'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#sparse" rel="noreferrer"><strong>4) Sparse data structures</strong></a></p>
<p>Kind of data: sparse</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.SparseDtype.html#pandas.SparseDtype" rel="noreferrer">SparseDtype</a></p>
<p>Scalar: (none)</p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.SparseArray.html#pandas.arrays.SparseArray" rel="noreferrer">arrays.SparseArray</a></p>
<p>String Aliases: 'Sparse', 'Sparse[int]', 'Sparse[float]'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-intervalindex" rel="noreferrer"><strong>5) IntervalIndex</strong></a></p>
<p>Kind of data: intervals</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IntervalDtype.html#pandas.IntervalDtype" rel="noreferrer">IntervalDtype</a></p>
<p>Scalar: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Interval.html#pandas.Interval" rel="noreferrer">Interval</a></p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.IntervalArray.html#pandas.arrays.IntervalArray" rel="noreferrer">arrays.IntervalArray</a></p>
<p>String Aliases: 'interval', 'Interval', 'Interval[<numpy_dtype>]', 'Interval[datetime64[ns, ]]', 'Interval[timedelta64[]]'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html#integer-na" rel="noreferrer"><strong>6) Nullable integer data type</strong></a></p>
<p>Kind of data: nullable integer</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Int64Dtype.html#pandas.Int64Dtype" rel="noreferrer">Int64Dtype</a>, ...</p>
<p>Scalar: (none)</p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.IntegerArray.html#pandas.arrays.IntegerArray" rel="noreferrer">arrays.IntegerArray</a></p>
<p>String Aliases: 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#text" rel="noreferrer"><strong>7) Working with text data</strong></a></p>
<p>Kind of data: Strings</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.StringDtype.html#pandas.StringDtype" rel="noreferrer">StringDtype</a></p>
<p>Scalar: <a href="https://docs.python.org/3/library/stdtypes.html#str" rel="noreferrer">str</a></p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.StringArray.html#pandas.arrays.StringArray" rel="noreferrer">arrays.StringArray</a></p>
<p>String Aliases: 'string'</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/arrays.html#api-arrays-bool" rel="noreferrer"><strong>8) Boolean data with missing values</strong></a></p>
<p>Kind of data: Boolean (with NA)</p>
<p>Data type: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.BooleanDtype.html#pandas.BooleanDtype" rel="noreferrer">BooleanDtype</a></p>
<p>Scalar: <a href="https://docs.python.org/3/library/functions.html#bool" rel="noreferrer">bool</a></p>
<p>Array: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.BooleanArray.html#pandas.arrays.BooleanArray" rel="noreferrer">arrays.BooleanArray</a></p>
<p>String Aliases: 'boolean'</p> |
50,609,417 | Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded | <p>When trying to post documents to Elasticsearch as normal I'm getting this error:</p>
<pre><code>cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)];
</code></pre>
<p>I also see this message on the Elasticsearch logs:</p>
<pre><code>flood stage disk watermark [95%] exceeded ... all indices on this node will marked read-only
</code></pre> | 50,609,418 | 8 | 1 | null | 2018-05-30 16:21:40.16 UTC | 87 | 2022-09-22 09:21:19.183 UTC | null | null | null | null | 1,175,266 | null | 1 | 292 | elasticsearch | 227,469 | <p>This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.</p>
<p>By default Elasticsearch's decision is based on the <strong>percentage</strong> of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.</p>
<p>The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.</p>
<p>For docs about the flood stage watermark see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html" rel="noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html</a>.</p>
<p>The right solution depends on the context - for example a production environment vs a development environment.</p>
<h2>Solution 1: free up disk space</h2>
<p>Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:</p>
<pre><code>$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
</code></pre>
<h2>Solution 2: change the flood stage watermark setting</h2>
<p>Change the <code>"cluster.routing.allocation.disk.watermark.flood_stage"</code> setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html" rel="noreferrer">the docs</a>:</p>
<pre><code>PUT _cluster/settings
{
"transient": {
"cluster.routing.allocation.disk.watermark.low": "100gb",
"cluster.routing.allocation.disk.watermark.high": "50gb",
"cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
"cluster.info.update.interval": "1m"
}
}
</code></pre>
<p>Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.</p> |
32,244,774 | What is the Android Studio Terminal Pane? | <p>This may seem trivial, but I really can`t find anything with Google, so I ask here: What is the "Android Studio Terminal pane" mentioned here (under "Add the configuration file to your project"),
<a href="https://developers.google.com/cloud-messaging/android/client" rel="noreferrer">https://developers.google.com/cloud-messaging/android/client</a>
and where can I find it?</p> | 32,244,927 | 5 | 1 | null | 2015-08-27 08:51:57.207 UTC | 3 | 2020-05-11 20:26:57.18 UTC | null | null | null | null | 3,869,448 | null | 1 | 17 | android|android-studio | 50,510 | <p>Here it is! Bottom of your Android Studio, select Terminal.
<a href="https://i.stack.imgur.com/s74dI.png"><img src="https://i.stack.imgur.com/s74dI.png" alt="enter image description here"></a></p>
<p>You can also go to: Tools -> Open Terminal</p>
<p><strong>Hint for Android Studio</strong>: Menu Help -> Find Action -> type what are you looking for. Android Studio will give you couple matches accordingly to your search criteria. Most of the times you can find what you are looking for with this "Find Action" option. </p> |
6,312,484 | UITableView delete all rows at once | <p>How is it possible to delete all rows from UITableView at once?
Because when I reload table view with new data, I am still inserting new rows:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomTableViewCell alloc] initWithFrame:CGRectZero] autorelease];
}
//... setting the new cell here ...
return cell;
}
</code></pre>
<p>Thank you.</p> | 6,312,682 | 5 | 1 | null | 2011-06-10 21:56:44.977 UTC | 7 | 2014-11-18 20:51:12.25 UTC | 2012-04-27 22:16:59.483 UTC | null | 227,532 | null | 329,242 | null | 1 | 18 | objective-c|uitableview|uikit | 45,654 | <p>Do this.</p>
<p>Before you are reloading the table with</p>
<pre><code>[tableView reloadData];
</code></pre>
<p>Remove all objects from your tableView array (The array which populated your tableView)
For example.</p>
<pre><code>[myArray removeAllObjects];
[tableView reloadData];
</code></pre> |
6,124,523 | Linking a static library to an iOS project in Xcode 4 | <p>I have a project (<code>AQGridView</code>) that compiles to a static library, but I can't seem to add it to my project.</p>
<p>Dragging in the project to my project creates a workspace, and if I try to link the <code>libAQGridView.a</code> file from the <code>DerivedData</code> directory it doesn't recognize it as a library. I'm not sure what I'm doing wrong.</p>
<p>This is the <code>AQGridView</code> project. Does anyone know specifically how to use it in an Xcode 4 project?</p> | 6,124,872 | 6 | 3 | null | 2011-05-25 12:35:22.52 UTC | 38 | 2022-04-18 05:16:03.273 UTC | 2019-07-09 08:01:04.787 UTC | null | 1,033,581 | null | 443,554 | null | 1 | 76 | iphone|objective-c|ios|xcode4 | 77,648 | <p>I do this as follows:</p>
<ol>
<li>Drag in the static library project. If you have the static library project open in Xcode, close it now.</li>
<li>Select the main project in the project navigator (the project I'm adding the static library to) and in the editor, under the header TARGETS in the left-hand column, select my main project's target and navigate to the Build Phases tab.</li>
<li>Click the "+" for Target Dependencies and add the library icon target dependency from the added static library project.</li>
<li>Click the "+" for Link Binary with Libraries and add the library icon that is under the folder "Workspace".</li>
<li>It may also be necessary to enter a Header Search Path for the headers of the static library project if that is how the headers are linked in the static library project itself.</li>
</ol>
<p>If you don't see the static library project as nested under the main project in the main project's project navigator, the most likely reason for that is that the static library's own Xcode project is still open. Quit Xcode and open up the main project that has the nested static library project in it without opening up the original static library project itself, and you should see it appearing as a nested project in your main project.</p> |
39,027,204 | Regex get domain name from email | <p>I am learning regex and am having trouble getting <code>google</code> from email address</p>
<p>String</p>
<pre><code>[email protected]
</code></pre>
<p>I just want to get google, not google.com</p>
<p>Regex:</p>
<pre><code>[^@].+(?=\.)
</code></pre>
<p>Result: <a href="https://regex101.com/r/wA5eX5/1" rel="noreferrer">https://regex101.com/r/wA5eX5/1</a></p>
<p>From my understanding. It ignore <code>@</code> find a string after that until <code>.</code> (dot) using <code>(?=\.)</code></p>
<p>What did I do wrong?</p> | 39,027,263 | 9 | 1 | null | 2016-08-18 20:46:08.45 UTC | 3 | 2022-09-08 22:41:08.863 UTC | null | null | null | null | 791,022 | null | 1 | 25 | regex | 39,128 | <p><code>[^@]</code> means "match one symbol that is <em>not</em> an <code>@</code> sign. That is not what you are looking for - use lookbehind <code>(?<=@)</code> for <code>@</code> and your <code>(?=\.)</code> lookahead for <code>\.</code> to extract server name in the middle:</p>
<pre><code>(?<=@)[^.]+(?=\.)
</code></pre>
<p>The middle portion <code>[^.]+</code> means "one or more non-dot characters".</p>
<p><a href="https://regex101.com/r/vE8rP9/1" rel="noreferrer">Demo.</a></p> |
25,187,048 | Run Executable from Powershell script with parameters | <p>So I have a powershell script that is supposed to run an executable with an argument to pass to set which method I want to run, and I need to pass a parameter, which is a directory to a config file. So this is what I have</p>
<pre><code>Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList /genmsi/f $MySourceDirectory\src\Deployment\Installations.xml
</code></pre>
<p>/f is the shortname and file is the long name for my attribute... I get an error in powershell telling me that a positional parameter cannot be found for /f or /file.</p>
<p>Any thoughts?</p> | 25,494,058 | 4 | 1 | null | 2014-08-07 15:58:08.08 UTC | 14 | 2016-08-25 16:16:55.153 UTC | null | null | null | null | 674,896 | null | 1 | 47 | powershell|command-line | 230,538 | <p>I was able to get this to work by using the <code>Invoke-Expression</code> cmdlet.</p>
<pre><code>Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
</code></pre> |
25,131,484 | Rundll32.exe javascript | <p>I've just (August 2014) seen a report of a program that uses the command line</p>
<pre><code>rundll32.exe javascript:"\..\mshtml,RunHTMLApplication"
</code></pre>
<p>How does that work? I thought the first parameter was supposed to be the name of a DLL (mshtml), but how does rundll32 parse that command line?</p>
<p>rundll reference:
<a href="http://support.microsoft.com/kb/164787">http://support.microsoft.com/kb/164787</a></p> | 25,427,342 | 1 | 1 | null | 2014-08-05 05:00:34.583 UTC | 9 | 2018-02-08 05:00:26.567 UTC | null | null | null | null | 1,335,492 | null | 1 | 9 | javascript|mshtml|rundll32 | 10,462 | <p>There's a great explanation of this here: <a href="http://thisissecurity.net/2014/08/20/poweliks-command-line-confusion/">http://thisissecurity.net/2014/08/20/poweliks-command-line-confusion/</a></p>
<p>To summarize using the same example of:</p>
<pre><code>rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";alert('foo');
</code></pre>
<ol>
<li><strong>RunDll32</strong>
<ol>
<li>Parses the command and decides the intended DLL is: <code>javascript:"\..\mshtml</code></li>
<li>Fails at loading that as an absolute path.</li>
<li>Fails to find a match in the working directory or on the path.</li>
<li>Fails to find a manifest <code>javascript:"\..\mshtml.manifest</code>for the module.</li>
<li>Calls <em>LoadLibrary</em></li>
</ol></li>
<li><strong>LoadLibrary</strong>
<ol>
<li>Adds the extension and attempts to load <code>javascript:"\..\mshtml.dll</code></li>
<li>Treats this as relative, so it goes up from the fake <code>javascript:"\</code> directory.</li>
<li>Searches for <code>mshtml.dll</code> which it finds in the System directory.</li>
<li>Loads the DLL using <em>RunHTMLApplication</em> as the entry point.</li>
</ol></li>
<li><strong>RunHTMLApplication</strong>
<ol>
<li>Attempts to execute the command <code>";alert('foo');</code></li>
<li>As that's invalid Javascript it calls <em>GetCommandLine</em> for the original command which returns <code>javascript:"\..\mshtml,RunHTMLApplication ";alert('foo');</code></li>
<li>Attempts to open this URI so it asks the system how to handle the <em>javascript</em> protocol which is typically set to <em>Microsoft HTML Javascript Pluggable Protocol</em> in the registry.</li>
<li>Then executes the Javascript: <code>"..\mshtml,RunHTMLApplication ";alert('foo');</code></li>
</ol></li>
<li><strong>Javascript</strong>
<ol>
<li>The first statement creates a string and does nothing with it which is valid enough to not cause an error.</li>
<li>Continues executing the rest of the script.</li>
</ol></li>
</ol> |
33,108,326 | How to pass client-side parameters to the server-side in Angular/Node.js/Express | <p>Probably a very basic question, but I cannot seem to find a simple answer. </p>
<p>I have a GET method leveraging Angular's <code>$http</code> that is requesting a promise from a particular url (<code>URL_OF_INTEREST</code>).</p>
<p>On this server, I run an express script <code>server.js</code> script that can handle GET requests.</p>
<p><strong>server.js</strong></p>
<pre><code>var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var stripe = require("stripe")("CUSTOM_TEST_TOKEN");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router(); // get an instance of the express Router
router.get('/', function(req, res, next) {
var stripeToken = "CUSTOM_PAYMENT_TOKEN";
var charge = stripe.charges.create({
amount: 1100, // amount in cents, again
currency: "usd",
source: stripeToken,
description: "Example charge"
}, function(err, charge) {
if (err && err.type === 'StripeCardError') {
res.json(err);
} else {
res.json(charge);
}
});
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
app.use('/api', router); // register our route
app.listen(port); // start our server
console.log('Magic happens on port ' + port);
</code></pre>
<p>I can communicate with the URL_OF_INTEREST using an Angular GET method as follows:</p>
<pre><code>$http.get('URL_OF_INTEREST')
.success(
function(success){
console.log(success)
})
.error(
function(error){
console.log(error)
});
</code></pre>
<p>However, the fields amount, currency, source and description need to be ideally passed on from the Angular client side application.</p>
<p>How can this be achieved and how can my express application read this data?</p> | 33,108,469 | 4 | 0 | null | 2015-10-13 16:53:01.803 UTC | 4 | 2016-06-14 03:39:23.577 UTC | null | null | null | null | 4,262,057 | null | 1 | 7 | javascript|angularjs|node.js|express|angularjs-http | 37,996 | <p>You need to pass the data in your get call as folow:</p>
<pre><code>var data = {
amount: 3,
currency: 2,
source: 3,
description: 4
};
$http.get('URL_OF_INTEREST', data) // PASS THE DATA AS THE SECOND PARAMETER
.success(
function(success){
console.log(success)
})
.error(
function(error){
console.log(error)
});
</code></pre>
<p>And in your backend, you can get your url parameters as folow:</p>
<pre><code>router.get('/', function(req, res, next) {
var amount = req.query.amount; // GET THE AMOUNT FROM THE GET REQUEST
var stripeToken = "CUSTOM_PAYMENT_TOKEN";
var charge = stripe.charges.create({
amount: 1100, // amount in cents, again
currency: "usd",
source: stripeToken,
description: "Example charge"
}, function(err, charge) {
if (err && err.type === 'StripeCardError') {
res.json(err);
} else {
res.json(charge);
}
});
});
</code></pre> |
33,878,825 | How to permanently redirect `http://` and `www.` URLs to `https://`? | <p>I have a Google App Engine project. On this project I have setup a custom domain and an SSL certificate. Therefore, I can use <code>https://www.mysite.xxx</code>, <code>http://www.mysite.xxx</code> and just the naked domain <code>mysite.xxx</code>.</p>
<p>Is it possible to permanently redirect the last two to always use the secure <code>https://</code> domain using the developers console or do I just have to redirect in the code?</p> | 33,880,474 | 7 | 0 | null | 2015-11-23 19:16:48.373 UTC | 10 | 2021-04-15 20:48:55.243 UTC | 2018-08-18 00:34:50.017 UTC | null | 4,642,212 | null | 430,861 | null | 1 | 42 | google-app-engine|https|url-redirection | 17,078 | <p>So you can add "secure: always" to your yaml file</p>
<p><a href="https://cloud.google.com/appengine/docs/python/config/appconfig?hl=en#Python_app_yaml_Secure_URLs" rel="noreferrer">https://cloud.google.com/appengine/docs/python/config/appconfig?hl=en#Python_app_yaml_Secure_URLs</a></p> |
19,001,450 | AFNetworking 2.0 cancel specific task | <p>I am trying out afnetworking 2.0 and just trying to figure out how to cancel specific tasks.
The old way would be to use something like</p>
<pre><code>[self cancelAllHTTPOperationsWithMethod:@"POST" path:@"user/receipts"]
</code></pre>
<p>but I dont see anything like this in 2.0</p>
<p>I created a sub class of <code>AFHTTPSessionManager</code> which gives me access to the array of pending tasks and I can cancel them directly but I dont know how to identify 1 task from another so I can cancel only specific tasks.
Task does have an taskidentifier but this doesnt appear to be what I need.</p>
<pre><code>NSString *path = [NSString stringWithFormat:@"user/receipts"];
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:[prefs valueForKey:@"uuid"] password:self.store.authToken];
[self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
completionBlock(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
errorBlock(error);
}];
</code></pre>
<p>now if i wanted to cancel this request only how would I approach this?</p> | 19,004,345 | 3 | 0 | null | 2013-09-25 09:44:16.793 UTC | 8 | 2014-04-08 19:51:00.74 UTC | 2013-09-27 22:57:12.78 UTC | null | 412,916 | null | 408,947 | null | 1 | 17 | ios|afnetworking|afnetworking-2 | 9,793 | <p>You can store the task in a variable so you can access it later:</p>
<pre><code>NSURLSessionDataTask* task = [self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
completionBlock(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
errorBlock(error);
}];
</code></pre>
<p>Then simply cancel it with <code>[task cancel]</code>.</p>
<p>Another way would be to save the task ID of the task and later ask the URL session for its tasks and identify the task you wish to cancel:</p>
<pre><code>// save task ID
_savedTaskID = task.taskIdentifier;
// cancel specific task
for (NSURLSessionDataTask* task in [self dataTasks]) {
if (task.taskIdentifier == _savedTaskID) {
[task cancel];
}
}
</code></pre> |
24,427,056 | What is an operand stack? | <p>I am reading about JVM architecture. Today I read about the concept of the Operand Stack. According to an article:</p>
<blockquote>
<p>The operand stack is used during the execution of byte code instructions
in a similar way that general-purpose registers are used in a native CPU.</p>
</blockquote>
<p>I can't understand: What exactly is an Operand Stack, and how does it work in jvm?</p> | 24,427,197 | 3 | 0 | null | 2014-06-26 09:35:07.183 UTC | 14 | 2020-04-01 07:11:19.587 UTC | 2014-06-26 14:21:33.34 UTC | null | 1,464,444 | null | 3,713,995 | null | 1 | 46 | java|jvm | 13,844 | <p>It's how the various individual bytecode operations get their input, and how they provide their output.</p>
<p>For instance, consider the <code>iadd</code> operation, which adds two <code>int</code>s together. To use it, you push two values on the stack and then use it:</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>Now the top value on the stack is the sum of those two local variables. The next operation might take that top stack value and store it somewhere, or we might push another value on the stack to do something else.</p>
<p>Suppose you want to add three values together. The stack makes that easy:</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
iload_2 # Push the value from local variable 2 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>Now the top value on the stack is the result of adding together those three local variables.</p>
<p>Let's look at that second example in more detail:</p>
<p>We'll assume:</p>
<ul>
<li>The stack is empty to start with <em>(which is almost never actually true, but we don't care what's on it before we start)</em></li>
<li>Local variable 0 contains <code>27</code></li>
<li>Local variable 1 contains <code>10</code></li>
<li>Local variable 2 contains <code>5</code></li>
</ul>
<p>So initially:</p>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
+−−−−−−−+</pre>
<p>Then we do</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
</code></pre>
<p>Now we have</p>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
| 27 |
+−−−−−−−+</pre>
<p>Next</p>
<pre><code>iload_1 # Push the value from local variable 1 onto the stack
</code></pre>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
| 10 |
| 27 |
+−−−−−−−+</pre>
<p>Now we do the addition:</p>
<pre><code>iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>It "pops" the <code>10</code> and <code>27</code> off the stack, adds them together, and pushes the result (<code>37</code>). Now we have:</p>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
| 37 |
+−−−−−−−+</pre>
<p>Time for our third <code>int</code>:</p>
<pre><code>iload_2 # Push the value from local variable 2 onto the stack
</code></pre>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
| 5 |
| 37 |
+−−−−−−−+</pre>
<p>We do our second <code>iadd</code>:</p>
<pre><code>iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>That gives us:</p>
<pre>+−−−−−−−+
| stack |
+−−−−−−−+
| 42 |
+−−−−−−−+</pre>
<p><em>(Which is, of course, the <a href="http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29" rel="noreferrer">Answer to the Ultimate Question of Life the Universe and Everything</a>.)</em></p> |
49,599,274 | How to submit a form in Vue, redirect to a new route and pass the parameters? | <p>I am using Nuxt and Vue and I am trying to submit a form, redirect the user to a new route including the submitted params, send an API request to get some data and then render that data.</p>
<p>I achieved this by simply setting the form action to the new path and manually adding all the URL parameters to the API request.</p>
<p>First I create a simple form with the route <code>/search</code>.</p>
<pre><code><form action="/search">
<input type="text" name="foobar">
<button type="submit">Submit</button>
</form>
</code></pre>
<p>When submitting the form the user leaves the current page and gets redirected to the new page. The URL would now look like this: <code>http://www.example.com/search?foobar=test</code>. Now I fetch the <code>foobar</code> parameter by using <code>this.$route.query.foobar</code> and send it to my API.</p>
<p>However the problem in my approach is when submitting the form the user leaves the current page and a new page load will occur. This is not what we want when building progressive web apps.</p>
<p>So my question is how can I submit a form in Nuxt/Vue and redirect to a new route including the submitted parameters?</p> | 49,609,883 | 3 | 0 | null | 2018-04-01 14:50:53.017 UTC | 7 | 2022-05-12 12:22:09.2 UTC | null | null | null | null | 1,032,472 | null | 1 | 29 | javascript|node.js|vue.js|nuxt.js | 41,661 | <p>The default behavior of <code><form></code> is to reload the page <code>onsubmit</code>. When implementing SPA's it would be better to avoid invoking default behavior of <code><form></code>.</p>
<p>Making use of <code>router module</code> which is available out-of-box in nuxtjs will enable all the redirection controls to flow within the application. if we try to trigger events available via <code><form></code> then browser reload will occur. This has to be avoided.</p>
<blockquote>
<p>So my question is how can I submit a form in Nuxt/Vue and redirect to
a new route including the submitted parameters?</p>
</blockquote>
<p>You can try below approach</p>
<p><strong>First</strong></p>
<p>Use <code>.stop.prevent</code> modifiers to prevent the submit button from invoking default <code><form></code> behavior. This is similar to using <code>event.stopPropagation();</code> and <code>event.preventDefault();</code> in jQuery</p>
<pre class="lang-html prettyprint-override"><code><form>
<input type="text" name="foobar" v-model="foobar">
<button type="submit" @click.stop.prevent="submit()">Submit</button>
</form>
</code></pre>
<p><strong>Then</strong></p>
<p>Create</p>
<ol>
<li><p>vue model object <code>foobar</code></p>
</li>
<li><p>vue method <code>submit</code></p>
</li>
</ol>
<p>Use <code>this.$router.push</code> to redirect to next page. This will enable the control flow to stay inside the SPA. if you want to send any data into server then you can do it before invoking <code>this.$router.push</code> else you can redirect and continue your logic.</p>
<pre class="lang-js prettyprint-override"><code>export default {
data(){
return {
foobar : null
}
},
methods: {
submit(){
//if you want to send any data into server before redirection then you can do it here
this.$router.push("/search?"+this.foobar);
}
}
}
</code></pre> |
44,099,594 | How to make a tkinter canvas rectangle with rounded corners? | <p>I would like to create a rectangle with rounded corners. I'm using canvas from tkinter. </p> | 44,100,075 | 3 | 0 | null | 2017-05-21 17:08:20.77 UTC | 9 | 2021-04-12 14:42:44.953 UTC | null | null | null | null | 7,173,551 | null | 1 | 14 | python|python-3.x|canvas|tkinter|tkinter-canvas | 26,392 | <p>Offering an alternate approach to tobias's method would be to indeed do it with one polygon.</p>
<p>This would have the advantage of being one canvas object if you are worried about optimization, or not having to worry about a tag system for referring to a single object.</p>
<p>The code is a bit longer, but very basic, as it is just utilizing the idea that when smoothing a polygon, you can give the same coordinate twice to 'stop' the smooth from occuring.</p>
<p>This is an example of what can be done:</p>
<pre><code>from tkinter import *
root = Tk()
canvas = Canvas(root)
canvas.pack()
def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return canvas.create_polygon(points, **kwargs, smooth=True)
my_rectangle = round_rectangle(50, 50, 150, 100, radius=20, fill="blue")
root.mainloop()
</code></pre>
<p>Using this function, you can just provide the normal coordinates that you would to a rectangle, and then specify the 'radius' which is rounded in the corners. The use of <code>**kwargs</code> denotes that you can pass keyword arguments such as <code>fill="blue"</code>, just as you usually could with a <code>create_</code> method.</p>
<p>Although the coords look complex, it is just going around methodically to each point in the 'rectangle', giving each non-corner point twice.</p>
<p>If you didn't mind a rather long line of code, you could put all the coordinates on one line, making the function just 2 lines(!). This looks like:</p>
<pre><code>def round_rectangle(x1, y1, x2, y2, r=25, **kwargs):
points = (x1+r, y1, x1+r, y1, x2-r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y1+r, x2, y2-r, x2, y2-r, x2, y2, x2-r, y2, x2-r, y2, x1+r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y2-r, x1, y1+r, x1, y1+r, x1, y1)
return canvas.create_polygon(points, **kwargs, smooth=True)
</code></pre>
<p>This produces the following (Note in mind this is ONE canvas object):</p>
<p><a href="https://i.stack.imgur.com/uChml.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uChml.png" alt="Rounded rectangle produced by function" /></a></p>
<hr />
<p>If you want to update the position of the rectangle after it has been created, you could use a function like this (if in the same scope as the original <code>canvas</code> object):</p>
<pre><code>def update_rectangle_coords(round_rect, x1, y1, x2, y2, r=25):
points = (x1+r, y1, x1+r, y1, x2-r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y1+r, x2, y2-r, x2, y2-r, x2, y2, x2-r, y2, x2-r, y2, x1+r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y2-r, x1, y1+r, x1, y1+r, x1, y1)
canvas.coords(round_rect, *points)
</code></pre>
<p>So, to update <code>my_rectangle</code>'s position (from the first code example), we could say:</p>
<pre><code>update_rectangle_coords(my_rectangle, 20, 20, 100, 100)
</code></pre> |
31,718,637 | Determine optimization level in preprocessor? | <p><code>-Og</code> is a relatively new optimization option that is intended to improve the debugging experience while apply optimizations. If a user selects <code>-Og</code>, then I'd like my source files to activate alternate code paths to enhance the debugging experience. GCC offers the <a href="https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros" rel="noreferrer"><code>__OPTIMIZE__</code> preprocessor macro</a>, but its only set to 1 when optimizations are in effect.</p>
<p>Is there a way to learn the optimization level, like <code>-O1</code>, <code>-O3</code> or <code>-Og</code>, for use with the preprocessor?</p> | 31,718,804 | 3 | 0 | null | 2015-07-30 08:22:31.91 UTC | 2 | 2021-03-24 20:47:03.193 UTC | null | null | null | null | 608,639 | null | 1 | 28 | c|gcc|gdb|compiler-optimization|c-preprocessor | 5,011 | <p>I believe this is not possible to know directly the optimization level used to compile the software as this is not in <a href="https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html" rel="noreferrer">the list of defined preprocessor symbols</a></p>
<p>You could rely on <code>-DNDEBUG</code> (no debug) which is used to disable assertions in release code and enable your "debug" code path in this case.</p>
<p>However, I believe a better thing to do is having a system wide set of symbols local to your project and let the user choose what to use explicitly.:</p>
<ul>
<li><code>MYPROJECT_DNDEBUG</code></li>
<li><code>MYPROJECT_OPTIMIZE</code></li>
<li><code>MYPROJECT_OPTIMIZE_AGGRESSIVELY</code></li>
</ul>
<p>This makes debugging or the differences of behavior between release/debug much easier as you can incrementally turn on/off the different behaviors. </p> |
30,215,830 | Dockerfile copy keep subdirectory structure | <p>I'm trying to copy a number of files and folders to a docker image build from my localhost.</p>
<p>The files are like this:</p>
<pre><code>folder1/
file1
file2
folder2/
file1
file2
</code></pre>
<p>I'm trying to make the copy like this:</p>
<pre><code>COPY files/* /files/
</code></pre>
<p>However, all of the files from <code>folder1/</code> and <code>folder2/</code> are placed in <code>/files/</code> directly, without their folders:</p>
<pre><code>files/
file1
file2
</code></pre>
<p>Is there a way in Docker to keep the subdirectory structure as well as copying the files into their directories?</p> | 30,220,096 | 5 | 3 | null | 2015-05-13 13:09:42.62 UTC | 47 | 2022-08-18 17:11:58.103 UTC | 2022-05-24 18:41:43.747 UTC | null | 5,223,757 | null | 1,220,022 | null | 1 | 445 | copy|docker|dockerfile | 417,089 | <p>Remove star from COPY, with this Dockerfile:</p>
<pre><code>FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*
</code></pre>
<p>Structure is there:</p>
<pre class="lang-sh prettyprint-override"><code>$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon
Step 0 : FROM ubuntu
---> d0955f21bf24
Step 1 : COPY files/ /files/
---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b
</code></pre> |
34,012,775 | pyspark and HDFS commands | <p>I would like to do some cleanup at the start of my Spark program (Pyspark). For example, I would like to delete data from previous HDFS run. In pig this can be done using commands such as </p>
<pre><code>fs -copyFromLocal ....
rmf /path/to-/hdfs
</code></pre>
<p>or locally using sh command.</p>
<p>I was wondering how to do the same with Pyspark.</p> | 34,019,256 | 4 | 1 | null | 2015-12-01 04:45:55.457 UTC | 13 | 2021-04-12 02:35:17.123 UTC | 2015-12-01 11:27:19.787 UTC | null | 1,560,062 | null | 3,803,714 | null | 1 | 12 | python|apache-spark|hdfs|pyspark | 31,589 | <p>You can execute arbitrary shell command using form example <a href="https://docs.python.org/3.5/library/subprocess.html#subprocess.call" rel="noreferrer"><code>subprocess.call</code></a> or <a href="https://pypi.python.org/pypi/sh" rel="noreferrer"><code>sh</code> library</a> so something like this should work just fine:</p>
<pre><code>import subprocess
some_path = ...
subprocess.call(["hadoop", "fs", "-rm", "-f", some_path])
</code></pre>
<p>If you use Python 2.x you can try using <a href="https://github.com/spotify/snakebite" rel="noreferrer"><code>spotify/snakebite</code></a>:</p>
<pre><code>from snakebite.client import Client
host = ...
port = ...
client = Client(host, port)
client.delete(some_path, recurse=True)
</code></pre>
<p><a href="https://hdfs3.readthedocs.io/en/latest/" rel="noreferrer"><code>hdfs3</code></a> is yet another library which can be used to do the same thing:</p>
<pre><code>from hdfs3 import HDFileSystem
hdfs = HDFileSystem(host=host, port=port)
HDFileSystem.rm(some_path)
</code></pre>
<p><a href="https://arrow.apache.org/docs/python/filesystems.html#hadoop-file-system-hdfs" rel="noreferrer">Apache Arrow Python bindings</a> are the latest option (and that often is already available on Spark cluster, as it is required for <code>pandas_udf</code>):</p>
<pre><code>from pyarrow import hdfs
fs = hdfs.connect(host, port)
fs.delete(some_path, recursive=True)
</code></pre> |
22,918,517 | NPM/Bower/Composer - differences? | <p>Can someone explain to me the difference between <code>NPM</code>, <code>Bower</code> and <code>Composer</code>.</p>
<p>They are all package managers - correct?</p>
<p>But when should each one be used?</p>
<p>Also, each one appears to have a json file that accompanies it, does this store all the packages you require so they can be installed by cmd line? Why do you need this file?</p> | 22,920,758 | 1 | 1 | null | 2014-04-07 16:53:34.23 UTC | 37 | 2021-12-18 14:25:41.73 UTC | 2015-12-02 20:44:31.373 UTC | null | 5,493,302 | null | 1,013,512 | null | 1 | 113 | npm|composer-php|bower | 44,821 | <h2>[<strong>update, four years later</strong>]</h2>
<ul>
<li><code>bower</code> is deprecated, and should not be used anymore for new projects. To a large extent, it has been subsumed into node dependency management (from their website: "While Bower is maintained, we recommend using Yarn and Webpack or Parcel for front-end projects").</li>
<li><code>yarn</code> came out of the wood as a better <code>npm</code> (fixing several of <code>npm</code> flaws), and this is really what you should use now, as it is the new de-facto standard if you are doing front-end or node development. It does consume the same <code>package.json</code> as npm, and is almost entirely compatible with it.</li>
<li>I wouldn't use <code>composer</code> at this point (because I wouldn't use <code>php</code>), although it seems to still be alive and popular</li>
</ul>
<h2>[<strong>original answer</strong>]</h2>
<p><code>npm</code> is nodejs package manager. It therefore targets nodejs environments, which usually means server-side nodejs projects or command-line projects (bower itself is a npm package). If you are going to do anything with nodejs, then you are going to use npm.</p>
<p><code>bower</code> is a package manager that aims at (front-end) web projects. You need npm and nodejs to install bower and to execute it, though bower packages are not meant specifically for nodejs, but rather for the "browser" environment.</p>
<p><code>composer</code> is a dependency manager that targets php projects. If you are doing something with symfony (or plain old php), this is likely the way to go</p>
<p>Summing it up:</p>
<ul>
<li>doing node? you do npm</li>
<li>doing php? try composer</li>
<li>front-end javascript? try bower</li>
</ul>
<p>And yes, the "json" files describe basic package information and dependencies. And yes, they are needed.</p>
<p>Now, what about the READMEs? :-)</p>
<ul>
<li><a href="https://github.com/bower/bower" rel="noreferrer">https://github.com/bower/bower</a></li>
<li><a href="https://www.npmjs.org/doc/cli/npm.html" rel="noreferrer">https://www.npmjs.org/doc/cli/npm.html</a></li>
<li><a href="https://getcomposer.org/doc/00-intro.md" rel="noreferrer">https://getcomposer.org/doc/00-intro.md</a></li>
</ul> |
7,309,110 | CSS3 transition on a background image | <p>I want to do an CSS3 transform: rotate(360deg); in a transition 1s;
on a background image instead of a seperate image(element)..
Is this possible? I have searched the hell out of Google but no succes!
What I am trying to achieve is something like: </p>
<pre><code>#footerLogo {
background: url('ster.png'),
-moz-transition: -moz-transform 1s,
transition: transform 1s,
-o-transition: -o-transform 1s,
-webkit-transition: -webkit-transform 1s;
background-position: #outlinedtotheleft;
}
#footerLogo:hover {
background: transform: rotate(360deg);
-o-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
</code></pre>
<p>I hope this is possible! I know it is easily doable in JS (jQuery) with: </p>
<pre><code>$('#something').hover(function(){morecodehere});
</code></pre>
<p>...but I want to know if it is possible with only CSS(3)</p>
<p>HTML:</p>
<pre><code><div id="footerLogo">
<img src="carenza.png"/>
</div>
</code></pre> | 7,310,379 | 2 | 1 | null | 2011-09-05 13:55:59.703 UTC | 2 | 2015-02-19 20:15:03.447 UTC | 2012-07-28 18:43:40.59 UTC | null | 16,511 | null | 798,022 | null | 1 | 11 | html|css|background|css-transitions | 38,338 | <p>Sure you can, try something like this:</p>
<p><strong>HTML</strong></p>
<pre><code><div id="planet">
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#planet {
width:200px;
height:200px;
background: transparent url(http://cdn3.iconfinder.com/data/icons/nx11/Internet%20-%20Real.png) no-repeat center center;
}
#planet {
-webkit-animation-name: rotate;
-webkit-animation-duration:2s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;
-moz-animation-name: rotate;
-moz-animation-duration:2s;
-moz-animation-iteration-count:infinite;
-moz-animation-timing-function:linear;
}
@-webkit-keyframes rotate {
from {-webkit-transform:rotate(0deg);}
to { -webkit-transform:rotate(360deg);}
}
@-moz-keyframes rotate {
from {-moz-transform:rotate(0deg);}
to { -moz-transform:rotate(360deg);}
}
</code></pre>
<p><a href="http://jsfiddle.net/andresilich/YqdJb/1/">JSFiddle</a></p> |
7,635,593 | How to do a second transform on the output of an XSLT template | <p>I have only basic XSLT skills so apologies if this is either basic or impossible.</p>
<p>I have a paginator template which is used everywhere on the site I'm looking at. There's a bug where one particular search needs to have a categoryId parameter appended to the href of the page links. <em>I can't alter the paginator stylesheet</em> or else i would just add a param to it. What I'd like to do is apply the template as is then do a second transform based on its output. Is this possible? How do others normally go about extending library templates?</p>
<p>So far I've thought about doing a recursive copy of the output and applying a template to the hrefs as they are processed. The syntax for that escapes me somewhat, particularly as I'm not even sure it's possible. </p>
<hr>
<p>Edit - Between Dabbler's answer and Michael Kay's comment we got there. Here is my complete test.</p>
<pre><code> <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common">
<!-- note we require the extensions for this transform -->
<!--We call the template to be extended here and store the result in a variable-->
<xsl:variable name="output1">
<xsl:call-template name="pass1"/>
</xsl:variable>
<!--The template to be extended-->
<xsl:template name="pass1">
<a href="url?param1=junk">foo</a>
</xsl:template>
<!--the second pass. we lock this down to a mode so we can control when it is applied-->
<xsl:template match="a" mode="pass2">
<xsl:variable name="href" select="concat(@href, '&amp;', 'catid', '=', 'stuff')"/>
<a href="{$href}"><xsl:value-of select="."/></a>
</xsl:template>
<xsl:template match="/">
<html><head></head><body>
<!--the node-set extension function turns the first pass back into a node set-->
<xsl:apply-templates select="ext:node-set($output1)" mode="pass2"/>
</body></html>
</xsl:template>
</xsl:stylesheet>
</code></pre> | 7,637,740 | 2 | 0 | null | 2011-10-03 13:24:23.853 UTC | 10 | 2016-06-09 14:00:42.647 UTC | 2011-10-06 10:57:51.483 UTC | null | 111,082 | null | 111,082 | null | 1 | 17 | xslt | 9,681 | <p>It's possible in XSLT 2; you can store data in a variable and call apply-templates on that.</p>
<p>Basic example:</p>
<pre><code><xsl:variable name="MyVar">
<xsl:element name="Elem"/> <!-- Or anything that creates some output -->
</xsl:variable>
<xsl:apply-templates select="$MyVar"/>
</code></pre>
<p>And somewhere in your stylesheet have a template that matches Elem. You can also use a separate mode to keep a clear distinction between the two phases (building the variable and processing it), especially when both phases use templates that match the same nodes.</p> |
19,066,140 | Doctrine error: "Failed opening required '/tmp/__CG__Source.php' " | <p>I am trying to migrate my PHP application to an Ubuntu server, but without succes. Any help would be appreciated.</p>
<p>First I installed Doctrine successfully into /jorrit/myapp, following the first part of Doctrine's <a href="http://docs.doctrine-project.org/en/latest/tutorials/getting-started.html" rel="noreferrer">Getting Started</a> manual (till "Generating the Database Schema"). Secondly I placed my PHP scripts (which use Doctrine) in folder /jorrit/myapp.</p>
<p>When I try to run my PHP script in the CLI, I get this error messages:</p>
<blockquote>
<p>PHP Warning: require(/tmp/__CG__Source.php): failed to open stream: No such file or directory in /jorrit/myapp/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php on line 200</p>
<p>PHP Fatal error: require(): Failed opening required '/tmp/__CG__Source.php' (include_path='.:/usr/share/php:/usr/share/pear') in /jorrit/myapp/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php on line 200</p>
</blockquote>
<p>Bootstrap.php looks like this:</p>
<pre><code><?php
// bootstrap.php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
require_once "vendor/autoload.php";
// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = false;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
// the connection configuration
$dbParams = array(
'driver' => 'pdo_mysql',
'host' => 'xx',
'user' => 'xx',
'password' => 'xx',
'dbname' => 'xx',
'profiler' => 'false'
);
// obtaining the entity manager
$entityManager = EntityManager::create($dbParams, $config);
?>
</code></pre>
<p>The first lines of my PHP script:</p>
<pre><code><?php
require_once "bootstrap.php";
require_once 'classes.php';
$connection = $entityManager->getConnection();
</code></pre>
<p>The application works fine in my development environment (Windows). The /tmp folder exists and is accessible. The database is migrated succesfully and exists. I did not change anything in the vendor folder.</p>
<p>Any ideas? Thanks in advance for your help.</p> | 20,231,349 | 3 | 1 | null | 2013-09-28 10:53:37.473 UTC | 11 | 2015-12-15 00:13:34.663 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,366,136 | null | 1 | 35 | php|symfony|doctrine-orm | 25,258 | <p>TL;DR You'll just need to generate your proxy classes manually</p>
<pre><code>vendor/bin/doctrine orm:generate-proxies
</code></pre>
<p>Doctrine uses Proxies to connect the to database. Proxies are generated from the the Entity classes.</p>
<p>In development mode, it generates a Proxies on every request because you could make changes to Entity classes.</p>
<p>In production mode, it does not generate Proxies every time. For performance reason, it assumes the Proxies exist and include them directly.</p>
<p>There are a few mode for Proxies generation:</p>
<ol>
<li>ALWAYS - It alwayes generates Proxies, this is the default setting for development mode</li>
<li>NEVER - It never generates Proxies, this is the default setting for production mode</li>
<li>ON_DEMAND - It only generates the Proxies if the Proxy files do not exist. The drawback of this option is that it has to call file_exists() every time which could potentially cause a performance issue.</li>
</ol>
<p>Now the command </p>
<pre><code>vendor/bin/doctrine orm:generate-proxies
</code></pre>
<p>generates Proxy classes to /tmp. I would say this might still cause trouble because other applications
on your server might delete these files unexpectedlly. One option is you can change your /tmp directory access permission to 1777</p>
<pre><code>sudo chmod 1777 /tmp
</code></pre>
<p>The stricky bit '1' in front of 777 means that, although everyone can read/write to the /tmp directory, but you can only operate on your own files. i.e. You can't remove files created by other users.</p>
<p>For further reading, please have a look at
<a href="http://docs.doctrine-project.org/en/latest/reference/advanced-configuration.html#auto-generating-proxy-classes-optional" rel="noreferrer">http://docs.doctrine-project.org/en/latest/reference/advanced-configuration.html#auto-generating-proxy-classes-optional</a></p>
<p>You can also set the Proxies directory to somewhere else so no other applications can modify them. <a href="http://docs.doctrine-project.org/en/latest/reference/advanced-configuration.html#autoloading-proxies" rel="noreferrer">http://docs.doctrine-project.org/en/latest/reference/advanced-configuration.html#autoloading-proxies</a></p> |
38,051,977 | what does populate in mongoose mean? | <p>I came across the following line of code which I couldn't understand ,although there are lot of tutorials that gives information related to examples of <code>populate</code> but there is none that explains what exactly it means.Here is a example </p>
<pre><code>var mongoose = require('mongoose'), Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String,
age : Number,
stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : {
type: Schema.ObjectId,
ref: 'Person'
},
title : String,
fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Story.findOne({ title: /Nintendo/i }).populate('_creator') .exec(function (err, story) {
if (err) ..
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})
</code></pre> | 38,140,808 | 5 | 2 | null | 2016-06-27 10:46:29.043 UTC | 32 | 2021-04-10 12:45:41.063 UTC | 2016-06-27 11:40:30.85 UTC | null | 4,221,420 | null | 4,221,420 | null | 1 | 49 | mongoose|mongoose-populate | 74,563 | <p><code>populate()</code> function in mongoose is used for populating the data inside the reference. In your example <code>StorySchema</code> is having <code>_creator</code> field which will reference to the <code>_id</code> field which is basically the <code>ObjectId</code> of the mongodb document.</p>
<blockquote>
<p>populate() function can accept a string or an object as an input.</p>
</blockquote>
<p>Where string is the field name which is required to be populated. In your case that is <code>_creator</code>. After mongoose found one doc from mongodb and the result of that is like below</p>
<pre><code>_creator: {
name: "SomeName",
age: SomeNumber,
stories: [Set Of ObjectIDs of documents in stories collection in mongodb]
},
title: "SomeTitle",
fans: [Set of ObjectIDs of documents in persons collection in mongodb]
</code></pre>
<blockquote>
<p>populate can also accept the object as an input.</p>
</blockquote>
<p>You can find the documents of mongoose's <code>populate()</code> function here :
<a href="http://mongoosejs.com/docs/2.7.x/docs/populate.html" rel="noreferrer">http://mongoosejs.com/docs/2.7.x/docs/populate.html</a> or <a href="https://mongoosejs.com/docs/populate.html" rel="noreferrer">https://mongoosejs.com/docs/populate.html</a></p> |
37,033,129 | spring yml file for specific environment | <p>I have 3 <code>yml</code> files namely </p>
<ul>
<li><code>application-default.yml</code> -> default properties, should be available
in all profiles</li>
<li><code>application-dev.yml</code> -> properties only for dev
profile</li>
<li><code>application-prod.yml</code> -> properties only for prod profile</li>
</ul>
<p>When I start my boot application by passing the <code>-Dspring.profiles.active=dev</code>,I am able to access the <code>application-dev.yml</code> specific properties.
But I cant get the properties defined in the <code>application-default.yml</code> files.
Following is my <code>application-dev.yml</code> file:</p>
<pre><code>Spring:
profiles:
include: default
spring.profiles: dev
prop:
key:value
</code></pre> | 37,043,216 | 3 | 2 | null | 2016-05-04 16:21:00.087 UTC | 9 | 2018-07-03 10:52:36.04 UTC | 2016-05-05 06:31:20.28 UTC | null | 4,414,557 | null | 5,873,698 | null | 1 | 18 | java|spring|spring-boot|yaml | 32,032 | <p>I was able to solve my problem, here is what I did.</p>
<p>Created a file application-common.yml, put the common properties there.
Then in the application-{env}.yml files I put this on the top.</p>
<pre><code>spring:
profiles:
include: default
</code></pre>
<p>Since I dont need to ever load the default profile specifically, this works for me!!!</p> |
35,461,203 | Angular 2. How to apply orderBy? | <p>I have a piece of code.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#participant of participants; #i = index">
<td>{{i+1}}</td>
<td>{{participant.username}}</td>
<td>{{participant.score}}</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<p>In Angular 1 i have <strong>orderBy</strong> filter to order rows by my filter. But how can i do orderBy in Angular 2 the same way ? Thank you.</p> | 35,465,976 | 4 | 1 | null | 2016-02-17 15:39:44.95 UTC | 7 | 2020-07-07 01:16:28.063 UTC | null | null | null | null | 5,930,884 | null | 1 | 9 | javascript|angular | 53,836 | <p>You need to implement a custom pipe for this. This corresponds to create a class decorated by @Pipe. Here is a sample. Its transform method will actually handle the list and you will be able to sort it as you want:</p>
<pre><code>import { Pipe } from "angular2/core";
@Pipe({
name: "orderby"
})
export class OrderByPipe {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
</code></pre>
<p>You can then use this pipe as described below in expressions. For example in an ngFor. Don't forget to specify your pipe into the <code>pipes</code> attribute of the component where you use it:</p>
<pre><code>@Component({
(...)
template: `
<li *ngFor="list | orderby"> (...) </li>
`,
pipes: [ OrderByPipe ]
})
(...)
</code></pre> |
3,657,953 | How do I get the jQuery-UI version? | <p>This should be an easy question, but how do I detect the jQuery-UI version?</p>
<p>This is for a Greasemonkey script and the (current) target page appears to be running jQuery-UI, 1.5.2. But, different target pages may run different versions.</p>
<p><code>console.log ($.ui);</code> did not show anything useful/obvious for version detection.</p> | 3,658,001 | 1 | 0 | null | 2010-09-07 10:51:04.447 UTC | 10 | 2016-01-01 04:07:21.36 UTC | null | null | null | null | 331,508 | null | 1 | 71 | jquery|jquery-ui|greasemonkey | 42,040 | <p>You can use <a href="http://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.core.js#L21" rel="noreferrer"><code>$.ui.version</code></a>, it's actually the property jQuery UI looks for when determining if it should load itself (if it's already there, abort).</p>
<p>For example <a href="http://jsfiddle.net/nick_craver/YtE2J/" rel="noreferrer">here's a fiddle including version 1.8.4</a>.</p>
<p>Unfortunately, <code>$.ui.version</code> was added in jQuery-UI version 1.6.</p>
<p>For earlier versions, you can check for <code>$.ui</code> though.</p>
<p>So, in this case, the following might be good enough:</p>
<pre><code>var version = $.ui ? $.ui.version || "pre 1.6" : 'jQuery-UI not detected';
</code></pre> |
47,619,229 | Google sign in failed com.google.android.gms.common.api.ApiException: 10: | <p>So I'm Stuck on this frustrating issue.
I am quite new to Google Auth on Firebase but I done everything the firebase docs instructed in how to integrate the Google SignIn Auth, yet I'm still receiving this weird Error in the console consisted of two parts:</p>
<pre><code>12-03 11:07:40.090 2574-3478/com.google.android.gms E/TokenRequestor: You have wrong OAuth2 related configurations, please check. Detailed error: UNREGISTERED_ON_API_CONSOLE
</code></pre>
<p>and also</p>
<pre><code>Google sign in failed com.google.android.gms.common.api.ApiException: 10:
</code></pre>
<p><strong>Before Anyone attempts to point out similar questions that have previously been asked on stack overflow, Here's what I have done till now after seen all the available solutions and yet non has resolved the error</strong></p>
<ul>
<li>I have my SHA1 fingerprint for my project</li>
<li>I have my OAuth 2.0 client ID, both, the android client id and the web client and in the requestIdToken() I have put the <strong>web client id</strong>.</li>
<li>I did <strong>not</strong> publish my project's APK on google play store. which means I did not accidentally generate another SHA1 fingerprint.</li>
<li>I have followed step by step the Google Sign in Auth firebase docs.</li>
</ul>
<p>here is my code snippet:</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
String webClientId = getString(R.string.web_client_id);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(webClientId)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
googleLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// [START_EXCLUDE]
Toast.makeText(this, "Gooogle Auth failed", Toast.LENGTH_LONG);
// [END_EXCLUDE]
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
// [START_EXCLUDE silent]
//showProgressDialog();
// [END_EXCLUDE]
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(LoginActivity.this, "Successful Auth", Toast.LENGTH_LONG).show();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// [START_EXCLUDE]
//hideProgressDialog();
// [END_EXCLUDE]
}
});
}
</code></pre> | 47,620,437 | 25 | 5 | null | 2017-12-03 14:12:27.1 UTC | 15 | 2022-07-11 10:13:37.887 UTC | null | null | null | null | 5,136,577 | null | 1 | 86 | android|firebase|google-authentication | 111,759 | <p>Basically problem is in the <code>SHA1</code> key put on console please regenerate it and put again properly same project.</p>
<p>1)As the answers, make sure that your actual signed Android <code>apk</code> has the same <code>SHA1</code> fingerprint as what you specified in the console of your Firebase project's Android integration section (the page where you can download the <code>google-services.json</code>)</p>
<p>For more info, see: <a href="https://stackoverflow.com/questions/51845559/generate-sha-1-for-flutter-app/56091158#56091158">Generate SHA-1 for Flutter app</a></p>
<p>2)On top of that go to the Settings of your firebase project (gear icon right to the Overview at the top-left area. Then switch to Account Linking tab. On that tab link the Google Play to your project.</p>
<p>EDIT:
Account Linking tab doesn't exist any more, instead :</p>
<ol>
<li>Sign in to Firebase.</li>
<li>Click the Settings icon, then select Project settings.</li>
<li>Click the Integrations tab.</li>
<li>On the Google Play card, click <code>Link</code>.</li>
</ol>
<p><a href="https://i.stack.imgur.com/9u8Sy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9u8Sy.png" alt="enter image description here"></a></p> |
1,377,037 | How to set a default tab with Jquery UI | <p>I'm using Jquery and Jquery UI with the following:</p>
<pre><code>$(document).ready(function() {
$('#tabvanilla > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle' } });
});
</code></pre>
<p>Right now it automatically sets the first tabs as the default tab that is selected when the document loads. How do I override this and make the second tab the default selected tab when the page loads?</p> | 1,377,045 | 3 | 0 | null | 2009-09-04 03:15:27.273 UTC | 3 | 2013-02-11 04:37:44.363 UTC | 2013-01-04 15:53:45.42 UTC | null | 122,139 | null | 168,286 | null | 1 | 13 | jquery|jquery-ui|tabs | 44,573 | <pre><code>$('#tabvanilla > ul').tabs({ selected: 1 });
</code></pre>
<p>More details on the <a href="http://jqueryui.com/demos/tabs/#option-selected" rel="noreferrer">specifications page</a>.</p> |
1,792,763 | With Maven, how can I build a distributable that has my project's jar and all of the dependent jars? | <p>I have a project (of type 'jar') that (obviously) builds a jar. But that project has many dependencies. I'd like Maven to build a "package" or "assembly" that contains my jar, all the dependent jars, and some scripts (to launch the application, etc.)</p>
<p>What's the best way to go about this? Specifically, what's the best way to get the dependents into the assembly?</p> | 1,793,017 | 3 | 0 | null | 2009-11-24 20:36:21.257 UTC | 14 | 2015-09-25 13:55:44.87 UTC | 2009-11-24 20:37:21.24 UTC | null | 21,234 | null | 44,757 | null | 1 | 28 | java|maven-2 | 6,279 | <p>For a single module, I'd use an assembly looking like the following one (<code>src/assembly/bin.xml</code>):</p>
<pre><code><assembly>
<id>bin</id>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<dependencySets>
<dependencySet>
<unpack>false</unpack>
<scope>runtime</scope>
<outputDirectory>lib</outputDirectory>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>src/main/command</directory>
<outputDirectory>bin</outputDirectory>
<includes>
<include>*.sh</include>
<include>*.bat</include>
</includes>
</fileSet>
</fileSets>
</assembly>
</code></pre>
<p>To use this assembly, add the following configuration to your pom.xml:</p>
<pre><code> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/assembly/bin.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</code></pre>
<p>In this sample, start/stop scripts located under <code>src/main/command</code> and are bundled into <code>bin</code>, dependencies are bundled into <code>lib</code>. Customize it to suit your needs.</p> |
8,403,866 | Values in a pie chart | <p>How do you display the values of each pie in a pie chart using ChartHelper? I am using MVC3/Razor syntax.</p>
<p>Trying to do something like this:</p>
<p><img src="https://i.stack.imgur.com/J8vKu.jpg" alt="Pie"></p>
<p>The image is from <a href="http://www.asp.net/web-pages/tutorials/data/7-displaying-data-in-a-chart" rel="nofollow noreferrer">this tutorial</a> for ChartHelper in MVC:</p>
<p>My code:</p>
<pre><code>var bytes = new Chart(600, 300).AddSeries(
chartType: "pie",
legend: "Sales in Store per Payment Collected",
xValue: viewModel.SalesInStorePerPaymentCollected.XValues,
yValues: viewModel.SalesInStorePerPaymentCollected.YValues
)
.GetBytes("png");
return File(bytes, "image/png");
</code></pre> | 8,403,930 | 3 | 1 | null | 2011-12-06 17:08:56.97 UTC | 2 | 2016-03-15 06:23:35.057 UTC | 2011-12-06 17:11:01.47 UTC | null | 383,710 | null | 463,469 | null | 1 | 3 | c#|asp.net-mvc|asp.net-mvc-3|mschart | 45,008 | <p>I did it by using the <code>System.Web.UI.DataVisualization.Charting.Chart</code> class.</p>
<p>Here is the code in my Controller:</p>
<pre><code>public ActionResult Chart()
{
Chart chart = new Chart();
chart.ChartAreas.Add(new ChartArea());
chart.Series.Add(new Series("Data"));
chart.Series["Data"].ChartType = SeriesChartType.Pie;
chart.Series["Data"]["PieLabelStyle"] = "Outside";
chart.Series["Data"]["PieLineColor"] = "Black";
chart.Series["Data"].Points.DataBindXY(
data.Select(data => data.Name.ToString()).ToArray(),
data.Select(data => data.Count).ToArray());
//Other chart formatting and data source omitted.
MemoryStream ms = new MemoryStream();
chart.SaveImage(ms, ChartImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
</code></pre>
<p>And the View:</p>
<pre><code><img alt="alternateText" src="@Url.Action("Chart")" />
</code></pre> |
8,763,869 | Append input text field with value of a div | <p>I'm trying to append an input text field and its value to be the value of a div.</p>
<p>Here is what I came up so far:</p>
<pre><code>$(this).append('<input type="text" value=' $('#div1').val() '>');
</code></pre> | 8,763,885 | 4 | 1 | null | 2012-01-06 20:13:28.517 UTC | 1 | 2019-08-06 05:16:48.073 UTC | null | null | null | null | 701,363 | null | 1 | 10 | jquery|append | 44,629 | <p>Don't use HTML strings for everything!</p>
<pre><code>$(this).append(
$('<input>', {
type: 'text',
val: $('#div1').text()
})
);
</code></pre> |
8,772,585 | spring bean with dynamic constructor value | <p>I need to create an Object which is in-complete without the constructor argument. Something like this</p>
<pre><code>Class A {
private final int timeOut
public A(int timeout)
{
this.timeOut = timeout;
}
//...
}
</code></pre>
<p>I would like this Bean to be spring managed, so that I can use Spring AOP later. </p>
<pre><code><bean id="myBean" class="A" singleton="false">
</bean>
</code></pre>
<p>However my bean needs timeout to be passed as a dynamic value - is there a way to create a spring managed bean with dynamic value being injedcted in the constructor?</p> | 8,773,187 | 3 | 1 | null | 2012-01-07 19:54:18.677 UTC | 11 | 2013-10-29 06:37:26.05 UTC | 2012-01-07 21:17:43.773 UTC | null | 21,234 | null | 61,395 | null | 1 | 17 | java|spring | 20,562 | <p><code>BeanFactory</code> has a <code>getBean(String name, Object... args)</code> method which, according to the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean%28java.lang.String,%20java.lang.Object...%29">javadoc</a>, allows you to specify constructor arguments which are used to override the bean definition's own arguments. So you could put a default value in the beans file, and then specify the "real" runtime values when required, e.g.</p>
<pre><code><bean id="myBean" class="A" scope="prototype">
<constructor-arg value="0"/> <!-- dummy value -->
</bean>
</code></pre>
<p>and then:</p>
<pre><code>getBean("myBean", myTimeoutValue);
</code></pre>
<p>I haven't tried this myself, but it should work.</p>
<p>P.S. <code>scope="prototype"</code> is now preferable to <code>singleton="false"</code>, which is deprecated syntax - it's more explicit, but does the same thing.</p> |
19,373,081 | How to use the Implements in Excel VBA | <p>I'm trying to implement some shapes for an engineering project and abstract it out for some common functions so that I can have a generalized program.</p>
<p>What I'm trying to do is have an interface called <code>cShape</code> and have <code>cRectangle</code> and <code>cCircle</code> implement <code>cShape</code></p>
<p>My code is below:</p>
<p><strong><code>cShape</code> interface</strong></p>
<pre><code>Option Explicit
Public Function getArea()
End Function
Public Function getInertiaX()
End Function
Public Function getInertiaY()
End Function
Public Function toString()
End Function
</code></pre>
<p><strong><code>cRectangle</code> class</strong></p>
<pre><code>Option Explicit
Implements cShape
Public myLength As Double ''going to treat length as d
Public myWidth As Double ''going to treat width as b
Public Function getArea()
getArea = myLength * myWidth
End Function
Public Function getInertiaX()
getInertiaX = (myWidth) * (myLength ^ 3)
End Function
Public Function getInertiaY()
getInertiaY = (myLength) * (myWidth ^ 3)
End Function
Public Function toString()
toString = "This is a " & myWidth & " by " & myLength & " rectangle."
End Function
</code></pre>
<p><strong><code>cCircle</code> class</strong></p>
<pre><code>Option Explicit
Implements cShape
Public myRadius As Double
Public Function getDiameter()
getDiameter = 2 * myRadius
End Function
Public Function getArea()
getArea = Application.WorksheetFunction.Pi() * (myRadius ^ 2)
End Function
''Inertia around the X axis
Public Function getInertiaX()
getInertiaX = Application.WorksheetFunction.Pi() / 4 * (myRadius ^ 4)
End Function
''Inertia around the Y axis
''Ix = Iy in a circle, technically should use same function
Public Function getInertiaY()
getInertiaY = Application.WorksheetFunction.Pi() / 4 * (myRadius ^ 4)
End Function
Public Function toString()
toString = "This is a radius " & myRadius & " circle."
End Function
</code></pre>
<p>The problem is that whenever I run my test cases, it comes up with the following error:</p>
<blockquote>
<p>Compile Error:</p>
</blockquote>
<blockquote>
<p>Object module needs to implement '~' for interface '~'</p>
</blockquote> | 19,379,641 | 6 | 1 | null | 2013-10-15 04:01:20.683 UTC | 72 | 2021-10-27 07:41:29.143 UTC | 2020-07-08 09:19:37.487 UTC | user2140173 | 11,636,588 | null | 174,634 | null | 1 | 67 | excel|vba|interface | 48,751 | <p>This is an esoteric OOP concept and there's a little more you need to do and understand to use a custom collection of shapes.</p>
<p>You may first want to go through <a href="https://stackoverflow.com/questions/19881863/vba-classes-interfaces-implements-and-adequate-comparison-methods/19908375#19908375"><strong><code>this answer</code></strong></a> to get a general understanding of classes and interfaces in VBA.</p>
<p><hr>
Follow the below instructions</p>
<p>First open Notepad and copy-paste the below code</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1
END
Attribute VB_Name = "ShapesCollection"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
Dim myCustomCollection As Collection
Private Sub Class_Initialize()
Set myCustomCollection = New Collection
End Sub
Public Sub Class_Terminate()
Set myCustomCollection = Nothing
End Sub
Public Sub Add(ByVal Item As Object)
myCustomCollection.Add Item
End Sub
Public Sub AddShapes(ParamArray arr() As Variant)
Dim v As Variant
For Each v In arr
myCustomCollection.Add v
Next
End Sub
Public Sub Remove(index As Variant)
myCustomCollection.Remove (index)
End Sub
Public Property Get Item(index As Long) As cShape
Set Item = myCustomCollection.Item(index)
End Property
Public Property Get Count() As Long
Count = myCustomCollection.Count
End Property
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
Set NewEnum = myCustomCollection.[_NewEnum]
End Property
</code></pre>
<p>Save the file as <em><code>ShapesCollection.cls</code></em> to your desktop.</p>
<blockquote>
<p><em>Make sure you are saving it with the</em> <em><code>*.cls</code> extension and not <code>ShapesCollection.cls.txt</code></em></p>
</blockquote>
<p>Now open you Excel file, go to VBE <kbd>ALT</kbd>+<kbd>F11</kbd> and right click in the <em><code>Project Explorer</code></em>. Select <em><code>Import File</code></em> from the drop-down menu and navigate to the file.</p>
<p><img src="https://i.stack.imgur.com/nkX6L.png" alt="enter image description here"></p>
<blockquote>
<p>NB: You needed to save the code in a <em><code>.cls</code></em> file first and then import it because VBEditor does not allow you to use Attributes. The attributes allow you to specify the default member in the iteration and use the for each loop on custom collection classes</p>
</blockquote>
<p>See more: </p>
<ul>
<li><a href="http://www.cpearson.com/excel/DefaultMember.aspx" rel="noreferrer">Chris Pearson: Default
Member</a> </li>
<li><p><a href="http://dailydoseofexcel.com/archives/2010/07/04/custom-collection-class/" rel="noreferrer">Daily Dose of Excel: Custom Collection
Class</a> </p></li>
<li><p><a href="http://www.excelforum.com/excel-programming-vba-macros/562915-solved-attribute-statements-of-vba-classes.html" rel="noreferrer">Excel Forum: Attribute Statements of VBA
Classes</a> </p></li>
<li><p><a href="http://www.pcreview.co.uk/forums/collections-vba-excel-and-probably-other-ms-office-2003-applications-t2293368.html" rel="noreferrer">PC-Review: VBA Excel
Collections</a></p></li>
</ul>
<p>Now Insert 3 class modules. Rename accordingly and copy-paste the code</p>
<p><strong>cShape</strong> <em>this is your Interface</em></p>
<pre><code>Public Function GetArea() As Double
End Function
Public Function GetInertiaX() As Double
End Function
Public Function GetInertiaY() As Double
End Function
Public Function ToString() As String
End Function
</code></pre>
<p><strong>cCircle</strong></p>
<pre><code>Option Explicit
Implements cShape
Public Radius As Double
Public Function GetDiameter() As Double
GetDiameter = 2 * Radius
End Function
Public Function GetArea() As Double
GetArea = Application.WorksheetFunction.Pi() * (Radius ^ 2)
End Function
''Inertia around the X axis
Public Function GetInertiaX() As Double
GetInertiaX = Application.WorksheetFunction.Pi() / 4 * (Radius ^ 4)
End Function
''Inertia around the Y axis
''Ix = Iy in a circle, technically should use same function
Public Function GetInertiaY() As Double
GetInertiaY = Application.WorksheetFunction.Pi() / 4 * (Radius ^ 4)
End Function
Public Function ToString() As String
ToString = "This is a radius " & Radius & " circle."
End Function
'interface functions
Private Function cShape_getArea() As Double
cShape_getArea = GetArea
End Function
Private Function cShape_getInertiaX() As Double
cShape_getInertiaX = GetInertiaX
End Function
Private Function cShape_getInertiaY() As Double
cShape_getInertiaY = GetInertiaY
End Function
Private Function cShape_toString() As String
cShape_toString = ToString
End Function
</code></pre>
<p><strong>cRectangle</strong></p>
<pre><code>Option Explicit
Implements cShape
Public Length As Double ''going to treat length as d
Public Width As Double ''going to treat width as b
Public Function GetArea() As Double
GetArea = Length * Width
End Function
Public Function GetInertiaX() As Double
GetInertiaX = (Width) * (Length ^ 3)
End Function
Public Function GetInertiaY() As Double
GetInertiaY = (Length) * (Width ^ 3)
End Function
Public Function ToString() As String
ToString = "This is a " & Width & " by " & Length & " rectangle."
End Function
' interface properties
Private Function cShape_getArea() As Double
cShape_getArea = GetArea
End Function
Private Function cShape_getInertiaX() As Double
cShape_getInertiaX = GetInertiaX
End Function
Private Function cShape_getInertiaY() As Double
cShape_getInertiaY = GetInertiaY
End Function
Private Function cShape_toString() As String
cShape_toString = ToString
End Function
</code></pre>
<p>You need to <em><code>Insert</code></em> a standard <em><code>Module</code></em> now and copy-paste the below code</p>
<p><strong>Module1</strong></p>
<pre><code>Option Explicit
Sub Main()
Dim shapes As ShapesCollection
Set shapes = New ShapesCollection
AddShapesTo shapes
Dim iShape As cShape
For Each iShape In shapes
'If TypeOf iShape Is cCircle Then
Debug.Print iShape.ToString, "Area: " & iShape.GetArea, "InertiaX: " & iShape.GetInertiaX, "InertiaY:" & iShape.GetInertiaY
'End If
Next
End Sub
Private Sub AddShapesTo(ByRef shapes As ShapesCollection)
Dim c1 As New cCircle
c1.Radius = 10.5
Dim c2 As New cCircle
c2.Radius = 78.265
Dim r1 As New cRectangle
r1.Length = 80.87
r1.Width = 20.6
Dim r2 As New cRectangle
r2.Length = 12.14
r2.Width = 40.74
shapes.AddShapes c1, c2, r1, r2
End Sub
</code></pre>
<p>Run the <strong><code>Main</code></strong> Sub and check out the results in the <em><code>Immediate Window</code></em> <kbd>CTRL</kbd>+<kbd>G</kbd></p>
<p><img src="https://i.stack.imgur.com/Ev3k1.png" alt="enter image description here"></p>
<hr>
<h1>Comments and explanation:</h1>
<p>In your <code>ShapesCollection</code> class module there are 2 subs for adding items to the collection. </p>
<p>The first method <code>Public Sub Add(ByVal Item As Object)</code> simply takes a class instance and adds it to the collection. You can use it in your <strong><code>Module1</code></strong> like this </p>
<pre><code>Dim c1 As New cCircle
shapes.Add c1
</code></pre>
<p>The <code>Public Sub AddShapes(ParamArray arr() As Variant)</code> allows you to add multiple objects at the same time separating them by a <code>,</code> comma in the same exact way as the <code>AddShapes()</code> Sub does. </p>
<p>It's quite a better design than adding each object separately, but it's up to you which one you are going to go for.</p>
<p>Notice how I have commented out some code in the loop</p>
<pre><code>Dim iShape As cShape
For Each iShape In shapes
'If TypeOf iShape Is cCircle Then
Debug.Print iShape.ToString, "Area: " & iShape.GetArea, "InertiaX: " & iShape.GetInertiaX, "InertiaY:" & iShape.GetInertiaY
'End If
Next
</code></pre>
<p>If you remove comments from the <code>'If</code> and <code>'End If</code> lines you will be able to print only the <code>cCircle</code> objects. This would be really useful if you could use delegates in VBA but you can't so I have shown you the other way to print only one type of objects. You can obviously modify the <code>If</code> statement to suit your needs or simply print out all objects. Again, it is up to you how you are going to handle your data :)</p> |
956,451 | TFS: Labels vs Changesets | <p>I am trying to come up with best practices regarding use of TFS source control. Right now, anytime we do a build, we label the files that are checked into the TFS with the version number. Is this approach better or worse than simply checking the files in and having the version number in the comments?
Can you then use the changeset to go back if necessary or the labels are still more versatile?</p>
<p>Thanks!</p> | 956,524 | 4 | 0 | null | 2009-06-05 15:21:36.473 UTC | 12 | 2017-08-04 11:21:00.793 UTC | null | null | null | null | 29,726 | null | 1 | 34 | tfs|label|changeset | 46,548 | <p>They have two different purposes, ChangeSets are when the files have actually changed and you wish to keep a permanent record of that change. Labels mark a certain version of the files so that you can easily go back to that point. Unless your build actually changes files under source control and you wish to record these changes. You should be labeling.</p>
<p>Also, labeling is much less resource intensive. And you can have multiple labels on the same version of a file.</p> |
1,005,479 | View classes dependency graph plugin? | <p>Is there any plugins I can use for Eclipse that will show graphical view of classes dependencies? </p> | 1,005,592 | 4 | 2 | null | 2009-06-17 06:59:25.45 UTC | 9 | 2016-05-12 17:42:55.107 UTC | 2016-05-12 17:42:55.107 UTC | null | 452,775 | null | 108,869 | null | 1 | 37 | java|eclipse|eclipse-plugin|eclipse-rcp|eclipse-3.4 | 37,251 | <p><strong><a href="http://classycleplugin.graf-tec.ch/index.html" rel="nofollow noreferrer">Classycle</a></strong> can be a good start (for static dependencies between classes at least)</p>
<p>(I find their graph a bit complicated to follow though : <a href="https://stackoverflow.com/questions/62276/java-package-cycle-detection-how-to-find-the-specific-classes-involved/71610#71610">CDA - Class Dependency Analyzer</a> is an external tool, but produce much more readable dependency graphs)</p> |
493,376 | Why does WCF return myObject[] instead of List<T> like I was expecting? | <p>I am returning a List from my WCF method. In my client code, it's return type shows as MyObject[]. I have to either use MyObject[], or IList, or IEnumerable... </p>
<pre><code>WCFClient myClient = new WCFClient();
MyObject[] list = myClient.GetMyStuff();
or
IList<MyObject> list = myClient.GetMyStuff();
or
IEnumerable<MyObject> list = myClient.GetMyStuff();
</code></pre>
<p>All I am doing is taking this collection and binding it to a grid. What is the best object to assign my returned collection?</p> | 493,405 | 4 | 0 | null | 2009-01-29 20:56:03.247 UTC | 19 | 2016-09-29 10:40:57.82 UTC | 2010-09-19 07:50:58.403 UTC | null | 57,787 | Scott | 3,047 | null | 1 | 63 | c#|wcf|collections | 30,247 | <p>You can specify that you want to use a generic list instead of an array by clicking the advanced button when you add a reference, or you can right click on the service reference and choose configure to change it in place.</p>
<p>The reason is that WCF serializes Generic lists as arrays to send across the wire. The configuration is just telling svcutil to create a proxy that converts them back to a generic list for your convenience.</p> |
924,551 | Difference between XPath, XQuery and XPointer | <p>What is the difference between <code>XPath</code>, <code>XQuery</code> and <code>XPointer</code>? As far as I know, <code>XQuery</code> is an extended version of <code>XPath</code>. I have some basic knowledge of <code>XPath</code>. Is there any feature available in <code>XPath</code> which is not in <code>XQuery</code>? Yesterday, I heard a new word, <code>XPointer</code>. I am confused. Which language is used for which purpose?</p> | 924,594 | 4 | 0 | null | 2009-05-29 05:42:22.29 UTC | 18 | 2016-07-08 06:06:58.873 UTC | 2016-07-07 20:11:42.653 UTC | null | 659,732 | null | 112,500 | null | 1 | 68 | xml|xpath|xquery | 44,913 | <p>Wikipedia is a good place to start for questions like this. Generally, <a href="http://en.wikipedia.org/wiki/XPath" rel="noreferrer">XPath</a> is a language used to succinctly pinpoint exact XML nodes in a DOM. <a href="http://en.wikipedia.org/wiki/XQuery" rel="noreferrer">XQuery</a> is a superset of XPath that also provides <a href="http://en.wikipedia.org/wiki/FLWOR" rel="noreferrer">FLWOR</a> syntax, which is SQL-like. Finally, <a href="http://en.wikipedia.org/wiki/Xpointer" rel="noreferrer">XPointer</a> includes XPath, but also provides a simpler position-based addressing scheme. </p>
<p>Of course, you can always read the W3C specs for full details.</p> |
4,101,863 | SQL Server - current user name | <p>Which one should I use to record update made by users?</p>
<ol>
<li><code>SYSTEM_USER</code>, or</li>
<li><code>ORIGINAL_LOGIN()</code>, or</li>
<li><code>SUSER_SNAME()</code></li>
</ol> | 4,102,013 | 1 | 0 | null | 2010-11-04 22:08:53.74 UTC | 17 | 2015-07-27 15:22:27.403 UTC | 2015-07-27 15:22:27.403 UTC | null | 74,757 | null | 85,952 | null | 1 | 62 | sql-server|tsql | 73,421 | <p><code>SYSTEM_USER</code> returns the current executing context, so this can return an impersonated context</p>
<p><code>ORIGINAL_LOGIN()</code> returns the identity of the user that initially connected to the instance, so regardless whether the context is impersonated or not it will yield the original user that logged in, good for auditing.</p>
<p><code>SUSER_SNAME()</code> this is used if you want to get the username by SID so <code>SUSER_SNAME</code> can be invoked with a parameter like such <code>SUSER_SNAME([server_user_sid])</code> but the SID is optional if you don’t pass that parameter the current user is returned.</p> |
34,727,989 | Why doesn't std::bitset come with iterators? | <p>It appears that <a href="http://en.cppreference.com/w/cpp/utility/bitset">std::bitset</a> does not come with STL iterators.<br>
Therefore, I cannot do the following: </p>
<pre><code>std::bitset<8> bs;
for (auto it: bs) {
std::cout << "this can not be done out of the box\n";
}
</code></pre>
<p>Instead I must: </p>
<pre><code>std::bitset<8> bs;
for (std::size_t i = 0; i < bs.size(); ++i) {
std::cout << bs[i] << '\n';
}
</code></pre>
<p>Without iterators, I also can't use bitsets with any of the STL algorithms.<br>
Why did the committee decide to exclude iterators from bitset? </p> | 34,728,458 | 2 | 3 | null | 2016-01-11 17:53:48.527 UTC | 3 | 2019-01-24 08:15:24.18 UTC | null | null | null | null | 908,939 | null | 1 | 37 | c++|stl|iterator|bitset|std-bitset | 12,958 | <p>I don't think there was ever an actual decision to exclude iterators from bitset.</p>
<p>Rather, bitset is one of the classes that predates the proposal to add the original Standard Template Library to the C++ standard. When it was designed, essentially <em>none</em> of the standard library included iterators.</p>
<p>Then, Stepanov's library was proposed for addition, and quite a bit of it was accepted. In response to that, additions were made to some existing classes (e.g., <code>std::string</code>) to allow them to be used like the new container classes.</p>
<p>This was all happening quite late in the standards process though--in fact, they already bent the rules in a few places to add what they did. Among other things, just about the same time as the containers/iterators/algorithms were added to the library, the committee voted to consider the standard "feature complete", so from that point onward they'd only work on fixing bugs and such, not adding new features.</p>
<p>As such, even if a proposal had been written to add an iterator interface to <code>bitset</code>, about the only way the committee could have accepted it would have been to treat this as a bug being fixed rather than a new feature being added. If there'd been a really solid proposal, I suppose they <em>could</em> have done that, but I don't think there was such a proposal, and it would have been stretching the point quite a bit, so even a really good proposal might easily have been rejected.</p>
<p>Since then, there was one proposal, <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1112" rel="noreferrer">LEWG 1112</a>, that would have added an iterator interface to <code>std::bitset</code>. This was proposed for C++11, and was proposed specifically to support the range-based <code>for</code> loop that was also being added in C++11. It suffered a rather ignominious fate: it was originally accepted, and wording was drafted. Then it looked like the proposal for adding Concepts to the language would be accepted, so this wording was rewritten to use the shiny, wonderful new concepts. Sometime later, concepts were removed from the language, and rather than rewording the proposal so it no longer depended on concepts, they tentatively marked it as "NAD Future", which means they treated it as not being a defect, and deferred any further work until some (indefinite) time in the future (and as far as I can see, haven't revisited it since).</p> |
31,424,561 | Wait until all promises complete even if some rejected | <p>Let's say I have a set of <code>Promise</code>s that are making network requests, of which one will fail:</p>
<pre><code>// http://does-not-exist will throw a TypeError
var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]
Promise.all(arr)
.then(res => console.log('success', res))
.catch(err => console.log('error', err)) // This is executed
</code></pre>
<p>Let's say I want to wait until all of these have finished, regardless of if one has failed. There might be a network error for a resource that I can live without, but which if I can get, I want before I proceed. I want to handle network failures gracefully.</p>
<p>Since <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all" rel="noreferrer"><code>Promise.all</code></a> doesn't leave any room for this, what is the recommended pattern for handling this, without using a promises library?</p> | 31,524,969 | 20 | 9 | null | 2015-07-15 07:53:55.82 UTC | 161 | 2022-01-18 09:34:47.077 UTC | 2021-05-06 10:01:46.42 UTC | null | 227,613 | null | 1,751,810 | null | 1 | 543 | javascript|promise|es6-promise | 248,846 | <p>Benjamin's answer offers a great abstraction for solving this issue, but I was hoping for a less abstracted solution. The explicit way to to resolve this issue is to simply call <code>.catch</code> on the internal promises, and return the error from their callback.</p>
<pre><code>let a = new Promise((res, rej) => res('Resolved!')),
b = new Promise((res, rej) => rej('Rejected!')),
c = a.catch(e => { console.log('"a" failed.'); return e; }),
d = b.catch(e => { console.log('"b" failed.'); return e; });
Promise.all([c, d])
.then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
.catch(err => console.log('Catch', err));
Promise.all([a.catch(e => e), b.catch(e => e)])
.then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
.catch(err => console.log('Catch', err));
</code></pre>
<hr>
<p>Taking this one step further, you could write a generic catch handler that looks like this:</p>
<pre><code>const catchHandler = error => ({ payload: error, resolved: false });
</code></pre>
<p>then you can do</p>
<pre><code>> Promise.all([a, b].map(promise => promise.catch(catchHandler))
.then(results => console.log(results))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!', { payload: Promise, resolved: false } ]
</code></pre>
<p>The problem with this is that the caught values will have a different interface than the non-caught values, so to clean this up you might do something like:</p>
<pre><code>const successHandler = result => ({ payload: result, resolved: true });
</code></pre>
<p>So now you can do this:</p>
<pre><code>> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
.then(results => console.log(results.filter(result => result.resolved))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]
</code></pre>
<p>Then to keep it DRY, you get to Benjamin's answer:</p>
<pre><code>const reflect = promise => promise
.then(successHandler)
.catch(catchHander)
</code></pre>
<p>where it now looks like</p>
<pre><code>> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
.then(results => console.log(results.filter(result => result.resolved))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]
</code></pre>
<hr>
<p>The benefits of the second solution are that its abstracted and DRY. The downside is you have more code, and you have to remember to reflect all your promises to make things consistent.</p>
<p>I would characterize my solution as explicit and KISS, but indeed less robust. The interface doesn't guarantee that you know exactly whether the promise succeeded or failed.</p>
<p>For example you might have this:</p>
<pre><code>const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));
</code></pre>
<p>This won't get caught by <code>a.catch</code>, so</p>
<pre><code>> Promise.all([a, b].map(promise => promise.catch(e => e))
.then(results => console.log(results))
< [ Error, Error ]
</code></pre>
<p>There's no way to tell which one was fatal and which was wasn't. If that's important then you're going to want to enforce and interface that tracks whether it was successful or not (which <code>reflect</code> does).</p>
<p>If you just want to handle errors gracefully, then you can just treat errors as undefined values:</p>
<pre><code>> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
.then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]
</code></pre>
<p>In my case, I don't need to know the error or how it failed--I just care whether I have the value or not. I'll let the function that generates the promise worry about logging the specific error.</p>
<pre><code>const apiMethod = () => fetch()
.catch(error => {
console.log(error.message);
throw error;
});
</code></pre>
<p>That way, the rest of the application can ignore its error if it wants, and treat it as an undefined value if it wants.</p>
<p>I want my high level functions to fail safely and not worry about the details on why its dependencies failed, and I also prefer KISS to DRY when I have to make that tradeoff--which is ultimately why I opted to not use <code>reflect</code>.</p> |
26,863,407 | AspectJ Maven Plugin cannot compile my project | <p>I try to use aspectj maven plugin for compile project with aspectj compiler and then I try to package classes into "war" file. Unfortunately, it doesn't work with following configuration (pom.xml):</p>
<pre><code><build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>com.liferay.maven.plugins</groupId>
<artifactId>liferay-maven-plugin</artifactId>
<version>${liferay.maven.plugin.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
</execution>
</executions>
<configuration>
<autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
<appServerDeployDir>${liferay.app.server.deploy.dir}</appServerDeployDir>
<appServerLibGlobalDir>${liferay.app.server.lib.global.dir}</appServerLibGlobalDir>
<appServerPortalDir>${liferay.app.server.portal.dir}</appServerPortalDir>
<liferayVersion>${liferay.version}</liferayVersion>
<pluginType>portlet</pluginType>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.7</source>
<target>1.7</target>
<showWarnings>true</showWarnings>
<failOnError>true</failOnError>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilationLevel>1.7</compilationLevel>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
<type>jar</type>
</dependency>
</code></pre>
<p>After <code>mvn clean install</code> I see following exceptions:</p>
<pre><code>[INFO] --- aspectj-maven-plugin:1.7:compile (default) @ tvbs-portlet ---
[INFO] Showing AJC message detail for messages of types: [error, warning, fail]
[ERROR] Missing message: configure.incompatibleComplianceForSource in: org.aspectj.ajdt.ajc.messages
<unknown source file>:<no line information>
[ERROR] no sources specified
<unknown source file>:<no line information>
[ERROR] AspectJ Compiler 1.8.2
Usage: <options> <source file | @argfile>..
AspectJ-specific options:
-inpath <list> use classes in dirs and jars/zips in <list> as source
</code></pre>
<p>Could anybody suggest me some solution?</p> | 26,866,775 | 5 | 1 | null | 2014-11-11 11:05:41.01 UTC | 1 | 2020-09-15 08:43:35.03 UTC | 2020-09-15 08:43:35.03 UTC | null | 1,082,681 | null | 980,776 | null | 1 | 21 | java|maven|jakarta-ee|aspectj|aspectj-maven-plugin | 51,304 | <p><strong>Update:</strong> While the things I said about AspectJ Maven configuration in this answer are all correct, the root cause of the concrete problem at hand - bad Maven dependency management - is described in my <a href="https://stackoverflow.com/a/26887224/1082681">other answer</a>. It would be better if that one was the accepted answer and not this one.</p>
<hr>
<ul>
<li>User codelion's hint makes sense, please change your <code><compilationLevel></code> tag (typo?) - to <code><complianceLevel></code>.</li>
<li>There is no need to downgrade to plugin version 1.6, you can keep 1.7.</li>
<li>There is also no need to specify the configuration again within the <code><execution></code> section, the one at plugin level is enough.</li>
<li>Please note that the default AspectJ version in plugin 1.7 is 1.8.2, so maybe your runtime dependency on 1.7.4 works, but if I were you I would upgrade that one too, optimally in sync with the plugin version. It is no hard requirement, but I think it makes sense.</li>
<li>Maybe you even want to upgrade to the current version AspectJ 1.8.4, in the plugin as well as the runtime. This can also be achieved by adding a dependency to the desired <em>aspectjtools</em> version to the plugin configuration:</li>
</ul>
<pre class="lang-xml prettyprint-override"><code> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.source-target.version>1.8</java.source-target.version>
<aspectj.version>1.8.4</aspectj.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<showWeaveInfo>true</showWeaveInfo>
<source>${java.source-target.version}</source>
<target>${java.source-target.version}</target>
<Xlint>ignore</Xlint>
<complianceLevel>${java.source-target.version}</complianceLevel>
<encoding>UTF-8</encoding>
<verbose>true</verbose>
</configuration>
<executions>
<execution>
<!-- IMPORTANT -->
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
</dependencies>
</code></pre> |
57,326,789 | How to save enum field in the database room? | <p>I must write the value from the <code>enum</code> enumeration to the database. An error occurs during compilation. What am I doing wrong?</p>
<blockquote>
<p>Cannot figure out how to save this field into database. You can consider adding a type converter for it.</p>
</blockquote>
<pre><code>@ColumnInfo(name = "state_of_health")
@TypeConverters(HealthConverter::class)
var health: Health
enum class Health(val value: Int){
NONE(-1),
VERY_BAD(0),
...
}
class HealthConverter{
@TypeConverter
fun fromHealth(value: Health): Int{
return value.ordinal
}
@TypeConverter
fun toHealth(value: Int): Health{
return when(value){
-1 -> Health.NONE
0 -> Health.VERY_BAD
...
else -> Health.EXCELLENT
}
}
}
</code></pre> | 60,079,133 | 6 | 2 | null | 2019-08-02 12:46:51.973 UTC | 8 | 2021-05-15 11:57:03.94 UTC | null | null | null | null | 5,894,542 | null | 1 | 46 | android|kotlin|enums|android-room|converters | 24,837 | <p>You can make a convert to each enum, like this:</p>
<pre><code>class Converters {
@TypeConverter
fun toHealth(value: String) = enumValueOf<Health>(value)
@TypeConverter
fun fromHealth(value: Health) = value.name
}
</code></pre>
<p>Or if you prefer store it as SQL <code>integer</code>, you can use ordinal too:</p>
<pre><code>class Converters {
@TypeConverter
fun toHealth(value: Int) = enumValues<Health>()[value]
@TypeConverter
fun fromHealth(value: Health) = value.ordinal
}
</code></pre>
<p>Unfortunatally, there is no way to use generics <code>Enum<T></code> to accomplish this since unbound generics will raise an error <code>Cannot use unbound generics in Type Converters</code>.</p>
<p>Android Room team could seriously add an annotation and a generator for Enums to their kapt compiler.</p>
<p>Finally, annotate a database class, entity class, dao class, dao method, dao method parameter or entity field class with this:</p>
<pre><code>@TypeConverters(Converters::class)
</code></pre> |
7,389,687 | Operand type clash: uniqueidentifier is incompatible with int | <p>When I attempt to create the stored procedure below I get the following error:</p>
<blockquote>
<p>Operand type clash: uniqueidentifier is incompatible with int</p>
</blockquote>
<p>It's not clear to me what is causing this error. UserID is in fact an int in all of my tables. Can someone tell me what I've done wrong?</p>
<pre><code>create procedure dbo.DeleteUser(@UserID int)
as
delete from [aspnet_Membership] where UserId = @UserID
delete from [Subscription] where UserID = @UserID
delete from [Address] where UserID = @UserID
delete from [User] where UserID = @UserID
go
</code></pre> | 7,389,771 | 3 | 1 | null | 2011-09-12 14:45:36.35 UTC | 5 | 2019-10-18 02:23:10.263 UTC | 2011-09-12 14:54:46.697 UTC | null | 41,956 | null | 549,273 | null | 1 | 27 | sql|sql-server|tsql|asp.net-membership | 160,718 | <p>Sounds to me like at least one of those tables has defined <code>UserID</code> as a <code>uniqueidentifier</code>, not an <code>int</code>. Did you check the data in each table? What does <code>SELECT TOP 1 UserID FROM</code> each table yield? An <code>int</code> or a <code>GUID</code>?</p>
<p><strong>EDIT</strong></p>
<p>I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the <code>aspnet_Membership</code> table in your script, since it's not really one of "your" tables.</p>
<p>If you meant to design your tables around the <code>aspnet_Membership</code> database, then why are the rest of the columns <code>int</code> when that table clearly uses a <code>uniqueidentifier</code> for the <code>UserID</code> column?</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.