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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21,100,391 | C++ Error: Expected a type specifier | <p>When I try to use a <code>LoggerStream</code> like this, I get 'expected a type specifier':</p>
<p><code>const LoggerStream logger(L"Test Component");</code></p>
<p>Here's where I'm trying to use the <code>LoggerStream</code>:</p>
<pre><code>#include "Logger.h"
#include "TestComponent.h"
namespace ophRuntime {
struct TestComponent::TestComponentImpl {
private:
LoggerStream logger(L"Test Component");
NO_COPY_OR_ASSIGN(TestComponentImpl);
};
TestComponent::TestComponent() : impl(new TestComponentImpl()) {
}
bool TestComponent::Init() {
}
}
</code></pre> | 21,101,550 | 4 | 3 | null | 2014-01-13 20:06:57.09 UTC | 5 | 2014-01-13 21:28:56.11 UTC | 2014-01-13 21:28:56.11 UTC | null | 158,109 | null | 158,109 | null | 1 | 11 | c++ | 66,457 | <p>You can't construct class members like this:-</p>
<pre><code> struct TestComponent::TestComponentImpl
{
private:
LoggerStream logger(L"Test Component");
</code></pre>
<p>Instead, use an initialization list in the constuctor, like this:</p>
<pre><code>struct TestComponent::TestComponentImpl
{
LoggerStream logger;
TestComponent::TestComponent() : impl(new TestComponentImpl()),
logger("L"Test Component")
{
}
...
}
</code></pre>
<p>And I think you've fallen foul of the <a href="http://en.wikipedia.org/wiki/Most_vexing_parse">"Most Vexing Parse"</a> because the compiler thinks <code>logger</code> must be a function, and it's complaining that <code>L"Test Component"</code> is not a type specifier for a parameter.</p> |
18,575,722 | leaflet.js - Set marker on click, update position on drag | <p>for a small project I am working on, I need to be able to place a marker on a leaflet.js powered image-map and update the position of this marker, if it gets dragged. I use the following code to try this, but it fails.
I get the error 'marker not defined'. I don't know why it's not working - maybe you guys could help me out? ;)</p>
<pre><code>function onMapClick(e) {
gib_uni();
marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'};
map.addLayer(marker);
};
marker.on('dragend', function(event){
var marker = event.target;
var position = marker.getLatLng();
alert(position);
marker.setLatLng([position],{id:uni,draggable:'true'}).bindPopup(position).update();
});
</code></pre> | 18,601,489 | 1 | 0 | null | 2013-09-02 14:40:27.003 UTC | 9 | 2017-08-02 15:35:57.87 UTC | 2017-08-02 15:35:57.87 UTC | null | 1,033,581 | null | 2,323,597 | null | 1 | 15 | javascript|jquery|maps|marker|leaflet | 34,802 | <p>In the code snippet above, marker is not defined at the time the event handler is added. Try the following where the dragend listener is added immediately following the creation of the Marker:</p>
<pre><code>function onMapClick(e) {
gib_uni();
marker = new L.marker(e.latlng, {id:uni, icon:redIcon, draggable:'true'});
marker.on('dragend', function(event){
var marker = event.target;
var position = marker.getLatLng();
console.log(position);
marker.setLatLng(position,{id:uni,draggable:'true'}).bindPopup(position).update();
});
map.addLayer(marker);
};
</code></pre>
<p>You were also missing a bracket at the end of your new L.Marker() line.</p>
<p>You also put <code>position</code> into an array in the call to <code>setLatLng</code> but it is already a <code>LatLng</code> object.</p> |
18,726,419 | How to open a magnific popup on page load? | <p>I'm using <a href="http://dimsemenov.com/plugins/magnific-popup/" rel="noreferrer">Magnific Popup</a> and I would like to have a video come up as soon as the page loads in a popup.</p>
<p>I got the plugin to work fine, but I have no idea on how to get it to pop up as soon as the page loads, without clicking on the thumbnail. </p>
<p>I looked around for a solution, but I did not manage to get it to work.</p> | 18,726,588 | 2 | 0 | null | 2013-09-10 18:33:24.99 UTC | 4 | 2017-07-04 11:19:39.203 UTC | 2017-07-04 11:19:39.203 UTC | null | 6,008,139 | null | 2,758,089 | null | 1 | 17 | javascript|jquery|html|magnific-popup | 45,315 | <p>If you're using jQuery you could just listen for the window load event and then call the open method for your Magnific Popup like so:</p>
<pre><code>(function($) {
$(window).load(function () {
// retrieved this line of code from http://dimsemenov.com/plugins/magnific-popup/documentation.html#api
$.magnificPopup.open({
items: {
src: 'someimage.jpg'
},
type: 'image'
// You may add options here, they're exactly the same as for $.fn.magnificPopup call
// Note that some settings that rely on click event (like disableOn or midClick) will not work here
}, 0);
});
})(jQuery);
</code></pre> |
1,587,028 | Android - configure Spinner to use array | <p>I declare my Spinner in the following manner (it's very static so I
have 2 string arrays in <code>array.xml</code> for titles and values)</p>
<pre><code><Spinner
android:id="@+id/searchCriteria"
android:entries="@array/searchBy"
android:entryValues="@array/searchByValues" />
</code></pre>
<p>I expect <code>spinner.getSelectedItem()</code> to return an array <code>[title, value]</code>
but in fact it returns just a title String. Is it ignoring
<code>android:entryValues</code>? How do I get a value, not a title from it? Is
this doable with XML only or do I need to create adapter and do it
programmatically? </p> | 4,059,553 | 3 | 1 | null | 2009-10-19 04:55:04.453 UTC | 31 | 2019-07-24 12:20:23.123 UTC | 2019-07-24 12:20:23.123 UTC | null | 1,000,551 | null | 135,946 | null | 1 | 49 | android|arrays|spinner|android-spinner | 81,543 | <p>Rather than the dual array method, why not fill your ArrayAdapter programmatically with objects of a known type and use that. I've written a tutorial of a similar nature (link at the bottom) that does this. The basic premise is to create an array of Java objects, tell the spinner about the, and then use those objects directly from the spinner class. In my example I have an object representing a "State" which is defined as follows:</p>
<pre><code>package com.katr.spinnerdemo;
public class State {
// Okay, full acknowledgment that public members are not a good idea, however
// this is a Spinner demo not an exercise in java best practices.
public int id = 0;
public String name = "";
public String abbrev = "";
// A simple constructor for populating our member variables for this tutorial.
public State( int _id, String _name, String _abbrev )
{
id = _id;
name = _name;
abbrev = _abbrev;
}
// The toString method is extremely important to making this class work with a Spinner
// (or ListView) object because this is the method called when it is trying to represent
// this object within the control. If you do not have a toString() method, you WILL
// get an exception.
public String toString()
{
return( name + " (" + abbrev + ")" );
}
}
</code></pre>
<p>Then you can populate a spinner with an array of these classes as follows:</p>
<pre><code> // Step 1: Locate our spinner control and save it to the class for convenience
// You could get it every time, I'm just being lazy... :-)
spinner = (Spinner)this.findViewById(R.id.Spinner01);
// Step 2: Create and fill an ArrayAdapter with a bunch of "State" objects
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new State[] {
new State( 1, "Minnesota", "MN" ),
new State( 99, "Wisconsin", "WI" ),
new State( 53, "Utah", "UT" ),
new State( 153, "Texas", "TX" )
});
// Step 3: Tell the spinner about our adapter
spinner.setAdapter(spinnerArrayAdapter);
</code></pre>
<p>You can retrieve the selected item as follows:</p>
<pre><code>State st = (State)spinner.getSelectedItem();
</code></pre>
<p>And now you have a bona fide Java class to work with. If you want to intercept when the spinner value changes, just implement the OnItemSelectedListener and add the appropriate methods to handle the events.</p>
<pre><code>public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// Get the currently selected State object from the spinner
State st = (State)spinner.getSelectedItem();
// Now do something with it.
}
public void onNothingSelected(AdapterView<?> parent )
{
}
</code></pre>
<p>You can find the whole tutorial here:
<a href="http://www.katr.com/article_android_spinner01.php" rel="noreferrer">http://www.katr.com/article_android_spinner01.php</a></p> |
8,447,384 | How to order child collections of entities in EF | <p>I have the following query:</p>
<pre><code>public IEnumerable<Team> GetAllTeamsWithMembers(int ownerUserId)
{
return _ctx.Teams
.Include(x => x.TeamMembers)
.Where(x => x.UserId == ownerUserId)
.OrderBy(x => x.Name).ToList();
}
</code></pre>
<p>How do I go about ordering the teams by their name, and then have all the child members of each team sorted by their name?</p>
<p>It seems that do this I need to create a new DTO class and use a select. I'd like to use the EF entities already created, in this case Team has a navigation property to Members. I return <code>IEnumerable<Team></code> out from my repository layer. </p>
<p>There doesn't seem to be a neat way of ordering child collections in EF. Can anyone help?</p> | 8,447,471 | 4 | 1 | null | 2011-12-09 15:01:46.13 UTC | 6 | 2021-02-12 17:27:10.817 UTC | null | null | null | null | 306,098 | null | 1 | 34 | linq|entity-framework | 33,987 | <p>You could load the data and sort in memory after loading it.</p>
<pre><code>IEnumerable<Team> teams = _ctx.Teams
.Include(x => x.TeamMembers)
.Include(x => x.TeamMembers.Select(u => u.User))
.Where(x => x.UserId == ownerUserId)
.OrderBy(x => x.Name).ToList();
foreach (var team in teams)
{
team.TeamMembers = team.TeamMembers.OrderBy(m => m.Name);
foreach (var teamMember in team.TeamMembers)
{
teamMember.Users = teamMember.Users.OrderBy(u => u.Name);
}
}
</code></pre>
<p>Or you could use Projections and use the Change Tracking of EF to sort your collection. <a href="http://thedatafarm.com/blog/data-access/use-projections-and-a-repository-to-fake-a-filtered-eager-load/">Here is an example</a> of filtering an Include but the same works for Ordering.</p> |
8,516,116 | Change Layout(Master Page) of view in ASP.NET MVC without recreate it | <p>I'm using ASP.NET MVC 3 with Razor views. When you want to create a view you can choose a layout (master page) for your view, or leave it to choose Default (_Layout).</p>
<p>I am interesting in to change this layout after create a view without recreate it, is there any where to store the layout information about the views? and how can I change it?</p> | 8,516,258 | 4 | 1 | null | 2011-12-15 06:45:19.94 UTC | 11 | 2015-08-12 16:12:57.683 UTC | 2012-02-14 05:53:43.407 UTC | null | 867,232 | null | 1,020,476 | null | 1 | 50 | c#|asp.net|.net|asp.net-mvc|asp.net-mvc-3 | 97,843 | <p>In MVC3 you have <code>_ViewStart.cshtml</code> that stores all pages' Layout; you can change this element to change all pages' Layout or you can add new Layout element in top of target view pages in <code>@{}</code> block like the following to change the layout of the specific page:</p>
<pre><code>@{
Layout = "~/Views/Shared/_newLayout.cshtml";
ViewBag.Title = "Index";
}
</code></pre> |
27,107,072 | Adding null values to arraylist | <p>Can I add <code>null</code> values to an <code>ArrayList</code> even if it has a generic type parameter?</p>
<p>Eg.</p>
<pre><code>ArrayList<Item> itemList = new ArrayList<Item>();
itemList.add(null);
</code></pre>
<p>If so, will</p>
<pre><code>itemsList.size();
</code></pre>
<p>return 1 or 0?</p>
<p>If I can add <code>null</code> values to an <code>ArrayList</code>, can I loop through only the indexes that contain items like this?</p>
<pre><code>for(Item i : itemList) {
//code here
}
</code></pre>
<p>Or would the for each loop also loop through the null values in the list?</p> | 27,107,189 | 3 | 3 | null | 2014-11-24 14:26:35.84 UTC | 13 | 2021-06-25 13:36:16.61 UTC | 2014-11-24 19:30:41.54 UTC | null | 1,221,571 | null | 4,285,091 | null | 1 | 64 | java|arraylist | 194,713 | <p>Yes, you can always use <code>null</code> instead of an object. Just be careful because some methods might throw error.</p>
<p>It would be 1.</p>
<p>Also <code>null</code>s would be factored in in the for loop, but you could use</p>
<pre><code>for (Item i : itemList) {
if (i != null) {
//code here
}
}
</code></pre> |
1,277,126 | Plot Graphs in Java | <p>The Java Swing GUI that I'm developing needs to plot a 2D graph based on the x and y coordinates generated in the program.</p>
<p>Is there a Swing component for that?</p>
<p>Or is there any other open source package for the purpose?</p> | 1,277,144 | 4 | 0 | null | 2009-08-14 10:22:46.94 UTC | 6 | 2018-03-08 11:25:04.687 UTC | 2018-03-08 11:25:04.687 UTC | null | 6,770,384 | null | 155,658 | null | 1 | 18 | java|user-interface|swing|graph|plot | 66,249 | <p>You should check out <a href="http://www.jfree.org/jfreechart/" rel="noreferrer">JFreeChart</a> which has Swing support. Here are some samples:</p>
<p><a href="http://www.jfree.org/jfreechart/samples.html" rel="noreferrer">http://www.jfree.org/jfreechart/samples.html</a></p> |
224,765 | Splitting WPF interface across multiple Xaml files | <p>I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across several files.</p>
<p>I would like to be able to set the content of an element such as a ComboBox to an element that is defined in a different xaml file (but in the same VS project).</p>
<p>thanks</p> | 224,816 | 4 | 0 | null | 2008-10-22 07:38:55.337 UTC | 8 | 2016-10-17 06:11:51.553 UTC | null | null | null | Dave Turvey | 18,966 | null | 1 | 57 | wpf|xaml | 31,725 | <p>You can split a large user interface by defining UserControls.</p>
<p>Right-click on the solution tree, choose Add->New Item... then User Control. You can design this in the normal way.</p>
<p>You can then reference your usercontrol in XAML using a namespace declaration. Let's say you want to include your UserControl in a Window. In the following example I've added a UserControl named "Foo" to the namespace "YourCompany.Controls":</p>
<pre><code><Window x:Class="YourCompany.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:YourCompany.Controls">
<Controls:Foo ... />
</code></pre>
<p>For your specific example, you would make use of your usercontrol in a combobox by defining a DataTemplate that displayed the data within your usercontrol.</p> |
56,833,469 | Typescript error: TS7053 Element implicitly has an 'any' type | <p>this is part of my code:</p>
<pre class="lang-js prettyprint-override"><code>const myObj: object = {}
const propname = 'propname'
myObj[propname] = 'string'
</code></pre>
<p>but I got error:</p>
<pre class="lang-sh prettyprint-override"><code>ERROR in path/to/file.ts(4,1)
TS7053: Element implicitly has an 'any' type because expression of type '"propname"' can't be used to index type '{}'.
Property 'propname' does not exist on type '{}'.
</code></pre>
<p>What is wrong here, and how can I fix it?</p> | 56,833,507 | 6 | 1 | null | 2019-07-01 09:49:53.103 UTC | 19 | 2022-07-14 14:20:37.453 UTC | null | null | null | null | 1,842,159 | null | 1 | 125 | typescript | 79,482 | <p>You have to define what kind of index type the object has. In your case it is a <code>string</code> based index.</p>
<pre><code>const myObj: {[index: string]:any} = {}
</code></pre> |
56,718,552 | Disable gesture to pull down form/page sheet modal presentation | <p>In iOS 13 modal presentations using the form and page sheet style can be dismissed with a pan down gesture. This is problematic in one of my form sheets because the user draws into this box which interferes with the gesture. It pulls the screen down instead of drawing a vertical line.</p>
<p>How can you disable the vertical swipe to dismiss gesture in a modal view controller presented as a sheet?</p>
<p>Setting <code>isModalInPresentation = true</code> still allows the sheet to be pulled down, it just won't dismiss.</p> | 57,635,168 | 16 | 2 | null | 2019-06-22 19:36:59.953 UTC | 30 | 2022-07-22 14:05:59.517 UTC | null | null | null | null | 1,795,356 | null | 1 | 110 | ios|uigesturerecognizer|ios13 | 50,011 | <p>In general, you shouldn't try to disable the swipe to dismiss functionality, as users expect all form/page sheets to behave the same across all apps. Instead, you may want to consider using a full-screen presentation style. If you do want to use a sheet that can't be dismissed via swipe, set <code>isModalInPresentation = true</code>, but note this still allows the sheet to be pulled down vertically and it'll bounce back up upon releasing the touch. Check out the <a href="https://developer.apple.com/documentation/uikit/uiadaptivepresentationcontrollerdelegate" rel="noreferrer">UIAdaptivePresentationControllerDelegate</a> documentation to react when the user tries to dismiss it via swipe, among other actions.</p>
<p>If you have a scenario where your app's gesture or touch handling is impacted by the swipe to dismiss feature, I did receive some advice from an Apple engineer on how to fix that.</p>
<p>If you can prevent the system's pan gesture recognizer from beginning, this will prevent the gestural dismissal. A few ways to do this:</p>
<ol>
<li><p>If your canvas drawing is done with a gesture recognizer, such as your own <code>UIGestureRecognizer</code> subclass, enter the <code>began</code> phase before the sheet’s dismiss gesture does. If you recognize as quickly as <code>UIPanGestureRecognizer</code>, you will win, and the sheet’s dismiss gesture will be subverted.</p></li>
<li><p>If your canvas drawing is done with a gesture recognizer, setup a dynamic failure requirement with <code>-shouldBeRequiredToFailByGestureRecognizer:</code> (or the related delegate method), where you return <code>NO</code> if the passed in gesture recognizer is a <code>UIPanGestureRecognizer</code>.</p></li>
<li><p>If your canvas drawing is done with manual touch handling (e.g. <code>touchesBegan:</code>), override <code>-gestureRecognizerShouldBegin</code> on your touch handling view, and return <code>NO</code> if the passed in gesture recognizer is a <code>UIPanGestureRecognizer</code>.</p></li>
</ol>
<p>With my setup #3 proved to work very well. This allows the user to swipe down anywhere outside of the drawing canvas to dismiss (like the nav bar), while allowing the user to draw without moving the sheet, just as one would expect.</p>
<p>I cannot recommend trying to find the gesture to disable it, as it seems to be rather dynamic and can reenable itself when switching between different size classes for example, and this could change in future releases.</p> |
47,775,041 | Disable autofill in Chrome 63 | <p>I just updated my browser to Chrome Version 63.0.3239.84 (Official Build) (64-bit).</p>
<p>I then proceeded to go on my website, where I have a input box with <code>autocomplete='off'</code>, yet I still get the following:</p>
<p><a href="https://i.stack.imgur.com/PYASx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PYASx.png" alt="enter image description here"></a></p>
<p>(You can see my inbuilt suggestion dropdown below it)</p>
<p><strong>This never used to be the case. Nothing else has changed!</strong></p>
<p>Why is this happening? Is this a bug in the new version of chrome? I have tried all other suggestions like <code>autocomplete="false"</code> or applying autocomplete=off to the form too. I have even tried to apply these with jquery after the page has loaded but also no luck.</p>
<p>I have tested this on multiple machines with the newest version of chrome on different operating systems. The issue persists.</p> | 47,822,599 | 15 | 10 | null | 2017-12-12 14:30:37.96 UTC | 9 | 2021-04-09 19:45:55.113 UTC | null | null | null | null | 4,512,218 | null | 1 | 58 | html|google-chrome | 54,576 | <p><strong>Update Apr 2021:</strong></p>
<p>Chrome and Firefox support <code>autocomplete="off"</code></p>
<p>Safari continues to ignore <code>autocomplete="off"</code> and as far as I know there's no good solution fore Safari except to obfuscate the field name.</p>
<p><strong>Update Feb 2018:</strong></p>
<p>Thanks to @JamesNisbet for pointing this out in the comments.</p>
<p>According to the <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164" rel="nofollow noreferrer">Chrome team</a>, autocomplete="off" and autocomplete="false" will be ignored moving forward. This is not a temporary regression in Chrome.</p>
<p>Chrome will attempt to autofill any form fields that follow the <a href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill" rel="nofollow noreferrer">WHATWG standard on autocomplete</a>. With one exception, they ignore "off" and "false" values.</p>
<p>In summary, to disable autofill, use the autocomplete attribute with a value that is not on the WHATWG list.</p>
<p>Make your case why you think autocomplete="off" should not be ignored by Chrome in <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=587466" rel="nofollow noreferrer">this Chromium thread</a>.</p>
<hr />
<p>Looks like a possible regression in Chrome 63. In Chrome's original autofill documentation:</p>
<blockquote>
<p>In the past, many developers would add autocomplete="off" to their form fields to prevent the browser from performing any kind of autocomplete functionality. While Chrome will still respect this tag for autocomplete data, it will not respect it for autofill data. So when should you use autocomplete="off"? One example is when you've implemented your own version of autocomplete for search.</p>
</blockquote>
<p><a href="https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill" rel="nofollow noreferrer">https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill</a></p>
<p>They do make a distinction between autocomplete and autofill, although it's not clear they are different.</p>
<p>Chrome, Safari, and Edge are all attempting to implement autofill but there is no clear standard. They look at the name attribute rather than an explicit, standardized attribute.</p>
<p>For now <code>autocomplete="something-new"</code> is a good workaround, although syntactically it makes no sense. This seems to work because the browser can't understand it.</p> |
21,955,088 | 7 equal columns in bootstrap | <p>I was wondering if anyone could explain how I can get 7 equal columns in bootstrap? I am trying to make a calendar. This code seems to do 5:</p>
<pre><code>div class="row">
<div class="col-md-2 col-md-offset-1"></div>
<div class="col-md-2"></div>
<div class="col-md-2"></div>
<div class="col-md-2"></div>
<div class="col-md-2"></div>
</div>
</code></pre>
<p>My main content has the following class, so I would like the 7 columns to sit within this: </p>
<blockquote>
<p>col-lg-12</p>
</blockquote>
<p>Can anyone explain if this is possible, or if I have to stick to even numbers instead?</p> | 21,955,398 | 18 | 1 | null | 2014-02-22 13:40:05.19 UTC | 28 | 2022-09-23 12:01:03.853 UTC | 2017-08-05 15:51:28.857 UTC | null | 2,756,409 | null | 1,738,522 | null | 1 | 83 | html|css|twitter-bootstrap|twitter-bootstrap-3 | 106,874 | <p>Well, IMO you probably need to override the <code>width</code> of the columns by using CSS3 <code>@media</code> query.</p>
<p>Here is my attempt to create a 7-col grid system:</p>
<pre class="lang-html prettyprint-override"><code><div class="container">
<div class="row seven-cols">
<div class="col-md-1">Col 1</div>
<div class="col-md-1">Col 2</div>
<div class="col-md-1">Col 3</div>
<div class="col-md-1">Col 4</div>
<div class="col-md-1">Col 5</div>
<div class="col-md-1">Col 6</div>
<div class="col-md-1">Col 7</div>
</div>
</div>
</code></pre>
<pre><code>@media (min-width: 768px){
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 100%;
*width: 100%;
}
}
@media (min-width: 992px) {
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 14.285714285714285714285714285714%;
*width: 14.285714285714285714285714285714%;
}
}
/**
* The following is not really needed in this case
* Only to demonstrate the usage of @media for large screens
*/
@media (min-width: 1200px) {
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 14.285714285714285714285714285714%;
*width: 14.285714285714285714285714285714%;
}
}
</code></pre>
<p>The value of <code>width</code> comes from:</p>
<pre><code>width = 100% / 7 column-number = 14.285714285714285714285714285714%
</code></pre>
<h3>WORKING DEMO - (<a href="https://jsbin.com/lixivoxami/1/edit?output" rel="noreferrer">jsbin</a>)</h3>
<p>Run the code snippet and click on the "Full page".</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.col-md-1 {
background-color: gold;
}
@media (min-width: 768px){
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 100%;
*width: 100%;
}
}
@media (min-width: 992px) {
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 14.285714285714285714285714285714%;
*width: 14.285714285714285714285714285714%;
}
}
@media (min-width: 1200px) {
.seven-cols .col-md-1,
.seven-cols .col-sm-1,
.seven-cols .col-lg-1 {
width: 14.285714285714285714285714285714%;
*width: 14.285714285714285714285714285714%;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row seven-cols">
<div class="col-md-1">Col 1</div>
<div class="col-md-1">Col 2</div>
<div class="col-md-1">Col 3</div>
<div class="col-md-1">Col 4</div>
<div class="col-md-1">Col 5</div>
<div class="col-md-1">Col 6</div>
<div class="col-md-1">Col 7</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<h2>Other options</h2>
<p>Also, you could build your own 7-columns version of Twitter Bootstrap by using the <strong><a href="https://getbootstrap.com/docs/3.4/customize/#grid-system" rel="noreferrer">Custom Builder</a></strong> (Changing the <code>@grid-columns</code>, ...).</p>
<p>If you are using <em>less</em> compiler, you could download the <em>less</em> version of Twitter Bootstrap (from <a href="https://github.com/twbs/bootstrap" rel="noreferrer">Github</a>) and <a href="https://github.com/twbs/bootstrap/blob/v3.4.1/less/variables.less#L322-L334" rel="noreferrer">edit the <code>variables.less</code></a> file instead.</p> |
48,125,093 | Xampp localhost/dashboard | <p>I downloaded the recent version of xampp and I installed it and everything but when i type "localhost" in the browser it redirects me to localhost/dashboard is there a way to type localhost and see the directories and files like before?</p>
<p>there was some versions of xampp where you just have to change the name of the index.php or delete it and you could see the directories and files in localhost from the browser</p>
<p>does someone knows which versions are? or how to solve the problem?</p> | 48,125,149 | 6 | 2 | null | 2018-01-06 07:06:16.14 UTC | 3 | 2021-09-19 06:56:50.793 UTC | null | null | null | null | 9,180,391 | null | 1 | 4 | php|xampp|localhost|dashboard | 170,137 | <p>If you want to display directory than edit <code>htdocs/index.php</code> file</p>
<p>Below code is display all directory in table</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Nims Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="server/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- START PAGE SOURCE -->
<div id="wrap">
<div id="top">
<h1 id="sitename">Nims <em>Server</em> Directory list</h1>
<div id="searchbar">
<form action="#">
<div id="searchfield">
<input type="text" name="keyword" class="keyword" />
<input class="searchbutton" type="image" src="server/images/searchgo.gif" alt="search" />
</div>
</form>
</div>
</div>
<div class="background">
<div class="transbox">
<table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;">
<tr>
<?php
//echo md5("saketbook007");
//File functuion DIR is used here.
$d = dir($_SERVER['DOCUMENT_ROOT']);
$i=-1;
//Loop start with read function
while ($entry = $d->read()) {
if($entry == "." || $entry ==".."){
}else{
?>
<td class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>
<?php
}
if($i%3 == 0){
echo "</tr><tr>";
}
$i++;
}?>
</tr>
</table>
<?php $d->close();
?>
</div>
</div>
</div>
</div></div></body>
</html>
</code></pre>
<p>Style:</p>
<pre><code>@import url("fontface.css");
* {
padding:0;
margin:0;
}
.clear {
clear:both;
}
body {
background:url(images/bg.jpg) repeat;
font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
color:#212713;
}
#wrap {
width:1300px;
margin:auto;
}
#sitename {
font: normal 46px chunk;
color:#1b2502;
text-shadow:#5d7a17 1px 1px 1px;
display:block;
padding:45px 0 0 0;
width:60%;
float:left;
}
#searchbar {
width:39%;
float:right;
}
#sitename em {
font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
}
#top {
height:145px;
}
img {
width:90%;
height:250px;
padding:10px;
border:1px solid #000;
margin:0 0 0 50px;
}
.post h2 a {
color:#656f42;
text-decoration:none;
}
#searchbar {
padding:55px 0 0 0;
}
#searchfield {
background:url(images/searchbar.gif) no-repeat;
width:239px;
height:35px;
float:right;
}
#searchfield .keyword {
width:170px;
background:transparent;
border:none;
padding:8px 0 0 10px;
color:#fff;
display:block;
float:left;
}
#searchfield .searchbutton {
display:block;
float:left;
margin:7px 0 0 5px;
}
div.background
{
background:url(h.jpg) repeat-x;
border: 2px solid black;
width:99%;
}
div.transbox
{
margin: 15px;
background-color: #ffffff;
border: 1px solid black;
opacity:0.8;
filter:alpha(opacity=60); /* For IE8 and earlier */
height:500px;
}
.site{
border:1px solid #CCC;
}
.site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
.site:hover{background:#000; border:1px solid #03C;}
.site:hover a{color:#FFF}
</code></pre>
<p>Output :
<a href="https://i.stack.imgur.com/3ly7M.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/3ly7M.jpg" alt="enter image description here"></a></p> |
48,160,125 | CMake was unable to find a build program corresponding to "Unix Makefiles" | <p>brand new to coding. I've installed CLion and I plan to start coding on C++. I've also installed Cygwin. I've researched for the last hour or so on how a compiler works and how to use it, but when I selected the compiler on Clion I get the errors</p>
<p>"CMake Error: CMake was unable to find a build program corresponding to "Unix Makefiles". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool."</p>
<p>"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage"</p>
<p>and</p>
<p>"CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"</p>
<p>I've looked for some answers, but they all seem very vague or not quite the answers I'm looking for. I would really appreciate it if somebody could help me as I'm eager to start coding but this is setting me back. Thank you.</p> | 48,160,189 | 1 | 2 | null | 2018-01-09 01:00:22.93 UTC | 6 | 2022-06-07 14:54:17.12 UTC | null | null | null | null | 9,190,493 | null | 1 | 23 | c++|cmake|clion | 78,756 | <p>At first glance it seems to me you are missing a compiler. Do you have a compiler installed (ex: g++) or Windows equivalent? You mentioned you are using Cygwin, if you are planning to use gcc/g++ etc. take a look at <a href="https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html" rel="nofollow noreferrer">this tutorial</a></p>
<p>You can install them via Cygwin</p> |
25,650,263 | K means clustering for multidimensional data | <p>if the data set has 440 objects and 8 attributes (dataset been taken from UCI machine learning repository). Then how do we calculate centroids for such datasets. (wholesale customers data)
<a href="https://archive.ics.uci.edu/ml/datasets/Wholesale+customers" rel="noreferrer">https://archive.ics.uci.edu/ml/datasets/Wholesale+customers</a></p>
<p>if i calculate the mean of values of each row, will that be the centroid?
and how do I plot resulting clusters in matlab.</p> | 25,651,433 | 1 | 2 | null | 2014-09-03 17:24:35.543 UTC | 12 | 2014-09-03 18:40:30.573 UTC | 2014-09-03 18:00:39.113 UTC | null | 2,067,773 | null | 2,067,773 | null | 1 | 9 | machine-learning|cluster-analysis | 32,835 | <p>OK, first of all, in the dataset, 1 row corresponds to a <em>single</em> example in the data, you have 440 rows, which means the dataset consists of 440 examples. Each column contains the values for that specific feature (or attribute as you call it), e.g. column 1 in your dataset contains the values for the feature <code>Channel</code>, column 2 the values for the feature <code>Region</code> and so on.</p>
<p><strong><a href="http://en.wikipedia.org/wiki/K-means_clustering">K-Means</a></strong></p>
<p>Now for K-Means Clustering, you need to specify the number of clusters (the <em>K</em> in K-Means). Say you want K=3 clusters, then the simplest way to initialise K-Means is to randomly choose 3 examples from your dataset (that is 3 rows, randomly drawn from the 440 rows you have) as your centroids. <em>Now these 3 examples are your centroids</em>. </p>
<p><em>You can think of your centroids as 3 bins and you want to put every example from the dataset into the <strong>closest</strong>(usually measured by the Euclidean distance; check the function <code>norm</code> in Matlab) bin.</em> </p>
<p>After the first round of putting all examples into the closest bin, you recalculate the centroids by calculating the <code>mean</code> of all examples in their respective bins. You repeat the process of putting all the examples into the closest bin until no example in your dataset <em>moves</em> to another bin.</p>
<p><strong>Some <a href="http://www.mathworks.co.uk/help/matlab/">Matlab</a> starting points</strong></p>
<p>You load the data by <code>X = load('path/to/the/dataset', '-ascii');</code> </p>
<p>In your case <code>X</code> will be a <code>440x8</code> matrix.</p>
<p>You can calculate the Euclidean distance from an example to a centroid by
<code>distance = norm(example - centroid1);</code>,
where both, <code>example</code> and <code>centroid1</code> have dimensionality <code>1x8</code>.</p>
<p>Recalculating the centroids would work as follows, suppose you have done 1 iteration of K-Means and have put all examples into their respective closest bin. Say <code>Bin1</code> now contains all examples that are closest to <code>centroid1</code> and therefore <code>Bin1</code> has dimensionality <code>127x8</code>, which means that 127 examples out of 440 are in this bin. To calculate the centroid position for the next iteration you can then do <code>centroid1 = mean(Bin1);</code>. You would do similar things to your other bins.</p>
<p>As for plotting, you have to note that your dataset contains 8 features, which means 8 dimensions and which is not visualisable. I'd suggest you create or look for a (dummy) dataset which only consists of 2 features and would therefore be visualisable by using Matlab's <code>plot()</code> function.</p> |
53,687,051 | ping: google.com: Temporary failure in name resolution | <pre><code>ping: google.com: Temporary failure in name resolution
</code></pre>
<p>This problem is what's happing when trying to ping a domain instead of a IP, at this moment in the resolve.conf it has the 127.0.0.57 IP, tried adding this</p>
<pre><code>nameserver 8.8.8.8
</code></pre>
<p>and it fixed the problem on the short term, im going to be running a daemon that need to contact my domain control panel. so I need a long term solution.
If anyone has a solution to this issue it could be awesome.</p> | 54,460,886 | 2 | 3 | null | 2018-12-08 21:13:54.497 UTC | 30 | 2021-02-06 14:08:22.29 UTC | 2021-02-06 14:08:22.29 UTC | null | 4,657,412 | null | 5,183,270 | null | 1 | 75 | ubuntu|dns|ubuntu-18.04 | 181,919 | <p>I've faced the exactly same problem but I've fixed it with another approache.</p>
<p>Using Ubuntu 18.04, first disable <code>systemd-resolved</code> service.</p>
<p><code>sudo systemctl disable systemd-resolved.service</code></p>
<p>Stop the service</p>
<p><code>sudo systemctl stop systemd-resolved.service</code></p>
<p>Then, remove the link to <code>/run/systemd/resolve/stub-resolv.conf</code> in <code>/etc/resolv.conf</code></p>
<p><code>sudo rm /etc/resolv.conf</code></p>
<p>Add a manually created <code>resolv.conf</code> in <code>/etc/</code></p>
<p><code>sudo vim /etc/resolv.conf</code></p>
<p>Add your prefered DNS server there</p>
<p><code>nameserver 208.67.222.222</code></p>
<p>I've tested this with success.</p> |
20,431,049 | What is function User.findOrCreate doing and when is it called in passport? | <p>I can't find documentation on this function and therefor I can't make it work right. When is that function being called, what is it doing and what is it taking as first parameters? I'm trying to get access token from passport, but can't reach it anyhow.</p>
<pre><code>passport.use(new FacebookStrategy({
clientID: APP_ID,
clientSecret: APP_SECRET,
callbackURL: "http://localhost:3000/",
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({// what are these parameters?}, function (err, user) {
// when is this function called and what is it doing?
});
}
));
</code></pre>
<p>How can I get access token from passport?</p> | 20,431,414 | 2 | 0 | null | 2013-12-06 18:28:44.563 UTC | 28 | 2018-03-05 03:57:36.19 UTC | 2015-01-06 15:52:34.117 UTC | null | 1,266,650 | null | 2,102,437 | null | 1 | 53 | node.js|passport.js | 38,644 | <p><code>User.findOrCreate</code> is a made-up function that represents whatever function you have to find a user by Facebook ID, or to create one if the user doesn't exist. I think your first problem is that your callback URL is just going to your root, so you probably are never getting to that function. </p>
<p>Your callback URL should be like <code>http://localhost:3000/auth/facebook/callback</code>.</p>
<p>And then handle that URL:</p>
<pre><code>app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
</code></pre>
<p>At this point Authentication is complete. <code>accessToken</code> is returned to you -- "this is needed any time the app calls an API to read, modify or write a specific person's Facebook data on their behalf". You should save this off in some table where you store access tokens for a user. <code>profile</code> is the other key variable because that is the info about the user (what info depends on the service).</p>
<p><strong>What you do inside that function is up to you</strong>. So, make your own <code>User.findOrCreate</code>. Here is the code from passport for Facebook with some comments to explain it. This assumes you are using something like MongoDB and have a <code>User</code> table. <code>User</code> in this case is whatever variable you declared that can interface with the <code>User</code> table.</p>
<pre><code>//Use facebook strategy
passport.use(new FacebookStrategy({
clientID: config.facebook.clientID,
clientSecret: config.facebook.clientSecret,
callbackURL: config.facebook.callbackURL
},
function(accessToken, refreshToken, profile, done) {
//check user table for anyone with a facebook ID of profile.id
User.findOne({
'facebook.id': profile.id
}, function(err, user) {
if (err) {
return done(err);
}
//No user was found... so create a new user with values from Facebook (all the profile. stuff)
if (!user) {
user = new User({
name: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'facebook',
//now in the future searching on User.findOne({'facebook.id': profile.id } will match because of this next line
facebook: profile._json
});
user.save(function(err) {
if (err) console.log(err);
return done(err, user);
});
} else {
//found user. Return
return done(err, user);
}
});
}
));
</code></pre>
<p>Personally I also use a "membership" table to track multiple accounts per user (so they can authenticate with multiple accounts), as I set it up through mongoose. This is actually where I store that access token. I prefer this to having a facebook column in the user table.... but that is up to you.</p>
<pre><code>var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var membershipSchema = new Schema({
provider: String,
providerUserId: String,
accessToken: String,
userId: {type: ObjectId, ref: 'User'},
dateAdded: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Membership', membershipSchema);
</code></pre>
<p>and as such, my version of <code>User.findOrCreate</code> starts off like this:</p>
<pre><code>function(accessToken, refreshToken, profile, done) {
Membership.findOne({
providerUserId: profile.id
}, function(err,membershipData) {
//blah blah blah
</code></pre>
<p>where membership is that model above, and is defined as a variable as:</p>
<pre><code>var Membership = require('./models/membership.js')
</code></pre> |
32,579,133 | Simplest non-trivial monad transformer example for "dummies", IO+Maybe | <p>Could someone give a super simple (few lines) monad transformer example, which is non-trivial (i.e. not using the Identity monad - that I understand).</p>
<p>For example, how would someone create a monad that does IO and can handle failure (Maybe)? </p>
<p>What would be the simplest example that would demonstrate this?</p>
<p>I have skimmed through a few monad transformer tutorials and they all seem to use State Monad or Parsers or something complicated (for a newbee). I would like to see something simpler than that. I think IO+Maybe would be simple, but I don't really know how to do that myself.</p>
<p>How could I use an IO+Maybe monad stack?
What would be on top? What would be on bottom? Why?</p>
<p>In what kind of use case would one want to use the IO+Maybe monad or the Maybe+IO monad? Would that make sense to create such a composite monad at all? If yes, when, and why?</p> | 32,582,127 | 3 | 3 | null | 2015-09-15 06:28:38.343 UTC | 32 | 2016-11-04 12:30:48.187 UTC | 2015-09-15 07:29:30.267 UTC | null | 908,515 | null | 1,198,559 | null | 1 | 54 | haskell|monads|monad-transformers | 8,340 | <p>This is available <a href="http://lpaste.net/8735951286651846656">here</a> as a .lhs file.</p>
<p>The <code>MaybeT</code> transformer will allow us to break out of a monad computation much like throwing an exception.</p>
<p>I'll first quickly go over some preliminaries. Skip down to <strong>Adding Maybe powers to IO</strong> for a worked example.</p>
<p>First some imports:</p>
<pre><code> import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
</code></pre>
<p>Rules of thumb:</p>
<blockquote>
<p>In a monad stack IO is always on the bottom.</p>
</blockquote>
<p>Other IO-like monads will also, as a rule, always appear on the bottom, e.g. the state transformer monad <code>ST</code>.</p>
<blockquote>
<p><code>MaybeT m</code> is a new monad type which adds the power of the Maybe monad to the monad <code>m</code> - e.g. <code>MaybeT IO</code>.</p>
</blockquote>
<p>We'll get into what that power is later. For now, get used to thinking of <code>MaybeT IO</code> as the maybe+IO monad stack.</p>
<blockquote>
<p>Just like <code>IO Int</code> is a monad expression returning an <code>Int</code>, <code>MaybeT IO Int</code> is a <code>MaybeT IO</code> expression returning an <code>Int</code>.</p>
</blockquote>
<p>Getting used to reading compound type signatures is half the battle to understanding monad transformers.</p>
<blockquote>
<p>Every expression in a <code>do</code> block must be from the same monad.</p>
</blockquote>
<p>I.e. this works because each statement is in the IO-monad:</p>
<pre><code> greet :: IO () -- type:
greet = do putStr "What is your name? " -- IO ()
n <- getLine -- IO String
putStrLn $ "Hello, " ++ n -- IO ()
</code></pre>
<p>This will not work because <code>putStr</code> is not in the <code>MaybeT IO</code> monad:</p>
<pre><code>mgreet :: MaybeT IO ()
mgreet = do putStr "What is your name? " -- IO monad - need MaybeT IO here
...
</code></pre>
<p>Fortunately there is a way to fix this.</p>
<blockquote>
<p>To transform an <code>IO</code> expression into a <code>MaybeT IO</code> expression use <code>liftIO</code>.</p>
</blockquote>
<p><code>liftIO</code> is polymorphic, but in our case it has the type:</p>
<pre><code>liftIO :: IO a -> MaybeT IO a
mgreet :: MaybeT IO () -- types:
mgreet = do liftIO $ putStr "What is your name? " -- MaybeT IO ()
n <- liftIO getLine -- MaybeT IO String
liftIO $ putStrLn $ "Hello, " ++ n -- MaybeT IO ()
</code></pre>
<p>Now all of the statement in <code>mgreet</code> are from the <code>MaybeT IO</code> monad.</p>
<blockquote>
<p>Every monad transformer has a "run" function.</p>
</blockquote>
<p>The run function "runs" the top-most layer of a monad stack returning
a value from the inside layer.</p>
<p>For <code>MaybeT IO</code>, the run function is:</p>
<pre><code>runMaybeT :: MaybeT IO a -> IO (Maybe a)
</code></pre>
<p>Example:</p>
<pre><code>ghci> :t runMaybeT mgreet
mgreet :: IO (Maybe ())
ghci> runMaybeT mgreet
What is your name? user5402
Hello, user5402
Just ()
</code></pre>
<p>Also try running: </p>
<pre><code>runMaybeT (forever mgreet)
</code></pre>
<p>You'll need to use Ctrl-C to break out of the loop.</p>
<p>So far <code>mgreet</code> doesn't do anything more than what we could do in IO.
Now we'll work on an example which demonstrates the power of mixing
the Maybe monad with IO.</p>
<h1>Adding Maybe powers to IO</h1>
<p>We'll start with a program which asks some questions:</p>
<pre><code> askfor :: String -> IO String
askfor prompt = do
putStr $ "What is your " ++ prompt ++ "? "
getLine
survey :: IO (String,String)
survey = do n <- askfor "name"
c <- askfor "favorite color"
return (n,c)
</code></pre>
<p>Now suppose we want to give the user the ability to end the survey
early by typing END in response to a question. We might handle it
this way:</p>
<pre><code> askfor1 :: String -> IO (Maybe String)
askfor1 prompt = do
putStr $ "What is your " ++ prompt ++ " (type END to quit)? "
r <- getLine
if r == "END"
then return Nothing
else return (Just r)
survey1 :: IO (Maybe (String, String))
survey1 = do
ma <- askfor1 "name"
case ma of
Nothing -> return Nothing
Just n -> do mc <- askfor1 "favorite color"
case mc of
Nothing -> return Nothing
Just c -> return (Just (n,c))
</code></pre>
<p>The problem is that <code>survey1</code> has the familiar staircasing issue which
doesn't scale if we add more questions.</p>
<p>We can use the MaybeT monad transformer to help us here.</p>
<pre><code> askfor2 :: String -> MaybeT IO String
askfor2 prompt = do
liftIO $ putStr $ "What is your " ++ prompt ++ " (type END to quit)? "
r <- liftIO getLine
if r == "END"
then MaybeT (return Nothing) -- has type: MaybeT IO String
else MaybeT (return (Just r)) -- has type: MaybeT IO String
</code></pre>
<p>Note how all of the statemens in <code>askfor2</code> have the same monad type.</p>
<p>We've used a new function:</p>
<pre><code>MaybeT :: IO (Maybe a) -> MaybeT IO a
</code></pre>
<p>Here is how the types work out:</p>
<pre><code> Nothing :: Maybe String
return Nothing :: IO (Maybe String)
MaybeT (return Nothing) :: MaybeT IO String
Just "foo" :: Maybe String
return (Just "foo") :: IO (Maybe String)
MaybeT (return (Just "foo")) :: MaybeT IO String
</code></pre>
<p>Here <code>return</code> is from the IO-monad.</p>
<p>Now we can write our survey function like this:</p>
<pre><code> survey2 :: IO (Maybe (String,String))
survey2 =
runMaybeT $ do a <- askfor2 "name"
b <- askfor2 "favorite color"
return (a,b)
</code></pre>
<p>Try running <code>survey2</code> and ending the questions early by typing END as a response to either question.</p>
<h1>Short-cuts</h1>
<p>I know I'll get comments from people if I don't mention the following short-cuts.</p>
<p>The expression:</p>
<pre><code>MaybeT (return (Just r)) -- return is from the IO monad
</code></pre>
<p>may also be written simply as:</p>
<pre><code>return r -- return is from the MaybeT IO monad
</code></pre>
<p>Also, another way of writing <code>MaybeT (return Nothing)</code> is:</p>
<pre><code>mzero
</code></pre>
<p>Furthermore, two consecutive <code>liftIO</code> statements may always combined into a single <code>liftIO</code>, e.g.:</p>
<pre><code>do liftIO $ statement1
liftIO $ statement2
</code></pre>
<p>is the same as:</p>
<pre><code>liftIO $ do statement1
statement2
</code></pre>
<p>With these changes our <code>askfor2</code> function may be written:</p>
<pre><code>askfor2 prompt = do
r <- liftIO $ do
putStr $ "What is your " ++ prompt ++ " (type END to quit)?"
getLine
if r == "END"
then mzero -- break out of the monad
else return r -- continue, returning r
</code></pre>
<p>In a sense, <code>mzero</code> becomes a way of breaking out of the monad - like throwing an exception.</p>
<h1>Another example</h1>
<p>Consider this simple password asking loop:</p>
<pre><code>loop1 = do putStr "Password:"
p <- getLine
if p == "SECRET"
then return ()
else loop1
</code></pre>
<p>This is a (tail) recursive function and works just fine.</p>
<p>In a conventional language we might write this as a infinite while loop with a break statement:</p>
<pre><code>def loop():
while True:
p = raw_prompt("Password: ")
if p == "SECRET":
break
</code></pre>
<p>With MaybeT we can write the loop in the same manner as the Python code:</p>
<pre><code>loop2 :: IO (Maybe ())
loop2 = runMaybeT $
forever $
do liftIO $ putStr "Password: "
p <- liftIO $ getLine
if p == "SECRET"
then mzero -- break out of the loop
else return ()
</code></pre>
<p>The last <code>return ()</code> continues execution, and since we are in a <code>forever</code> loop, control passes back to the top of the do block. Note that the only value that <code>loop2</code> can return is <code>Nothing</code> which corresponds to breaking out of the loop.</p>
<p>Depending on the situation you might find it easier to write <code>loop2</code> rather than the recursive <code>loop1</code>.</p> |
4,577,191 | Non-static method requires a target C# | <p>I have a win form app with a listbox displaying methods (by attribute). I am attempting to dynamically invoke methods in a thread, using reflection to get method info from the selected value of the the list box. However, when calling <em>Methodinfo.Invoke</em> I am getting this inner exception "Non-static method requires a target C#". </p>
<p>Here's my code (keep in mind I'm still new to c# and programming in general.)</p>
<pre><code>private void PopulateComboBox()
{//Populates list box by getting methods with declared attributes
MethodInfo[] methods = typeof(MainForm).GetMethods();
MyToken token = null;
List<KeyValuePair<String, MethodInfo>> items =
new List<KeyValuePair<string, MethodInfo>>();
foreach (MethodInfo method in methods)
{
token = Attribute.GetCustomAttribute(method,
typeof(MyToken), false) as MyToken;
if (token == null)
continue;
items.Add(new KeyValuePair<String, MethodInfo>(
token.DisplayName, method));
}
testListBox.DataSource = items;
testListBox.DisplayMember = "Key";
testListBox.ValueMember = "Value";
}
public void GetTest()
{//The next two methods handle selected value of the listbox and invoke the method.
if (testListBox.InvokeRequired)
testListBox.BeginInvoke(new DelegateForTest(functionForTestListBox));
else
functionForTestListBox();
}
public void functionForTestListBox()
{
_t = testListBox.SelectedIndex;
if (_t < 0)
return;
_v = testListBox.SelectedValue;
method = _v as MethodInfo;
if (method == null)
return;
_selectedMethod = method.Name;
MessageBox.Show(_selectedMethod.ToString());
method.Invoke(null, null);//<----Not sure about this. it runs fine when I dont invoke in a thread.
counter++;
}
private void runTestButton_Click(object sender, EventArgs e)
{// Click event that calls the selected method in the thread
if (_serverStatus == "Running")
{
if (_testStatus == "Not Running")
{
// create Instance new Thread and add function
// which will do some work
try
{
SetupTestEnv();
//functionForOutputTextBox();
Thread UIthread = new Thread(new ThreadStart(GetTest));
UIthread.Name = "UIThread";
UIthread.Start();
// Update test status
_testStatus = "Running";
//Make thread global
_UIthread = UIthread;
}
catch
{
MessageBox.Show("There was an error at during the test setup(Note: You must install each web browser on your local machine before attempting to test on them).");
}
}
else
{
MessageBox.Show("Please stop the current test before attempt to start a new one");
}
}
else
{
MessageBox.Show("Please make sure the server is running");
}
}
</code></pre> | 4,577,220 | 1 | 0 | null | 2011-01-02 04:53:25.28 UTC | 3 | 2014-04-14 13:31:15.257 UTC | 2014-04-14 13:31:15.257 UTC | null | 1,279,355 | null | 560,140 | null | 1 | 14 | c#|multithreading|reflection | 62,285 | <p>You are trying to invoke non-static method without providing object instance reference, for which this method should be invoked. Since you are working with methods of <code>MainForm</code> class, you should provide object of <code>MainForm</code> type in the first parameter of <code>MethodInfo.Invoke(Object, Object[])</code>, in your case:</p>
<pre><code>if(method.IsStatic)
method.Invoke(null, null);
else
method.Invoke(this, null);
</code></pre>
<p>Example of executing method on separate thread:</p>
<pre><code>public MethodInfo GetSelectedMethod()
{
var index = testListBox.SelectedIndex;
if (index < 0) return;
var value = testListBox.SelectedValue;
return value as MethodInfo;
}
private void ThreadProc(object arg)
{
var method = (MethodInfo)arg;
if(method.IsStatic)
method.Invoke(null, null)
else
method.Invoke(this, null);
}
private void RunThread()
{
var method = GetSelectedMethod();
if(method == null) return;
var thread = new Thread(ThreadProc)
{
Name = "UIThread",
};
thread.Start(method);
}
</code></pre> |
4,176,377 | How to get the full path of the file from a file input | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3489133/full-path-from-file-input-using-jquery">Full path from file input using jQuery</a> </p>
</blockquote>
<p>I have the following html element </p>
<pre><code><input type="file" id="upload">
</code></pre>
<p>If I use </p>
<pre><code>$("#upload").val();
</code></pre>
<p>I only the file name, not the complete absolute path of the file. Can someone tell me how do get the complete path? </p> | 4,176,605 | 1 | 1 | null | 2010-11-14 05:58:48.197 UTC | 3 | 2012-10-20 08:56:10.037 UTC | 2017-05-23 10:30:55.877 UTC | null | -1 | null | 157,644 | null | 1 | 25 | jquery|html | 137,260 | <p>You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/3489133/full-path-from-file-input-using-jquery">full path from file input using jquery</a> </li>
<li><a href="https://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3">How to get the file path from HTML input form in Firefox 3</a></li>
</ul>
<p>In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the <code>input type="file"</code> field, ostensibly for backward compatibility reasons. </p>
<ul>
<li><a href="http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-March/018981.html" rel="noreferrer">http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-March/018981.html</a></li>
<li><a href="http://acidmartin.wordpress.com/2009/06/09/the-mystery-of-cfakepath-unveiled/" rel="noreferrer">The Mystery of c:\fakepath Unveiled</a></li>
</ul>
<p>So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.</p> |
25,020,129 | cin.ignore(numeric_limits<streamsize>::max(), '\n') | <p>What does <code>cin.ignore(numeric_limits<streamsize>::max(), '\n')</code> mean in C++?</p>
<p>Does it actually ignore the last input from the user? </p> | 25,020,223 | 3 | 3 | null | 2014-07-29 16:18:42.85 UTC | 30 | 2021-08-10 23:33:05.71 UTC | 2021-08-10 23:33:05.71 UTC | null | 12,299,000 | null | 3,888,498 | null | 1 | 44 | c++|cin | 56,252 | <p>This line ignores the rest of the current line, up to <code>'\n'</code> or <code>EOF</code> - whichever comes first:</p>
<ul>
<li><code>'\n'</code> sets the delimiter, i.e. the character after which <code>cin</code> stops ignoring</li>
<li><code>numeric_limits<streamsize>::max()</code> sets the maximum number of characters to ignore. Since this is the upper limit on the size of a stream, you are effectively telling <code>cin</code> that there is no limit to the number of characters to ignore.</li>
</ul> |
39,826,711 | How to navigate to error lines in Android Studio by shortcut? | <p>How can I navigate to the error lines in a java file? </p>
<p>Isn't there any better way than scrolling to them?</p> | 39,826,712 | 5 | 1 | null | 2016-10-03 07:46:23.28 UTC | 9 | 2021-06-01 12:03:13.993 UTC | 2018-10-19 10:22:48.87 UTC | null | 6,325,722 | null | 6,769,908 | null | 1 | 86 | android|android-studio | 25,834 | <p>I searched for it and found the answer.</p>
<p>1- you can use <strong>F2</strong> and <strong>SHIFT+F2</strong> shortcut to navigate between errors in your document. if there is no error you will be navigated to the warnings.</p>
<p>2- another way that most of us know is to click on the red areas on the scrollbar.</p>
<p><a href="https://www.jetbrains.com/help/idea/2016.2/navigating-to-next-previous-error.html" rel="noreferrer">here is the the link to the <strong>intelliJ IDEA</strong> help documents</a> which is the base of <strong>Android Studio</strong>.</p>
<p>you can even press <strong>F2</strong> in project window of Android Studio and it will select the files containing errors.</p>
<p>Also if there are no more errors it will point to warnings.</p> |
39,732,319 | How to inject WCF service client in ASP.Net core? | <p>I have WCF service that I need to access from ASP.NET Core. I have installed <a href="https://visualstudiogallery.msdn.microsoft.com/c3b3666e-a928-4136-9346-22e30c949c08" rel="noreferrer">WCF Connected Preview</a> and created proxy successfully.</p>
<p>It created interface & client something like below</p>
<pre><code> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IDocumentIntegration")]
public interface IDocumentIntegration
{
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IDocumentIntegration/SubmitDocument", ReplyAction="http://tempuri.org/IDocumentIntegration/SubmitDocumentResponse")]
[System.ServiceModel.FaultContractAttribute(typeof(ServiceReference1.FaultDetail), Action="http://tempuri.org/IDocumentIntegration/SubmitDocumentFaultDetailFault", Name="FaultDetail", Namespace="http://schemas.datacontract.org/2004/07/MyCompany.Framework.Wcf")]
System.Threading.Tasks.Task<string> SubmitDocumentAsync(string documentXml);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
public interface IDocumentIntegrationChannel : ServiceReference1.IDocumentIntegration, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.3.0.0")]
public partial class DocumentIntegrationClient : System.ServiceModel.ClientBase<ServiceReference1.IDocumentIntegration>, ServiceReference1.IDocumentIntegration
{
// constructors and methods here
}
</code></pre>
<p>The consumer class that calls the service looks like below</p>
<pre><code>public class Consumer
{
private IDocumentIntegration _client;
public Consumer(IDocumentIntegration client)
{
_client = client;
}
public async Task Process(string id)
{
await _client.SubmitDocumentAsync(id);
}
}
</code></pre>
<p>How do I register the IDocumentIntegration with ConfigureServices method in Startup class?
I want to setup RemoteAddress & clientCredentials during the registration</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// how do I inject DocumentIntegrationClient here??
var client = new DocumentIntegrationClient();
client.ClientCredentials.UserName.UserName = "myusername";
client.ClientCredentials.UserName.Password = "password";
client.Endpoint.Address = new EndpointAddress(urlbasedonenvironment)
}
</code></pre> | 39,732,412 | 1 | 2 | null | 2016-09-27 18:55:20.667 UTC | 9 | 2018-12-16 15:42:56.06 UTC | 2018-12-16 15:42:56.06 UTC | null | 8,618,595 | null | 3,862,378 | null | 1 | 13 | c#|asp.net-core|.net-core|coreclr | 23,056 | <p>Using the factory method overload seems suitable use case for it. </p>
<pre class="lang-cs prettyprint-override"><code>services.AddScoped<IDocumentIntegration>(provider => {
var client = new DocumentIntegrationClient();
// Use configuration object to read it from appconfig.json
client.ClientCredentials.UserName.UserName = Configuration["MyService:Username"];
client.ClientCredentials.UserName.Password = Configuration["MyService:Password"];
client.Endpoint.Address = new EndpointAddress(Configuration["MyService:BaseUrl"]);
return client;
});
</code></pre>
<p>Where your appsettings would look like </p>
<pre class="lang-cs prettyprint-override"><code>{
...
"MyService" :
{
"Username": "guest",
"Password": "guest",
"BaseUrl": "http://www.example.com/"
}
}
</code></pre>
<p>Alternatively, inject the Options via options pattern. Since the <code>DocumentIntegrationClient</code> is partial, you can create a new file and add a parameterized constructor. </p>
<pre class="lang-cs prettyprint-override"><code>public partial class DocumentIntegrationClient :
System.ServiceModel.ClientBase<ServiceReference1.IDocumentIntegration>, ServiceReference1.IDocumentIntegration
{
public DocumentIntegrationClient(IOptions<DocumentServiceOptions> options) : base()
{
if(options==null)
{
throw new ArgumentNullException(nameof(options));
}
this.ClientCredentials.Username.Username = options.Username;
this.ClientCredentials.Username.Password = options.Password;
this.Endpoint.Address = new EndpointAddress(options.BaseUrl);
}
}
</code></pre>
<p>And create a options class</p>
<pre class="lang-cs prettyprint-override"><code>public class DocumentServiceOptions
{
public string Username { get; set; }
public string Password { get; set; }
public string BaseUrl { get; set; }
}
</code></pre>
<p>and populate it from <code>appsettings.json</code>.</p>
<pre class="lang-cs prettyprint-override"><code>services.Configure<DocumentServiceOptions>(Configuration.GetSection("MyService"));
</code></pre> |
31,261,035 | Select2 disable/enable specific option | <p>I have a list which is of type select2.</p>
<pre><code><select id="list" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<optgroup label="Types">
<option value="None">None</option>
<option value="1">One</option>
<option value="2">Two</option>
</optgroup>
</select>
</code></pre>
<p>I want to disable option which is having <strong>value=1</strong>
so I did like this</p>
<pre><code>$("#list>optgroup>option[value='1']").prop('disabled',true);
Result:// <option value="1" disabled>One</option>
</code></pre>
<p>It is working fine;but if i want to re-enable disabled option i tried below codes but still the select2 option is disabled.</p>
<pre><code>$("#list>optgroup>option[value='1']").prop('disabled',false);
$("#list>optgroup>option[value='1']").removeProp('disabled');
Result:// <option value="1">One</option>
</code></pre>
<p>but strange is disabled property of the option is removed. but the select2 option remains disabled.</p>
<p>Not getting how to resolve this. Need help.</p>
<p>Update: If I check DOM of select2 it is having this property even after removing disabled.</p>
<pre><code><li class="select2-results__option" id="select2-template-type-list-result-4qd3-merge" role="treeitem" aria-disabled="true">One</li>
</code></pre>
<p>if i make <strong>aria-disabled="false"</strong> it will enable. not able to get what is the cause.</p> | 31,263,496 | 6 | 9 | null | 2015-07-07 06:10:52.65 UTC | 3 | 2021-08-30 10:41:24.3 UTC | 2020-08-05 05:04:42.233 UTC | null | 4,596,556 | null | 4,596,556 | null | 1 | 24 | jquery|select|jquery-select2 | 88,161 | <p>Probably easiest way to achieve this, would be calling <code>.select2(…)</code> on the element again after changing the disabled attribute.</p>
<p><a href="http://jsfiddle.net/xoxd2u15/" rel="noreferrer">http://jsfiddle.net/xoxd2u15/</a></p>
<p>Since select2 <em>replaces</em> the original select field with custom HTML elements (and hides the original), and apparently does not “watch” the options of that original select element for changes in their disabled state constantly after invocation, you have to call it once more after changing the state, so that it reads the current attribute values from the original element’s options. </p> |
39,248,826 | How to solve error converting data type varchar to numeric | <pre><code>SELECT
A.SETMOD, B.DESCRP
FROM
PMS.PSBSTTBL A
JOIN
PMS.PR029TBL B ON A.SETMOD = B.PAYMOD
</code></pre>
<p><code>Paymod</code> is of datatype <code>VARCHAR</code>, <code>SETMOD</code> of type <code>decimal</code></p> | 39,248,965 | 3 | 4 | null | 2016-08-31 11:48:08.627 UTC | null | 2016-08-31 11:54:07.88 UTC | 2016-08-31 11:50:25.66 UTC | null | 13,302 | null | 5,762,475 | null | 1 | -1 | sql|sql-server|tsql | 53,457 | <p>Best thing is to convert the decimal to string and compare it with the string value.. make necessary adjustments on the decimal part.. :)</p>
<pre><code>SELECT
A.SETMOD, B.DESCRP
FROM
PMS.PSBSTTBL A
JOIN
PMS.PR029TBL B ON CONVERT(VARCHAR(50),A.SETMOD) = B.PAYMOD
</code></pre> |
70,022,194 | Open .net framework 4.5 project in VS 2022. Is there any workaround? | <p>Is there anyway to open and work on <code>.net framework 4.5</code> project in <code>visual studio 2022</code>.</p>
<p>May be problem is not with VS2022 but as <code>.net framework 4.5</code> developer pack is not available any more .. my project can not be changed target version .. Is there any workaround?</p>
<p><a href="https://i.stack.imgur.com/924BM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/924BM.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/mJrjt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mJrjt.png" alt="enter image description here" /></a></p> | 70,109,092 | 7 | 3 | null | 2021-11-18 15:07:00.417 UTC | 26 | 2022-08-02 12:50:15.687 UTC | 2021-11-18 15:23:25.42 UTC | null | 2,052,085 | null | 2,052,085 | null | 1 | 91 | .net|visual-studio|windows-10|.net-framework-version | 47,205 | <ul>
<li>Download <a href="https://www.nuget.org/packages/microsoft.netframework.referenceassemblies.net45" rel="noreferrer">Microsoft.NETFramework.ReferenceAssemblies.net45</a> from nuget.org</li>
<li>Open the package as zip</li>
<li>copy the files from <code>build\.NETFramework\v4.5\</code> to <code>C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5</code></li>
</ul>
<p>For more details: <a href="https://thomaslevesque.com/2021/11/12/building-a-project-that-target-net-45-in-visual-studio-2022/" rel="noreferrer">Building a project that target .NET Framework 4.5 in Visual Studio 2022</a></p> |
26,818,091 | Force browser to reload index.htm | <p>how can I force a browser to always load the newest version of index.htm when the page is loaded by entering the URL www.mydomain.com/index.htm or just www.mydomain.com in the browser's address field and pressing enter.</p>
<p>I'm trying this in Chrome and the newest version of index.htm is apparently only loaded, when I refresh manually (F5), or when the URL is already in the browser's address field and I press enter.</p>
<p>I guess I am doing something extremely stupid, because when I searched for the issue, all I could find were solutions about how to make a browser reload your .js and .css files by appending ?v=xxxx to the file names. But how should this work, if not even the newest version of index.htm page, in which I am doing these modifiactions, is loaded??</p>
<p>I also tried putting</p>
<pre><code><meta http-equiv="cache-control" content="no-cache">
</code></pre>
<p>in the <code><head></code> of index.htm. But this does not seem to have any effect.</p>
<p>Any help would be greatly appreciated!</p>
<p>Thanks, Linus</p> | 26,818,602 | 3 | 1 | null | 2014-11-08 14:26:17.993 UTC | 18 | 2017-05-04 13:21:59.7 UTC | null | null | null | null | 617,065 | null | 1 | 44 | html|caching|reload | 93,351 | <p>OK, apparently no-cache was not enough.
The following does the trick:</p>
<pre><code> <meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
</code></pre> |
19,868,838 | Call to undefined method Illuminate\Database\Query\Builder::associate() | <p>Reference: <a href="https://stackoverflow.com/questions/16921511/how-can-i-update-an-existing-eloquent-relationship-in-laravel-4">How can I update an existing Eloquent relationship in Laravel 4?</a></p>
<pre><code>$userinfo = \Userinfo::find($id);
\User::find($id)->userinfo()->associate($userinfo)->save();
</code></pre>
<p>I'm getting the error: <code>Call to undefined method Illuminate\Database\Query\Builder::associate()</code></p>
<p>Here is the entire method: </p>
<pre><code>public function saveUser($id)
{
$user = \User::find($id);
$userdata = \Input::all();
$rules = array(
'email' => 'required|email',
'state' => 'size:2',
'zip' => 'size:5',
'phone' => array('regex:/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/')
);
$validator = \Validator::make($userdata, $rules);
if ($validator->passes())
{
if ($userdata['email'] !== $user->email)
{
$rules = array('email' => 'unique:users');
$validator = \Validator::make($userdata, $rules);
if ($validator->fails()) return Redirect::route('admin.user.edit', array('user' => $user))
->with('error', 'Specified email already exists.');
}
$user->email = $userdata['email'];
$user->firstname = $userdata['firstname'];
$user->lastname = $userdata['lastname'];
$userinfoArray = array(
'address' => $userdata['address'],
'city' => $userdata['city'],
'state' => $userdata['state'],
'zip' => $userdata['zip'],
'phone' => preg_replace('/[^0-9]/', '', $userdata['phone'])
);
$user->save();
if (!$user->userinfo)
{
$userinfo = new \Userinfo($userinfoArray);
$userinfo = $user->userinfo()->save($userinfo);
}
else
{
$userinfo = \Userinfo::find($id);
\User::find($id)->userinfo()->associate($userinfo)->save();
//$user->userinfo()->update($userinfoArray);
}
return \Redirect::route('admin.user.detail', array('id' => $id))
->with('success', 'User updated.');
}
return \Redirect::route('admin.user.edit', array('id' => $id))
->withInput()
->withErrors($validator);
}
</code></pre> | 19,993,027 | 4 | 0 | null | 2013-11-08 21:29:47.823 UTC | 4 | 2017-06-17 12:20:45.727 UTC | 2017-05-23 10:31:27.11 UTC | null | -1 | null | 204,406 | null | 1 | 24 | php|laravel-4|eloquent | 74,997 | <p>associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.</p>
<p>I am just guessing as you have not provided your eloquent model class code so can't see how you have set the relationships exactly, but if you have:</p>
<pre><code>class User extends Eloquent {
public function userinfo()
{
return $this->hasOne('Userinfo');
}
}
class Userinfo extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
</code></pre>
<p>Then associate needs to be called against Userinfo as this has the belongsTo relationship to which the associate() method is attached.</p>
<p>For example</p>
<pre><code>$user = \User::find(4);
$userinfo = \UserInfo::find(1);
$userinfo->user()->associate($user);
$userinfo->save();
</code></pre>
<p>Will set the foreign key user_id in the user_info table to the id of the $user object.</p>
<p>Looking at your above code it doesn't appear that this is what you are actually trying to do and that the </p>
<pre><code>$user->userinfo()->update($userinfoArray);
</code></pre>
<p>call which you have commented out will in fact do what you seem to be trying to achieve, which is to update the userinfo that is related to the current user if that user already exists.</p>
<p>Hope this helps. </p>
<p>Glen</p> |
6,444,576 | Python method name with double-underscore is overridden? | <p>Take a look at this.
Note that class <code>B</code> overrides <code>A</code>'s <code>a()</code> method.</p>
<pre><code>In [1]: class A(object):
...: def __init__(self):
...: self.a()
...: def a(self):
...: print "A.a()"
...:
...:
In [2]: class B(A):
...: def __init__(self):
...: super(B, self).__init__()
...: def a(self):
...: print "B.a()"
...:
...:
In [3]: b = B()
B.a()
</code></pre>
<p>No surprises there.</p>
<p>Now, take a look at this.
Note that the method now being overridden is <code>__a()</code>.</p>
<pre><code>In [7]: class A(object):
...: def __init__(self):
...: self.__a()
...: def __a(self):
...: print "A.__a()"
...:
...:
In [8]: class B(A):
...: def __init__(self):
...: super(B, self).__init__()
...: def __a(self):
...: print "B.__a()"
...:
...:
In [9]: b = B()
A.__a()
</code></pre>
<p>This behaviour surprised me.</p>
<p>Can anyone explain why <code>A.__a()</code> is called instead of <code>B.__a()</code>?</p>
<p>Anything <code>__special__</code> about <code>__a</code>?</p>
<p><strong><em>Update</em></strong>:
After reading Sean's answer I wanted to see if I could override the name mangled method and got this result:</p>
<pre><code>In [11]: class B(A):
....: def __init__(self):
....: super(B, self).__init__()
....: def _A__a(self):
....: print "B._A__a()"
....:
....:
In [12]: b = B()
B._A__a()
</code></pre> | 6,444,617 | 2 | 0 | null | 2011-06-22 18:18:46.55 UTC | 6 | 2018-01-30 16:59:37.527 UTC | 2014-05-12 16:00:48.58 UTC | null | 100,297 | null | 300,781 | null | 1 | 30 | python | 23,887 | <p>keywords with a pattern of __* are class private names.</p>
<p><a href="http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers" rel="nofollow noreferrer">http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers</a></p>
<p>Quoting:</p>
<blockquote>
<p>Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes</p>
</blockquote>
<p>Private name mangling (emphasis added):</p>
<blockquote>
<p>Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. <strong>For example, the identifier <code>__spam</code> occurring in a class named Ham will be transformed to <code>_Ham__spam</code></strong>. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.</p>
</blockquote>
<p><a href="http://docs.python.org/reference/expressions.html#atom-identifiers" rel="nofollow noreferrer">http://docs.python.org/reference/expressions.html#atom-identifiers</a></p>
<p>This means that behind the scenes, <code>B.__a()</code> is transformed to something like <code>B._B__a()</code></p> |
6,635,417 | How do I add Sublime Text 2 keybindings? | <p>I am looking to get the following assigned to Keybindings. I am able to make a snippet for this, yet would prefer to be able to <kbd>CTRL</kbd> + <kbd>></kbd> just like in Textmate.</p>
<pre><code><%= %>
</code></pre>
<p>What do I need to add and where do I need to add it, or where could I find out.</p> | 6,635,457 | 2 | 0 | null | 2011-07-09 14:38:28.547 UTC | 12 | 2013-04-14 03:36:34.163 UTC | 2013-04-14 03:36:34.163 UTC | null | 150,647 | null | 577,180 | null | 1 | 41 | macos|sublimetext | 13,827 | <p>If you just want to literally insert those characters, you can set up your "User Key Bindings" like this:</p>
<pre><code>[
{ "keys": ["ctrl+."], "command": "insert", "args": {"characters": "<%= %>"} }
]
</code></pre>
<p>You can use the Default Key Bindings file as an example for possible key binding commands. Both User and Default are located in Sublime Text 2 -> Preferences on OS X.</p>
<p>Not sure if you really wanted <code>"ctrl+shift+."</code>, but it would work as well.</p>
<p>To move the cursor to the middle during insert, you can use insert_snippet like this:</p>
<pre><code>[
{ "keys": ["ctrl+shift+."], "command": "insert_snippet", "args": {"contents": "<%=$0 %>"} }
]
</code></pre> |
7,493,273 | Remove trailing decimal point & zeroes with Regex | <p>Is this the proper REGEX to remove trailing decimal and zeroes from a string? I can't get it to work. What am I missing?</p>
<ol>
<li>78.000 -> 78</li>
<li>78.008 -> 78.008</li>
</ol>
<p><code>str.replaceAll("^.0*$", "");</code></p> | 7,493,292 | 3 | 0 | null | 2011-09-21 00:17:24.807 UTC | 5 | 2011-09-21 00:55:05.297 UTC | null | null | null | null | 783,284 | null | 1 | 15 | java|regex|string | 40,034 | <p>You need to escape the <code>.</code>, as it is a special character in Regex that matches any character. You also have to remove the <code>^</code>, which anchors at the beginning of the number.</p>
<pre><code>str.replaceAll("\\.0*$", "");
</code></pre>
<p>You can use a lookbehind if you want to make sure there is a number in front of the dot, like this:</p>
<pre><code>str.replaceAll("(?<=^\\d+)\\.0*$", "");
</code></pre>
<p>The lookbehind (the <code>(?<=...)</code> part) is not a part of the match, so it will not be replaced, but it still has to match for the rest of the regex to match.</p> |
7,232,405 | Examples of XSS that I can use to test my page input? | <p>I have had issues with XSS. Specifically I had an individual inject JS alert showing that the my input had vulnerabilities. I have done research on XSS and found examples but for some reason I can't get them to work.</p>
<p>Can I get example(s) of XSS that I can throw into my input and when I output it back to the user see some sort of change like an alert to know it's vulnerable?</p>
<p>I'm using PHP and I am going to implement htmlspecialchars() but I first am trying to reproduce these vulnerabilities.</p>
<p>Thanks! </p> | 7,232,426 | 4 | 7 | null | 2011-08-29 15:42:32.57 UTC | 8 | 2017-10-01 11:22:15.407 UTC | null | null | null | null | 625,740 | null | 1 | 22 | php|javascript|security|xss | 57,739 | <p>You can use this firefox addon:</p>
<ul>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/xss-me/" rel="noreferrer">XSS Me</a></li>
</ul>
<blockquote>
<p>XSS-Me is the Exploit-Me tool used to test for reflected Cross-Site
Scripting (XSS). It does NOT currently test for stored XSS.</p>
<p>The
tool works by submitting your HTML forms and substituting the form
value with strings that are representative of an XSS attack. If the
resulting HTML page sets a specific JavaScript value
(document.vulnerable=true) then the tool marks the page as vulnerable
to the given XSS string. The tool does not attempting to compromise
the security of the given system. It looks for possible entry points
for an attack against the system. There is no port scanning, packet
sniffing, password hacking or firewall attacks done by the
tool.</p>
<p>You can think of the work done by the tool as the same as the
QA testers for the site manually entering all of these strings into
the form fields.</p>
</blockquote> |
8,153,800 | How to set NumberFormat to Number with 0 decimal places | <p>The below VBA in MS Access is run to format my Excel sheet. However, it is formatting to Number with 2 decimal places. How do I specify that I want 0 decimal places?</p>
<pre><code> wb.Sheets(1).Range("K:AD").Formula = wb.Sheets(1).Range("K:AD").Value
wb.Sheets(1).Range("K:AD").NumberFormat = "Number"
</code></pre> | 8,153,869 | 1 | 0 | null | 2011-11-16 15:05:08.873 UTC | 3 | 2011-11-16 17:18:01.753 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 888,737 | null | 1 | 9 | vba|excel|number-formatting | 72,181 | <pre><code> wb.Sheets(1).Range("K:AD").NumberFormat = "0"
</code></pre> |
1,818,729 | Java foreach loop: for (Integer i : list) { ... } | <p>When I use JDK5 like below</p>
<pre><code>ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : list) {
//cannot check if already reached last item
}
</code></pre>
<p>on the other hand if I just use an <code>Iterator</code></p>
<pre><code>ArrayList<Integer> list = new ArrayList<Integer>();
for (Iterator i = list.iterator(); i.hasNext();) {
//i can check whether this is last item
if(i.hasNextItem()){
}
}
</code></pre>
<p>How can I check if I've already reached last item with <code>for (Integer i : list) {</code></p> | 1,818,742 | 4 | 0 | null | 2009-11-30 09:22:39.71 UTC | 2 | 2013-11-07 16:31:20.01 UTC | 2013-11-07 16:31:20.01 UTC | null | 1,305,253 | null | 108,869 | null | 1 | 20 | java|iterator|foreach | 187,007 | <p>One way to do that is to use a counter:</p>
<pre><code>ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) {
...
if (--size == 0) {
// Last item.
...
}
}
</code></pre>
<p><em>Edit</em></p>
<p>Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a <code>for</code> loop or the <code>iterator</code>, as everything you win when using the Java5 syntax will be lost in the loop itself...</p>
<pre><code>for (int i = 0; i < list.size(); i++) {
...
if (i == (list.size() - 1)) {
// Last item...
}
}
</code></pre>
<p>or </p>
<pre><code>for (Iterator it = list.iterator(); it.hasNext(); ) {
...
if (!it.hasNext()) {
// Last item...
}
}
</code></pre> |
2,172,614 | Using jQuery .live with toggle event | <p>My code is working, but requiring me to click twice to active my chaining (once for the click event, and once for the toggle event.) What can I do to make it so I only have to click once so that the toggle will automatically occur?</p>
<pre><code> //Show or Hide Comments
$('#showHideComments').live('click', function() {
$('#showHideComments').toggle(function() {
$(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
$("#comments").fadeIn(300);
$("#addComment").fadeIn(300);
},function(){
$(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
$("#comments").fadeOut(300);
$("#addComment").fadeOut(300);
});
});
</code></pre>
<p>Thanks!</p> | 2,172,622 | 4 | 0 | null | 2010-01-31 17:32:52 UTC | 16 | 2013-12-06 12:35:24.98 UTC | 2010-11-10 18:12:58.89 UTC | null | 231,435 | null | 234,240 | null | 1 | 20 | jquery | 21,882 | <p>You cannot use <code>live</code> and <code>toggle</code> together. What you can do, is simply make your own "toggle" of sorts:</p>
<pre><code>$('#showHideComments').live('click', function() {
if($("#addComment").is(':visible')){
$(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
$("#comments, #addComment").fadeOut(300);
} else {
$(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
$("#comments, #addComment").fadeIn(300);
};
});
</code></pre>
<p><code>live</code> is binding to <code>click</code>, however, when <code>toggle</code> is called, it is also bound (normally) on click. You should decide if 'live' is really what you need. For instance, if <code>#showHideComments</code> object is replaced via AJAX during the use of the page, then you need live and my solution. However, if it isn't swapped out and remains the same, just use the inside of your original <code>live</code> function (just the toggle code) and you will be golden.</p> |
49,530,673 | Build Flutter app in release mode for iOS | <p>I have Android Studio with Flutter plugin installed.
Flutter SDK is also installed on my Mac through Android Studio and I know path to it.</p>
<p>I want to run my app in release mode on real iOS device. Not only to hide "slow mode" banner that can be done using this code as I know</p>
<pre><code>new MaterialApp(
debugShowCheckedModeBanner: false,
...
</code></pre>
<p>but also to check how my app works.</p>
<p>I found this instructions <a href="https://flutter.io/ios-release/" rel="noreferrer">https://flutter.io/ios-release/</a> but still can't build app in release mode.</p>
<p>Each time I try to run flutter command in terminal, I got:</p>
<blockquote>
<p>flutter: command not found</p>
</blockquote>
<p>I think that it is because I had installed Flutter SDK from Android Studio and I should update some pathes.
So what are my steps to build flutter app in release mode using Xcode?</p> | 49,532,265 | 7 | 5 | null | 2018-03-28 09:21:32.71 UTC | 14 | 2021-07-14 11:34:04.573 UTC | 2020-08-21 10:43:27.713 UTC | user10563627 | null | null | 1,218,405 | null | 1 | 35 | android-studio|flutter|dart|build|release | 70,728 | <p><strong>Building steps</strong></p>
<p>If you have problems using flutter command in terminal because it is not found - read <em>Configuring steps</em> below.</p>
<p><strong>Step 1</strong></p>
<p>Open terminal, run command</p>
<pre><code>cd /Users/John/myFlutterApp/
</code></pre>
<p>Run </p>
<pre><code>flutter build ios
</code></pre>
<p>Open Xcode and run .xcworkspace file in iOS folder. It should now work smoothly and Slow mode banner should be gone.</p>
<p><strong>Configuring steps</strong></p>
<p><strong>Step 1</strong></p>
<p>Locate folder where flutter is installed on your mac. If it was installed using Android Studio. Just open Android Studio create new flutter project and you will see <strong>Flutter SDK path</strong>.
For example let it be /Users/John/flutter/</p>
<p><strong>Step 2</strong></p>
<p>open terminal on your Mac and run</p>
<pre><code>cd /Users/John/
</code></pre>
<p>As you can see we are now one level up from SDK path</p>
<p><strong>Step 3</strong></p>
<p>run </p>
<pre><code>export PATH=`pwd`/flutter/bin:$PATH
</code></pre>
<p>If you now run <strong>flutter</strong> in terminal you should see list of available params. So you can run </p>
<pre><code>flutter doctor
</code></pre>
<p>To check is everything is fine with installation.
Now flutter command only works for this terminal session. And if you close it and later open it again and run fuller command - you will get error that this command is unknown. So you want to save flutter command to be available even after terminal was closed.</p>
<p><strong>Step 4</strong></p>
<p>run </p>
<pre><code>open ~/.bash_profile
</code></pre>
<p>you will see text editor where you need to paste</p>
<pre><code>export PATH=/Users/John/flutter/bin:$PATH
</code></pre>
<p>save file. If you close terminal now and open it again - you should be able to run flutter command.</p> |
28,516,962 | How WebSocket server handles multiple incoming connection requests? | <p>According to <a href="https://msdn.microsoft.com/en-us/hh969243.aspx" rel="noreferrer">here</a>:</p>
<blockquote>
<p>The HTTP Upgrade header requests that the server <strong><em>switch the
application-layer protocol from HTTP to the WebSocket protocol</em></strong>.</p>
<p>The client handshake established a HTTP-on-TCP connection between IE10
and server. After the server returns its 101 response, the
application-layer protocol switches from HTTP to WebSockets which uses
the previously established TCP connection.</p>
<p><strong><em>HTTP is completely out of the picture</em></strong> at this point. Using the
lightweight WebSocket wire protocol, messages can now be sent or
received by either endpoint at any time.</p>
</blockquote>
<p>So, my understanding is, after the 1st client finished handshake with the server, the server's 80 port will be <strong><em>monopolized</em></strong> by the WebSocket protocol. And the <strong>HTTP is no longer working on 80 port</strong>. </p>
<p>So how could the 2nd client exchange handshake with the server. <strong><em>After all the WebSocket handshake is in HTTP format.</em></strong></p>
<h2>ADD 1</h2>
<p>Thanks for all the answers so far. They are really helpful.</p>
<p>Now I understand that the same server's 80 port is <strong><em>shared</em></strong> by multiple <code>TCP</code> connections. And this sharing is totally OK because <code>TCP</code> connections are identified by a 5-element tuple as <code>Jan-Philip Gehrcke</code> pointed out.</p>
<p>I'd like to add a few thoughts.</p>
<p>Both <code>WebSocket</code> and <code>HTTP</code> are merely application level protocols. <em>Usually</em> they both rely on the <code>TCP</code> protocol as their transport. </p>
<h2>Why choose port 80?</h2>
<p>WebSocket design intentionally choose server's port 80 for <em>both handshake and following communication</em>. I think the designer wants to make WebSocket communication <em>look like</em> normal HTTP communication <strong><em>from the transport level's perspective (i.e. the server port number is still 80)</em></strong>. But according to <code>jfriend00</code>'s answer, this trick doesn't always fool the network infrastructures. </p>
<h2>How does the protocol shift from <em>HTTP</em> to <em>WebSocket</em> happen?</h2>
<p>From RFC 6455 - WebSocket protocol</p>
<blockquote>
<p>Basically it is intended to be as close to just exposing raw TCP to
script as possible given the constraints of the Web. It’s also
designed in such a way that its servers can share a port with HTTP
servers, by having its handshake be a valid HTTP Upgrade request. One
could conceptually use other protocols to establish client-server
messaging, but the intent of WebSockets is to provide a relatively
simple protocol that can coexist with HTTP and deployed HTTP
infrastructure (such as proxies) and that is as close to TCP as is
safe for use with such infrastructure given security considerations,
with targeted additions to simplify usage and keep simple things
simple (such as the addition of message semantics).</p>
</blockquote>
<p>So I think I am wrong on the following statement:</p>
<blockquote>
<p>The handshake request <em>mimic</em> HTTP request but the communication that
follows don't. The handshake request arrives at the server on port 80.
<strong>Because it's 80 port, server will treat it with HTTP protocol. And that's why the WebSocket handshake request must be in HTTP format.</strong>
If so, I think the HTTP protocol <strong>MUST</strong> be modified/extended to
recognize those WebSocket-specific things. Otherwise it won't realize
it should <strong><em>yield to</em></strong> WebSocket protocol.</p>
</blockquote>
<p>I think it should be understood like this:</p>
<blockquote>
<p>WebSocket communication starts with a <strong>valid</strong> HTTP request from
client to server. So it is the server that follows the HTTP protocol
to parse the handshake request and <strong>identify</strong> the begging for
protocol change. And it is the server that switches the protocol. So
HTTP protocol doesn't need to change. HTTP protocol doesn't even need
to know about WebSocket.</p>
</blockquote>
<h2>WebSocket and Comet</h2>
<p>So WebSocket is different from <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29" rel="noreferrer">Comet</a> technologies in that WebSoket doesn't limit itself within the current HTTP realm to solve the bi-directional communication issue.</p>
<h2>ADD 2</h2>
<p>A related question: <a href="https://stackoverflow.com/questions/35387835/how-does-a-browser-establish-connection-with-a-web-server-on-80-port">How does a browser establish connection with a web server on 80 port? Details?</a></p> | 28,518,466 | 4 | 3 | null | 2015-02-14 15:10:00.207 UTC | 50 | 2020-06-04 10:05:02.957 UTC | 2017-05-23 12:10:16.227 UTC | null | -1 | null | 264,052 | null | 1 | 81 | http|websocket|spring-websocket | 62,329 | <p>Your question is great!</p>
<p>I would like to try to answer it from the point of view involving the system calls <code>listen()</code> and <code>accept()</code>. Understanding the behavior of these two calls I think is quite insightful and sufficient to answer your question.</p>
<h3>Spoiler: we can answer your question by looking into how TCP/IP works :-)</h3>
<p>For the core part of the question there really is no difference depending on HTTP or WebSocket. The common ground is TCP over IP. Sending an HTTP request requires an established TCP/IP connection between two parties (I have tried to elaborate on that a bit more <a href="https://stackoverflow.com/a/15270860/145400">here</a>).</p>
<p>In case of a simple web browser / web server scenario</p>
<ol>
<li>first, a TCP connection is established between both (initiated by the client)</li>
<li>then an HTTP request is sent through <em>that</em> TCP connection (from the client to the server)</li>
<li>then an HTTP response is sent through the <em>same</em> TCP connection (in the other direction, from the server to the client)</li>
</ol>
<p>After this exchange, the underlying TCP connection is not needed anymore and usually becomes destroyed/disconnected. In case of a so-called "HTTP Upgrade request" (which can be thought of as: "hey, server! Please upgrade this to a WebSocket connection!"), the underlying TCP connection just goes on living, and the WebSocket communication goes through the very same TCP connection that was created initially (step (1) above).</p>
<p>This hopefully clarifies that the key difference between WebSocket and HTTP is a switch in a high-level protocol (from HTTP toward WebSocket) <strong>without changing the underlying transport channel (a TCP/IP connection).</strong></p>
<h1>Handling multiple IP connection attempts through the same socket, how?</h1>
<p>This is a topic I was once struggling with myself and that many do not understand because it is a little non-intuitive. However, the concept actually is quite simple when one understands how the basic socket-related system calls provided by the operating system are working.</p>
<p>First, one needs to appreciate that an IP connection is <em>uniquely</em> defined by <strong>five</strong> pieces of information:</p>
<p><strong>IP:PORT of Machine A</strong> and <strong>IP:PORT of Machine B</strong> and <strong>the protocol (TCP or UDP)</strong></p>
<p>Now, <em>socket</em> objects are often thought to represent a connection. But that is not entirely true. They may represent different things: they can be active or passive. A socket object in <strong>passive/listen</strong> mode does something pretty special, and that is important to answer your question. </p>
<p><a href="http://linux.die.net/man/2/listen" rel="noreferrer">http://linux.die.net/man/2/listen</a> says:</p>
<blockquote>
<p>listen() marks the socket referred to by sockfd as a passive socket,
that is, as a socket that will be used to accept incoming connection
requests using accept(2).</p>
</blockquote>
<p>That is, we can create a <strong>passive</strong> socket that listens for incoming connection requests. By definition, such a socket can never represent a connection. It just listens for connection requests.</p>
<p>Let's head over to <code>accept()</code> (<a href="http://linux.die.net/man/2/accept" rel="noreferrer">http://linux.die.net/man/2/accept</a>):</p>
<blockquote>
<p>The accept() system call is used with connection-based socket types
(SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection
request on the queue of pending connections for the listening socket,
sockfd, creates a new connected socket, and returns a new file
descriptor referring to that socket. The newly created socket is not
in the listening state. The original socket sockfd is unaffected by
this call.</p>
</blockquote>
<p>Let's digest this carefully, I think this now really answers your question.</p>
<p><code>accept()</code> does not change the state of the <strong>passive</strong> socket created before. It returns an <strong>active (connected)</strong> socket (such a socket then represents the five pieces of information states above -- simple, right?).</p>
<p>Usually, this newly created active socket object is then handed off to another process or thread or just "entity" that takes care of the connection. After <code>accept()</code> has returned this connected socket object, <code>accept()</code> can be called <em>again</em> on the passive socket, and again and again -- something that is known as <strong>accept loop</strong>.</p>
<p>But calling <code>accept()</code> takes time, right? Can't it miss incoming connection requests? There is more essential information in the just-quoted help text: there is a queue of pending connection requests! It is handled automatically by the TCP/IP stack of your operating system.</p>
<p>That means that while <code>accept()</code> can only deal with incoming connection requests <strong>one-by-one</strong>, no incoming request will be missed even when they are incoming at a high rate or (quasi-)simultaneously. One could say that the behavior of <code>accept()</code> is rate-limiting the frequency of incoming connection requests your machine can handle. However, this is a fast system call and in practice, other limitations hit in first -- usually those related to handling all the connections that have been accepted <em>so far</em>.</p> |
36,421,930 | ConnectivityManager.CONNECTIVITY_ACTION deprecated | <p>In Android N, it is mentioned on the official website that "Apps targeting Android N do not receive CONNECTIVITY_ACTION broadcasts". And it is also mentioned that <code>JobScheduler</code> can be used as an alternative. But the <code>JobScheduler</code> doesn't provide exactly the same behavior as <code>CONNECTIVITY_ACTION</code> broadcast. </p>
<p>In my Android application, I was using this broadcast to know the network state of the device. I wanted to know if this state was <code>CONNECTING</code> or <code>CONNECTED</code> with the help of <code>CONNECTIVITY_ACTION</code> broadcast and it was best suited for my requirement. </p>
<p>Now that it is deprecated, can any one suggest me the alternative approach to get current network state?</p> | 36,447,866 | 15 | 7 | null | 2016-04-05 09:12:02.713 UTC | 52 | 2022-09-06 08:59:19.077 UTC | 2016-04-05 10:03:43.83 UTC | null | 5,653,461 | null | 3,531,097 | null | 1 | 115 | android | 59,274 | <p>What will be deprecated is the ability for a backgrounded application to receive network connection state changes.</p>
<p>As <a href="https://stackoverflow.com/users/769265/david-wasser">David Wasser</a> said you can still get notified of connectivity changes if the app component is instantiated (not destroyed) and you have <a href="http://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver,%20android.content.IntentFilter)" rel="noreferrer">registered your receiver programmatically</a> with its context, instead of doing it in the manifest.</p>
<p>Or you can use <a href="http://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback.html" rel="noreferrer">NetworkCallback</a> instead. In particular, you will need to override <a href="http://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback.html#onAvailable(android.net.Network)" rel="noreferrer">onAvailable</a> for connected state changes.</p>
<p>Let me draft a snippet quickly:</p>
<pre><code>public class ConnectionStateMonitor extends NetworkCallback {
final NetworkRequest networkRequest;
public ConnectionStateMonitor() {
networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
}
public void enable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(networkRequest, this);
}
// Likewise, you can have a disable method that simply calls ConnectivityManager.unregisterNetworkCallback(NetworkCallback) too.
@Override
public void onAvailable(Network network) {
// Do what you need to do here
}
}
</code></pre> |
7,442,133 | try / else with return in try block | <p>I came across a strange behavior in python. I could not find information about this in the python help or on SE so here it is:</p>
<pre><code>def divide(x, y):
print 'entering divide'
try:
return x/y
except:
print 'error'
else:
print 'no error'
finally:
print 'exit'
print divide(1, 1)
print divide(1, 0)
</code></pre>
<p>the output:</p>
<pre><code>entering divide
exit
1
entering divide
error
exit
None
</code></pre>
<p>It seems that python will not go inside the <code>else</code> block if a value is returned in the <code>try</code>. However, it will always go in the <code>finally</code> block. I don't really understand why. Can someone help me with this logic?</p>
<p>thanks</p> | 7,442,169 | 5 | 0 | null | 2011-09-16 08:40:39.967 UTC | 16 | 2022-02-16 10:32:19.46 UTC | null | null | null | null | 692,799 | null | 1 | 62 | python|exception-handling | 101,407 | <p><a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="noreferrer">http://docs.python.org/reference/compound_stmts.html#the-try-statement</a></p>
<blockquote>
<p>The optional else clause is executed if and when control flows off the
end of the try clause.</p>
<p>Currently, control “flows off the end” except in the case of an
exception or the execution of a return, continue, or break statement.</p>
</blockquote> |
7,676,951 | How to put spacing between floating divs? | <p>i have a parent div, which can change its size, depending on the available space. Within that div, i have floating divs. Now, i would like to have spacing between these divs, but no space to the parent div (see drawing).</p>
<p><img src="https://i.stack.imgur.com/SjiXb.gif" alt="enter image description here"></p>
<p>Is there a way to do this with CSS?</p>
<p>Thank you</p> | 7,685,713 | 6 | 0 | null | 2011-10-06 15:49:00.267 UTC | 13 | 2020-05-04 00:05:55.277 UTC | 2011-10-06 16:04:28.567 UTC | null | 632,011 | null | 632,011 | null | 1 | 47 | css|html | 133,388 | <p>I found a solution, which at least helps in my situation, it probably is not suitable for other situations:</p>
<p>I give all my green child divs a complete margin:</p>
<pre><code>margin: 10px;
</code></pre>
<p>And for the surrounding yellow parent div i set a negative margin:</p>
<pre><code>margin: -10px;
</code></pre>
<p>I also had to remove any explicit width or height setting for the yellow parent div, otherwise it did not work.</p>
<p>This way, in absolute terms, the child divs are correctly aligned, although the parent yellow div obviously is set off, which in my case is OK, because it will not be visible.</p> |
7,637,022 | Default value in an asp.net mvc view model | <p>I have this model:</p>
<pre><code>public class SearchModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}
</code></pre>
<p>But based on my research and answers here, <code>DefaultValueAttribute</code> does not actually set a default value. But those answers were from 2008, Is there an attribute or a better way than using a private field to set these values to true when passed to the view?</p>
<p>Heres the view anyways:</p>
<pre><code>@using (Html.BeginForm("Search", "Users", FormMethod.Get))
{
<div>
@Html.LabelFor(m => Model.IsMale)
@Html.CheckBoxFor(m => Model.IsMale)
<input type="submit" value="search"/>
</div>
}
</code></pre> | 7,637,050 | 6 | 0 | null | 2011-10-03 15:20:51.367 UTC | 11 | 2020-07-27 22:41:01.077 UTC | null | null | null | null | 400,861 | null | 1 | 74 | asp.net-mvc|asp.net-mvc-3 | 152,518 | <p>Set this in the constructor:</p>
<pre><code>public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
</code></pre>
<p>Then pass it to the view in your GET action:</p>
<pre><code>[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
</code></pre> |
7,203,668 | How permission can be checked at runtime without throwing SecurityException? | <p>I design a function that may get/set a resource from SD and if not found from sd then take it from Asset and if possible write the asset back to SD<br/>
This function may check by method invocation if SD is mounted and accessible...</p>
<pre><code>boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
</code></pre>
<p>My designed function may be used from one app(project) to another (with or without android.permission.WRITE_EXTERNAL_STORAGE)</p>
<p>Then I would like to check if the current application has this particular permission without playing with SecurityException.</p>
<p>Does it exist a "nice" way to consult current defined permissions at runtime ?</p> | 7,203,752 | 11 | 0 | null | 2011-08-26 10:58:11.6 UTC | 37 | 2019-08-16 12:07:16.12 UTC | 2011-08-26 11:04:44.953 UTC | null | 574,131 | null | 574,131 | null | 1 | 99 | android|security|permissions|runtime | 135,403 | <p>You can use <code>Context.checkCallingorSelfPermission()</code> function for this. Here is an example:</p>
<pre><code>private boolean checkWriteExternalPermission()
{
String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
int res = getContext().checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
</code></pre> |
13,800,289 | Configure Git clients, like GitHub for Windows, to not ask for authentication | <p>I have installed GitHub for Windows and also GitExtensions and have multiple versions of git.exe in my path. </p>
<p><img src="https://i.stack.imgur.com/5fw28.png" alt="enter image description here"></p>
<pre><code>C:\Users\Rajat\AppData\Local\GitHub\PortableGit_93e8418133eb85e81a81e5e19c272776524496c6\cmd\git.exe
C:\Users\Rajat\AppData\Local\GitHub\PortableGit_93e8418133eb85e81a81e5e19c272776524496c6\bin\git.exe
E:\cygwin\bin\git.exe
C:\Program Files (x86)\Git\cmd\git.exe
C:\Program Files (x86)\Git\bin\git.exe
</code></pre>
<p>Now, when I do <code>git push origin master</code> with any of the last three <code>git.exe</code>s, it asks for my username. But the Portable Git doesn't ask for username. See the following screenshot:</p>
<p><img src="https://i.stack.imgur.com/hw8n3.png" alt="enter image description here"></p>
<p>The heart-shaped character is just a <code>^C</code> so ignore that.</p>
<p>How is authentication being taken care of in this case? Ultimately I want the last three Gits to not ask for authorization. How's that possible?</p>
<p>I found two extra files in the GitHub's Git but I doubt they matter at all:</p>
<p><img src="https://i.stack.imgur.com/a2dW9.png" alt="enter image description here"></p> | 18,607,931 | 3 | 1 | null | 2012-12-10 11:43:18.787 UTC | 19 | 2018-11-07 21:29:30.397 UTC | 2013-09-04 16:47:54.663 UTC | null | 9,314 | null | 459,384 | null | 1 | 21 | git|github|github-for-windows | 37,000 | <p>For GitHub for Windows itself, <a href="https://stackoverflow.com/users/5728/paul-betts">Paul Betts</a> (<a href="https://github.com/paulcbetts" rel="noreferrer">GitHub staff</a>) gently reminds everyone that <strong>G4W already includes a credential helper</strong> (based on <strong>CryptProtect</strong> and I suppose the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx" rel="noreferrer"><code>CryptProtectData</code> function</a>)<br>
See <a href="https://stackoverflow.com/a/23021315/6309">his answer below</a>.</p>
<p>For those who don't use G4W, read on.</p>
<hr>
<p>To add to my <a href="https://stackoverflow.com/a/13801685/6309">previous answer</a> (when pushing to GitHub through the console/command-line): </p>
<p>A file like <code>~/.netrc</code> (on Unix) or <code>%HOME%/_netrc</code> (on Windows) can help you to <strong>avoid entering your credential for every git push you would make to GitHub</strong>. </p>
<p>You can store as many credentials you need in a <code>netrc</code> file.<br>
(for GitHub or other repo hosting providers)<br>
But:</p>
<ul>
<li>you don't want to store your main GitHub password account</li>
<li>you don't want those in a plain text file.</li>
</ul>
<p>The following sections address those issues:</p>
<hr>
<h2>Enable the <a href="https://github.com/blog/1614-two-factor-authentication" rel="noreferrer">two-factor authentication (2FA) on your GitHub account</a></h2>
<p>(September 3rd, 2013)</p>
<p><strong>Configure 2FA through an application</strong>, always through an app, <em>never</em> through a text SMS, if you can avoid it.</p>
<p>The reason is, through that activation process, you have access to your <strong>two-factor secret key</strong>, which is used to generate the second factor authentication every 30 seconds:</p>
<p><img src="https://i.stack.imgur.com/QLfgU.png" alt="two factor secret string"></p>
<p>That way you can go to <strong>any GAuth (<a href="https://code.google.com/p/google-authenticator/" rel="noreferrer">Google Authenticator</a>) client</strong>, enter that same 2FA secret key, and see the <em>exact</em> same code you would get through SMS message.<br>
Except that, if you don't have phone service, it still works ;)</p>
<p>Of course, the <a href="https://support.google.com/accounts/answer/1066447?hl=en" rel="noreferrer">first client to use is GAuth</a> on your android phone or your iphone.</p>
<p><img src="https://i.stack.imgur.com/0pm1b.png" alt="GAuth on Android"></p>
<p>That means you don't have to wait for an SMS, and you keep your 2FA on your phone.</p>
<p>However, having your secret key allows you to not be limited to a client on your phone.<br>
You can go to any other client, like:</p>
<ul>
<li><a href="http://blog.jcuff.net/2011/09/beautiful-two-factor-desktop-client.html" rel="noreferrer">JAuth</a>, a beautiful two factor desktop client, (<a href="https://github.com/mclamp/JAuth" rel="noreferrer">codeon GitHub</a>)</li>
<li><a href="https://github.com/gbraad/html5-google-authenticator" rel="noreferrer">html5-google-authenticator</a>: a <strong><a href="http://gauth.apps.gbraad.nl/" rel="noreferrer">GAuth Authenticator client web page</a></strong> where you can see your token generated every 30 seconds, like you would see them on your phone or through SMS.</li>
<li>a <a href="https://github.com/rdgreen/LCGoogleApps" rel="noreferrer">desktop system tray</a></li>
<li>a browser extension (like <a href="https://marketplace.firefox.com/app/gauth-authenticator/" rel="noreferrer">gauth-authenticator</a> for FireFox)</li>
</ul>
<p>For all those clients (on your phone with GAuth, or with a desktop client or a web page), you will need your <strong>two-factor secret key</strong>.</p>
<p>If you activated your 2FA through SMS:</p>
<ul>
<li>you don't know your secret key</li>
<li>you can't use any other GAuth client</li>
<li>you are limited to receiving your token through your phone (if you have phone service and/or if you have your phone at all)</li>
</ul>
<hr>
<p>Note: if you have added a key in your Gauth client on Android, without having memorized first said secret key, <a href="http://bryars.eu/2012/02/how-to-add-an-additional-google-authenticator-device/" rel="noreferrer">all is not lost</a>.<br>
(but you need a rooted phone though)</p>
<pre><code>$ adb shell
# sqlite3 /data/data/com.google.android.apps.authenticator/databases/databases
sqlite> select * from accounts;
1|[email protected]|your2factorkey|0|0
sqlite> .quit
#exit
</code></pre>
<hr>
<p>Don't forget to get and then save the associated recovery codes (in the <a href="https://github.com/settings/admin" rel="noreferrer"><code>Account Settings</code> section of your GitHub account</a>):</p>
<p><img src="https://i.stack.imgur.com/6yKeL.png" alt="Recovery code"></p>
<p>(See also the last section about <em>where</em> to save those codes)</p>
<hr>
<h2>Encrypt your <code>_netrc</code> file</h2>
<p>(see the <strong><a href="https://stackoverflow.com/a/18362082/6309">credential helper netrc with git1.8.3+</a></strong>: gpg encryption) </p>
<p>You need to encrypt in that file at least those two credentials:</p>
<pre><code>machine github.com
login username
password xxxx
protocol https
machine gist.github.com
login username
password xxxx
protocol https
</code></pre>
<p>You then keep only a <code>~/.netrc.gpg</code> or <code>%HOME%/_netrc.gpg</code></p>
<p>But, if you enable the new two-factor authentication described above, '<code>xxxx</code>' won't be your GitHub account: see the next section about "Personal Access Token".</p>
<hr>
<h2>Generate a Personal Access Token</h2>
<p>You won't be able to push with your GitHub password if you have activated 2FA.</p>
<p><strong><code>Anonymous access to user/repo.git denied</code></strong></p>
<p>Here is what you would see (the <code>gpg</code> part is because I use the <a href="https://stackoverflow.com/a/18362082/6309"><code>netrc</code> credential helper</a>):</p>
<pre><code>C:\Users\VonC\prog\git\git>git push origin
Using GPG to open %HOME%/_netrc.gpg: [gpg2 --decrypt %HOME%/_netrc.gpg]
You need a passphrase to unlock the secret key for
user: "auser <[email protected]>"
2048-bit RSA key, ID A2EF56, created 2012-09-12 (main key ID DC43D6)
remote: Anonymous access to VonC/git.git denied. <=====
fatal: Authentication failed for 'https://[email protected]/VonC/git/' <=====
</code></pre>
<p>So go to the <strong><a href="https://github.com/settings/developers" rel="noreferrer"><code>Developer</code> section of your GitHub Account</a></strong> (subsection <a href="https://github.com/settings/tokens" rel="noreferrer"><code>Personal access tokens</code></a>), and generate a <strong>Personal Access Token</strong>:</p>
<p><img src="https://i.stack.imgur.com/JiTRj.png" alt="Personal token"></p>
<p>That token <strong>won't require a two-factor authentication</strong>: you can use it as password in your <code>_netrc</code> file, and you will be able to just push to GitHub.</p>
<p>But the difference with your main GitHub account password is:<br>
<strong>You can revoke a personal access token</strong> (and generate a new one), while still keeping your main password unchanged.</p>
<p>If you had encrypted your main GitHub password in your <code>~/.netrc.gpg</code> file, you can replace it with your new personal token:</p>
<pre class="lang-sh prettyprint-override"><code>gpg -d %HOME%\_netrc.gpg | sed "s/yourPassord/YourPersonalAccessToken/g" | gpg -e -r auser --yes -o %HOME%\_netrc.gpg
</code></pre>
<p>In multiple line for readability:</p>
<pre><code>gpg -d %HOME%\_netrc.gpg |
sed "s/yourPassord/YourPersonalAccessToken/g" |
gpg -e -r auser --yes -o %HOME%\_netrc.gpg
</code></pre>
<p>That works even on Windows, with the help of the unix-like <a href="https://github.com/bmatzelle/gow/wiki" rel="noreferrer">GoW (Gnu on Windows)</a> command, which includes <code>sed</code>.</p>
<hr>
<h2>Save your GitHub credentials</h2>
<p>I recommend an online credential storage like <strong><a href="https://lastpass.com/" rel="noreferrer">lastpass.com</a></strong></p>
<p>You need to save:</p>
<ul>
<li>Your GitHub account password</li>
<li>Your 2FA secret key</li>
<li>Your 2FA recovery code</li>
<li>Your personal token </li>
</ul>
<p><img src="https://i.stack.imgur.com/pTWLW.png" alt="LastPass"></p> |
13,843,164 | How do you store static data in your SQL Server Database Project in VS 2012 | <p>I am trying to use the SQL Server Database Project to keep all our table, stored procedure, views etc scripts. I now want a way to be able to keep all our reference (static) data as well. When the tool or project is run it will install all the DB objects and the insert all the reference data.</p>
<p>I found similar articles for vs 2010 but they were using things like Team Edition for Database professionals. </p>
<ul>
<li>Get our DB under source control.</li>
<li>Synchronize our local development DB with latest version in source control.</li>
<li>Work with Visual Studio 2012 and SQL Server 2012</li>
<li>Use .Net tools as far as possible and not something like Redgate (Redgate is great but I don't want to for out for it just yet if I can use tools in VS 2012)</li>
</ul> | 13,994,500 | 1 | 1 | null | 2012-12-12 15:34:16.037 UTC | 15 | 2019-03-10 20:42:36.333 UTC | 2019-03-10 20:42:36.333 UTC | null | 1,127,428 | null | 62,544 | null | 1 | 23 | database|version-control|visual-studio-2012|sql-server-2012 | 8,722 | <p>You can use this approach:</p>
<ul>
<li>Put your reference data into XML files, one per table</li>
<li>Add XML files with reference data to your database project</li>
<li>Use a Post-Deployment script to extract the data from XML and merge it into your tables</li>
</ul>
<p>Here is a more detailed description of each step, illustrated with an example. Let's say that you need to initialize a table of countries that has this structure:</p>
<pre><code>create table Country (
CountryId uniqueidentifier NOT NULL,
CountryCode varchar(2) NOT NULL,
CountryName varchar(254) NOT NULL
)
</code></pre>
<p>Create a new folder called <code>ReferenceData</code> under your database project. It should be a sibling folder of the <code>Schema Objects</code> and <code>Scripts</code>.</p>
<p>Add a new XML file called <code>Country.xml</code> to the <code>ReferenceData</code> folder. Populate the file as follows:</p>
<pre><code><countries>
<country CountryCode="CA" CountryName="Canada"/>
<country CountryCode="MX" CountryName="Mexico"/>
<country CountryCode="US" CountryName="United States of America"/>
</countries>
</code></pre>
<p>Find <code>Script.PostDeployment.sql</code>, and add the following code to it:</p>
<pre><code>DECLARE @h_Country int
DECLARE @xmlCountry xml = N'
:r ..\..\ReferenceData\Country.xml
'
EXEC sp_xml_preparedocument @h_Country OUTPUT, @xmlCountry
MERGE Country AS target USING (
SELECT c.CountryCode, c.CountryName
FROM OPENXML(@h_Country, '/countries/country', 1)
WITH (CountryCode varchar(2), CountryName varchar(254)) as c) AS source (CountryCode, CountryName)
ON (source.CountryCode = target.CountryCode)
WHEN MATCHED THEN
UPDATE SET CountryName = source.CountryName
WHEN NOT MATCHED BY TARGET THEN
INSERT (CountryId, CountryCode, CountryName) values (newid(), source.CountryCode, source.CountryName)
;
</code></pre>
<p>I tried this solution only in VS 2008, but it should be agnostic to your development environment.</p> |
14,064,189 | How to ignorecase when using string.text.contains? | <p>I am trying to figure out how to check if a string contains another while ignoring case using .text.contains.</p>
<p>As it stands right now If I do this:</p>
<pre><code> Dim myhousestring As String = "My house is cold"
If txt.Text.Contains(myhousestring) Then
Messagebox.Show("Found it")
End If
</code></pre>
<p>It will only return a match if it is the exact same case. So if the user typed "my house is cold", it would not be a match. </p>
<p>How can I do this? If it is not possible I could probably just use regex instead with ignorecase. Any help would be appreciated.</p> | 14,064,213 | 9 | 0 | null | 2012-12-28 03:23:18.53 UTC | 2 | 2020-10-10 13:37:12.537 UTC | 2014-11-11 05:44:49.15 UTC | null | 405,180 | null | 1,632,018 | null | 1 | 24 | .net|vb.net|string | 59,570 | <p>According to <a href="http://msdn.microsoft.com/en-us/library/ms224424.aspx">Microsoft</a> you can do case-insensitive searches in strings with <code>IndexOf</code> instead of <code>Contains</code>. So when the result of the <code>IndexOf</code> method returns a value greater than <code>-1</code>, it means the second string is a substring of the first one.</p>
<pre><code>Dim myhousestring As String = "My house is cold"
If txt.Text.IndexOf(myhousestring, 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
Messagebox.Show("Found it")
End If
</code></pre>
<p>You can also use other case-insensitive variants of <a href="http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx">StringComparison</a>.</p> |
14,332,320 | Git no space left on device | <p>I did <strong>git pull --rebase</strong> and I got following error:</p>
<pre><code> error: file write error (No space left on device)
fatal: unable to write sha1 file
fatal: unpack-objects failed
</code></pre>
<p>I have lot of space on my device. Don't know why it is showing this error. </p>
<p>First time I got this error.</p> | 14,332,342 | 8 | 1 | null | 2013-01-15 06:35:41.64 UTC | 4 | 2022-01-26 02:15:32.607 UTC | 2020-05-23 02:35:55.61 UTC | null | 541,136 | null | 1,133,674 | null | 1 | 25 | git|git-rebase|git-pull | 48,781 | <p>You're out of drive space. Delete some <em>unused</em> files from anywhere on your machine. After you've done some housecleaning, you may think about running <code>git gc</code> to have git garbage collect your repository; if you've made lots of changes to git's objects recently - like can happen with a rebase - you can reclaim significant data from git itself. After giving git some breathing room (as gc will need a little wiggle room to copy data to new files as it works), <code>git gc</code> will compact your git repository as much as is possible without losing your repository's history.</p> |
14,235,362 | Mac install and open mysql using terminal | <p>I downloaded the mysql dmg file and went through the wizard to run. Done. I have also started mysql server under system preferences.</p>
<p>The purpose of me doing this is to work through the exercises of my SQL text book. The terminal commands are new to me but I think once I can actually get started, working through the exercises should be OK.</p>
<p>From researching the web the various blogs tell me to navigate to to the mysql folder in the terminal:</p>
<pre><code>/usr/local/mysql
</code></pre>
<p>Fine. Then it gets a little less clear as nearly each article has a different set of instructions on how to proceed. I was fiddling with it yesterday and was prompted for a password - what is the default mysql password?</p>
<p>Could someone give me the steps to get up and running with mysql via the terminal?</p> | 14,235,558 | 12 | 0 | null | 2013-01-09 12:37:49.027 UTC | 50 | 2022-09-12 12:20:39.597 UTC | 2021-08-28 07:40:13.047 UTC | null | 11,573,842 | null | 1,024,586 | null | 1 | 85 | mysql|macos|installation|terminal | 337,119 | <p><em>(Updated for 2017)</em></p>
<p>When you installed MySQL it generated a password for the root user. You can connect using</p>
<pre><code>/usr/local/mysql/bin/mysql -u root -p
</code></pre>
<p>and type in the generated password.</p>
<p>Previously, the <code>root</code> user in MySQL used to not have a password and could only connect from localhost. So you would connect using</p>
<pre><code>/usr/local/mysql/bin/mysql -u root
</code></pre> |
13,832,322 | How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver? | <p>Currently I'm trying to capture a screenshot using the Selenium WebDriver. But I can only obtain the whole page screen shot. However, what I wanted is just to capture a part of the page or perhaps just on specific element based on ID or any specific element locator. (For example, I wish to capture the picture with image id = "Butterfly")</p>
<p>Is there any way to capture a screenshot by selected item or element?</p> | 13,834,607 | 23 | 2 | null | 2012-12-12 03:32:21.743 UTC | 50 | 2021-11-02 14:36:05.23 UTC | 2016-04-06 10:32:20.603 UTC | null | 617,450 | null | 1,713,791 | null | 1 | 90 | selenium|selenium-webdriver|screenshot | 133,141 | <p>We can get the element screenshot by cropping entire page screenshot as below:</p>
<pre class="lang-java prettyprint-override"><code>driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);
</code></pre> |
28,965,847 | How to export specific request to file using postman? | <p>I want to export one specific request from a Postman extension (Chromium) and send it to another developer so that they can import it. How I can do this?</p> | 28,966,615 | 8 | 3 | null | 2015-03-10 14:05:29.547 UTC | 14 | 2022-02-15 08:13:57.237 UTC | 2022-02-04 20:08:43.657 UTC | null | 3,739,391 | null | 2,992,726 | null | 1 | 212 | rest|postman|webapi | 205,189 | <p>To do that you need to leverage the "Collections" feature of Postman. This link could help you: <a href="https://learning.getpostman.com/docs/postman/collections/creating_collections/" rel="noreferrer">https://learning.getpostman.com/docs/postman/collections/creating_collections/</a></p>
<p>Here is the way to do it:</p>
<ul>
<li>Create a collection (within tab "Collections")</li>
<li>Execute your request</li>
<li>Add the request to a collection</li>
<li>Share your collection as a file</li>
</ul> |
43,097,102 | use RxSwift, driver and bind to | <p>I'm the first time to ask a question,I'm learning RxSwift, how to use bind to and driver, what's the difference between of driver and bind to.Anyone else learning RxSwift now.If you are learning RxSwift or Swift or OC,i hope we can be friends and learn from each other.</p> | 43,140,373 | 2 | 1 | null | 2017-03-29 14:54:47.11 UTC | 4 | 2018-10-09 19:45:39.897 UTC | null | null | null | null | 5,813,637 | null | 1 | 28 | rx-swift | 29,057 | <p>@iwillnot response is fine but I will try to improve it with an example:</p>
<p>Imagine you have this code: </p>
<pre><code>let intObservable = sequenceOf(1, 2, 3, 4, 5, 6)
.observeOn(MainScheduler.sharedInstance)
.catchErrorJustReturn(1)
.map { $0 + 1 }
.filter { $0 < 5 }
.shareReplay(1)
</code></pre>
<p>As @iwillnot wrote: </p>
<blockquote>
<p><strong>Driver</strong>
You can read more in detail what the Driver is all about from the documentation. In summary, it simply allows you to rely on these properties:
- Can't error out
- Observe on main scheduler
- Sharing side effects</p>
</blockquote>
<p>if you use <code>Driver</code>, you won't have to specify <code>observeOn</code>, <code>shareReplay</code> nor <code>catchErrorJustReturn</code>.</p>
<p>In summary, the code above is similar to this one using <code>Driver</code>:</p>
<pre><code>let intDriver = sequenceOf(1, 2, 3, 4, 5, 6)
.asDriver(onErrorJustReturn: 1)
.map { $0 + 1 }
.filter { $0 < 5 }
</code></pre>
<p><a href="https://github.com/ReactiveX/RxSwift/issues/275" rel="noreferrer">More details</a> </p> |
9,410,485 | How do I use class helpers to access strict private members of a class? | <p>This is a follow-up question to: <a href="https://stackoverflow.com/questions/9400170/how-to-hide-a-protected-procedure-of-an-object">How to hide a protected procedure of an object?</a><br>
<em>(I'm a bit fuzzy on the whole class helper concept)</em> </p>
<p>Suppose I have an class like:</p>
<pre><code>type
TShy = class(TObject)
strict private
procedure TopSecret;
private
procedure DirtyLaundry;
protected
procedure ResistantToChange;
end;
</code></pre>
<p>I know I can access the private method if I have the source code by adding a descendent class in the same unit.</p>
<p>I have 2 questions:<br>
- How do I employ a class helper to access the <code>strict private</code> member?<br>
- Can I use a class helper in a <strong>separate</strong> unit to access (strict) private members?</p> | 9,410,717 | 2 | 1 | null | 2012-02-23 09:42:41.263 UTC | 8 | 2016-06-11 08:26:37.927 UTC | 2017-05-23 12:09:56.23 UTC | null | -1 | null | 650,492 | null | 1 | 29 | delphi|class-helpers | 6,632 | <p>Up to, and including Delphi 10.0 Seattle, you can use a class helper to access <code>strict protected</code> and <code>strict private</code> members, like this:</p>
<pre><code>unit Shy;
interface
type
TShy = class(TObject)
strict private
procedure TopSecret;
private
procedure DirtyLaundry;
protected
procedure ResistantToChange;
end;
</code></pre>
<p></p>
<pre><code>unit NotShy;
interface
uses
Shy;
type
TNotShy = class helper for TShy
public
procedure LetMeIn;
end;
implementation
procedure TNotShy.LetMeIn;
begin
Self.TopSecret;
Self.DirtyLaundry;
Self.ResistantToChange;
end;
end.
</code></pre>
<p></p>
<pre><code>uses
..., Shy, NotShy;
procedure TestShy;
var
Shy: TShy;
begin
Shy := TShy.Create;
Shy.LetMeIn;
Shy.Free;
end;
</code></pre>
<p>However, starting with Delphi 10.1 Berlin, <strong>this no longer works</strong>! Class helpers can no longer access <code>strict protected</code>, <code>strict private</code> or <code>private</code> members. This "feature" was actually a <strong>compiler bug</strong> that Embarcadero has now fixed in Berlin. You are out of luck.</p> |
49,391,001 | Why does the x86-64 / AMD64 System V ABI mandate a 16 byte stack alignment? | <p>I've read in different places that it is done for "performance reasons", but I still wonder what are the particular cases where performance get improved by this 16-byte alignment. Or, in any case, what were the reasons why this was chosen.</p>
<p><strong>edit</strong>: I'm thinking I wrote the question in a misleading way. I wasn't asking about why the processor does things faster with 16-byte aligned memory, this is explained everywhere in the docs. What I wanted to know instead, is how the enforced 16-byte alignment is better than just letting the programmers align the stack themselves when needed. I'm asking this because from my experience with assembly, the stack enforcement has two problems: it is only useful by less 1% percent of the code that is executed (so in the other 99% is actually overhead); and it is also a very common source of bugs. So I wonder how it really pays off in the end. While I'm still in doubt about this, I'm accepting peter's answer as it contains the most detailed answer to my original question.</p> | 49,397,524 | 1 | 10 | null | 2018-03-20 17:48:44.4 UTC | 10 | 2022-02-03 09:03:26.2 UTC | 2022-02-03 08:13:23.743 UTC | null | 224,132 | null | 309,366 | null | 1 | 19 | assembly|x86-64|memory-alignment|stack-memory|abi | 6,907 | <p>Note that <strong>the current version of the i386 System V ABI used on Linux also requires 16-byte stack alignment</strong><sup>1</sup>. See <a href="https://sourceforge.net/p/fbc/bugs/659/" rel="nofollow noreferrer">https://sourceforge.net/p/fbc/bugs/659/</a> for some history, and my comment on <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=40838#c91" rel="nofollow noreferrer">https://gcc.gnu.org/bugzilla/show_bug.cgi?id=40838#c91</a> for an attempt at summarizing the unfortunate history of how i386 GNU/Linux + GCC accidentally got into a situation where a backwards-incompat change to the i386 System V ABI was the lesser of two evils.</p>
<p>Windows x64 also requires 16-byte stack alignment before a <code>call</code>, presumably for similar motivations as x86-64 System V.</p>
<p>Also, semi-related: x86-64 System V requires that global arrays of 16 bytes and larger be aligned by 16. Same for local arrays of >= 16 bytes or variable size, although that detail is only relevant across functions if you know that you're being passed the address of the start of an array, not a pointer into the middle. (<a href="https://stackoverflow.com/questions/52249333/different-memory-alignment-for-different-buffer-sizes">Different memory alignment for different buffer sizes</a>). It doesn't let you make any extra assumptions about an arbitrary <code>int *</code>.</p>
<hr />
<p><strong>SSE2 is baseline for x86-64</strong>, and making the ABI efficient for types like <code>__m128</code>, and for compiler auto-vectorization, was one of the design goals, I think. The ABI has to define how such args are passed as function args, or by reference.</p>
<p>16-byte alignment is sometimes useful for local variables on the stack (especially arrays), and guaranteeing 16-byte alignment means compilers can get it for free whenever it's useful, even if the source doesn't explicitly request it.</p>
<p><strong>If the stack alignment relative to a 16-byte boundary wasn't known, every function that wanted an aligned local would need an <code>and rsp, -16</code>, and extra instructions to save/restore <code>rsp</code> after an unknown offset to <code>rsp</code> (either <code>0</code> or <code>-8</code>)</strong> e.g. using up <code>rbp</code> for a frame pointer.</p>
<p>Without AVX, memory source operands have to be 16-byte aligned. e.g. <code>paddd xmm0, [rsp+rdi]</code> faults if the memory operand is misaligned. So if alignment isn't known, you'd have to either use <code>movups xmm1, [rsp+rdi]</code> / <code>paddd xmm0, xmm1</code>, or write a loop prologue / epilogue to handle the misaligned elements. For local arrays that the compiler wants to auto-vectorize over, it can simply choose to align them by 16.</p>
<p>Also note that early x86 CPUs (before Nehalem / Bulldozer) had a <code>movups</code> instruction that's slower than <code>movaps</code> even when the pointer does turn out to be aligned. (I.e. unaligned loads/stores on aligned data was extra slow, as well as preventing folding loads into an ALU instruction.) (See <a href="http://agner.org/optimize/" rel="nofollow noreferrer">Agner Fog's optimization guides, microarch guide, and instruction tables</a> for more about all of the above.)</p>
<p>These factors are why a guarantee is more useful than just "usually" keeping the stack aligned. <strong>Being allowed to make code which actually faults on a misaligned stack allows more optimization opportunities.</strong></p>
<p><strong>Aligned arrays also speed up vectorized <code>memcpy</code> / <code>strcmp</code> / whatever</strong> functions that can't <em>assume</em> alignment, but instead check for it and can jump straight to their whole-vector loops.</p>
<p>From <a href="https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI" rel="nofollow noreferrer">a recent version of the x86-64 System V ABI (r252)</a>:</p>
<blockquote>
<p>An array uses the same alignment as its elements, except that a local or global
array variable of length at least 16 bytes or a C99 variable-length array variable
always has alignment of at least 16 bytes.<sup>4</sup></p>
</blockquote>
<blockquote>
<p><sup>4</sup> The alignment requirement allows the use of SSE instructions when operating on the array.
The compiler cannot in general calculate the size of a variable-length array (VLA), but it is expected
that most VLAs will require at least 16 bytes, so it is logical to mandate that VLAs have at
least a 16-byte alignment.</p>
</blockquote>
<p>This is a bit aggressive, and mostly only helps when functions that auto-vectorize can be inlined, but usually there are other locals the compiler can stuff into any gaps so it doesn't waste stack space. And doesn't waste instructions as long as there's a known stack alignment. (Obviously the ABI designers could have left this out if they'd decided not to require 16-byte stack alignment.)</p>
<hr />
<h3>Spill/reload of <code>__m128</code></h3>
<p>Of course, it makes it free to do <code>alignas(16) char buf[1024];</code> or other cases where the source <em>requests</em> 16-byte alignment.</p>
<p>And there are also <code>__m128</code> / <code>__m128d</code> / <code>__m128i</code> locals. The compiler may not be able to keep all vector locals in registers (e.g. spilled across a function call, or not enough registers), so it needs to be able to spill/reload them with <code>movaps</code>, or as a memory source operand for ALU instructions, for efficiency reasons discussed above.</p>
<p>Loads/stores that actually are split across a cache-line boundary (64 bytes) have significant latency penalties, and also minor throughput penalties on modern CPUs. The load needs data from 2 separate cache lines, so it takes two accesses to the cache. (And potentially 2 cache misses, but that's rare for stack memory.)</p>
<p>I think <code>movups</code> already had that cost baked in for vectors on older CPUs where it's expensive, but it still sucks. Spanning a 4k page boundary is <em>much</em> worse (on CPUs before Skylake), with a load or store taking ~100 cycles if it touches bytes on both sides of a 4k boundary. (Also needs 2 TLB checks.) <strong>Natural alignment makes splits across any wider boundary impossible</strong>, so 16-byte alignment was sufficient for everything you can do with SSE2.</p>
<hr />
<p><strong><a href="http://en.cppreference.com/w/c/types/max_align_t" rel="nofollow noreferrer"><code>max_align_t</code></a> has 16-byte alignment</strong> in the x86-64 System V ABI, because of <code>long double</code> (10-byte/80-bit x87). It's defined as padded to 16 bytes for some weird reason, unlike in 32-bit code where <code>sizeof(long double) == 10</code>. x87 10-byte load/store is quite slow anyway (like 1/3rd the load throughput of <code>double</code> or <code>float</code> on Core2, 1/6th on P4, or 1/8th on K8), but maybe cache-line and page split penalties were so bad on older CPUs that they decided to define it that way. I think on modern CPUs (maybe even Core2) looping over an array of <code>long double</code> would be no slower with packed 10-byte, because the <code>fld m80</code> would be a bigger bottleneck than a cache-line split every ~6.4 elements.</p>
<p>Actually, the ABI was defined before silicon was available to benchmark on (<a href="https://stackoverflow.com/questions/4429398/why-does-windows64-use-a-different-calling-convention-from-all-other-oses-on-x86/35619528#35619528">back in ~2000</a>), but those K8 numbers are the same as K7 (32-bit / 64-bit mode is irrelevant here). Making <code>long double</code> 16-byte does make it possible to copy a single one with <code>movaps</code>, even though you can't do anything with it in XMM registers. (Except manipulate the sign bit with <code>xorps</code> / <code>andps</code> / <code>orps</code>.)</p>
<p>Related: this <code>max_align_t</code> definition means that <code>malloc</code> always returns 16-byte aligned memory in x86-64 code. This lets you get away with using it for SSE aligned loads like <code>_mm_load_ps</code>, but such code can break when compiled for 32-bit where <code>alignof(max_align_t)</code> is only 8. (Use <code>aligned_alloc</code> or whatever.)</p>
<hr />
<p><strong>Other ABI factors</strong> include passing <code>__m128</code> values on the stack (after xmm0-7 have the first 8 float / vector args). It makes sense to require 16-byte alignment for vectors in memory, so they can be used efficiently by the callee, and stored efficiently by the caller. Maintaining 16-byte stack alignment at all times makes it easy for functions that need to align some arg-passing space by 16.</p>
<p><strong>There are types like <code>__m128</code> that the ABI guarantees have 16-byte alignment</strong>. If you define a local and take its address, and pass that pointer to some other function, that local needs to be sufficiently aligned. So maintaining 16-byte stack alignment goes hand in hand with giving some types 16-byte alignment, which is obviously a good idea.</p>
<p>These days, it's nice that <code>atomic<struct_of_16_bytes></code> can cheaply get 16-byte alignment, so <code>lock cmpxchg16b</code> doesn't ever cross a cache line boundary. For the really rare case where you have an atomic local with automatic storage, and you pass pointers to it to multiple threads...</p>
<hr />
<h3>Footnote 1: 32-bit Linux</h3>
<p>Not all 32-bit platforms broke backwards compatibility with existing binaries and hand-written asm the way Linux did; some <a href="https://mail-index.netbsd.org/port-i386/2012/12/30/msg002975.html" rel="nofollow noreferrer">like i386 NetBSD</a> still only use the historical 4-byte stack alignment requirement from the original version of the i386 SysV ABI.</p>
<p>The historical 4-byte stack alignment was also insufficient for efficient 8-byte <code>double</code> on modern CPUs. Unaligned <code>fld</code> / <code>fstp</code> are generally efficient except when they cross a cache-line boundary (like other loads/stores), so it's not horrible, but naturally-aligned is nice.</p>
<p>Even before 16-byte alignment was officially part of the ABI, GCC used to enable <code>-mpreferred-stack-boundary=4</code> (2^4 = 16-bytes) on 32-bit. This currently assumes the incoming stack alignment is 16 bytes (even for cases that will fault if it's not), as well as preserving that alignment. I'm not sure if historical gcc versions used to try to preserve stack alignment without depending on it for correctness of SSE code-gen or <code>alignas(16)</code> objects.</p>
<p>ffmpeg is one well-known example that depends on the compiler to give it stack alignment: <a href="https://stackoverflow.com/questions/672461/what-is-stack-alignment">what is "stack alignment"?</a>, e.g. on 32-bit Windows.</p>
<p>Modern gcc still emits code at the top of <code>main</code> to align the stack by 16 (even on Linux where the ABI guarantees that the kernel starts the process with an aligned stack), but not at the top of any other function. You could use <code>-mincoming-stack-boundary</code> to tell gcc how aligned it should assume the stack is when generating code.</p>
<p>Ancient gcc4.1 didn't seem to really respect <code>__attribute__((aligned(16)))</code> or <code>32</code> for automatic storage, i.e. it doesn't bother aligning the stack any extra <a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5IILERyAgGoAZqlRKOAdj4AGAIJKjSgPommBOXgBGIgpjNQmDPMBaZ0EAMxcAlP6V0UWsGTECOAFYeABZIgBEOLz19bQSkjgMM/QA3VDx0JUwADwIIWXlFVXUAKl9E5LwWZWsmYghfTR0s4yVyhWU1DUFNLzjOvh1aADpdUiVdGdSl9IMe4tLuADZBOpX9AHp9nrMLK1t7RwhnV3dPWk3/DtzmAjxQpUblbJGx2nqsw49a5uJiCbx%2BJTPCxvMKfJRFH7zf6rYzETAEMQsJF7JYGKS%2BRjSCJSUgsaS6EmoaQAYX4/F6onEYW4XloJII5PxBIA1iAvF4pvyhcKRZtCVJoiSALZ0XSzMlSCmkKlSEmCECzDmK/GkOCwGCIFCoKUABxhZAoEDQpvNIGA0VoXFIKje9mI6og1k5pGsjVaAE9pGzSNapZgmgB5FgMQPa0hYKWsYChb34NGKPDZTDquPFTDIOySKTBz6YBjeqwy4s65hsFB03iMGzqyAE1Am16oFg5pQAWgA6s4GH2I14%2B1KfOPBIJMFw1YyJHQCeWpMTSd6VUUABybXubaJKYDIZBKaJTaZcJQQXCEEiaLisubU41m0LEe%2Bsjq03j8dmc/ykLy/KCiKoH8mKK6SqQMoRPKG7SGqGqkFqFIEnqhrWq%2BmAWpQmG2sgtbAJscrOq62Eel6ca%2BiwAZBiSobhgQUYxqmmCJmwKZxmm%2BavFmOZKnmBb2HR5BNGWFbEHgVZssuSb1j%2BjYuNYLbtMqHZ4F2Oa9kUJ59oODDDiOY69hOc5CAuki0MuRIkgqSqbjue4HgRSZKJsMwzFeN5EO%2BLL0Eoz42m%2BH4Qt%2BfC8H%2B2oAQgmBMFgxCUNZErSiAsHrnGKqIZq/48nyApgWBEHSF4tnwaqyH/rqBoQEgeFvuQuEvraeDHrQW6kQwboUd61G0dWIbGmGkbRrGSoJkmnFjXg6a8dm3qCYWImliuSqVnRsl1pwCkCEpKltupmnSNpJ69qO46tMgCCJHECCggA7mWw69ioLCoL2WbENYqAzr2oJSuOPjzmIi5WeKa52ZS0jbru%2B4fMeShtR5uhefgPkfv5gVYb5D5eF%2BDY8JFqG5cBBWgeKUEyrQJEQ8qCFCEhKFcuKZk05lFVRQSH2CBpZLREAA%3D%3D" rel="nofollow noreferrer">in this example on Godbolt</a>, so old gcc has kind of a checkered past when it comes to stack alignment. I think the change of the official Linux ABI to 16-byte alignment happened as a de-facto change first, not a well-planned change. I haven't turned up anything official on when the change happened, but somewhere between 2005 and 2010 I think, after x86-64 became popular and the x86-64 System V ABI's 16-byte stack alignment proved useful.</p>
<p>At first it was a change to GCC's code-gen to use more alignment than the ABI required (i.e. using a stricter ABI for gcc-compiled code), but later it was written in to the version of the i386 System V ABI maintained at <a href="https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI" rel="nofollow noreferrer">https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI</a> (which is official for Linux at least).</p>
<hr />
<p><a href="https://stackoverflow.com/questions/51498309/why-does-main-initialize-stack-frame-when-there-are-no-variables/51498580?noredirect=1#comment89981401_51498580">@MichaelPetch and @ThomasJager report</a> that gcc4.5 may have been the first version to have <code>-mpreferred-stack-boundary=4</code> for 32-bit as well as 64-bit. gcc4.1.2 and gcc4.4.7 on Godbolt appear to behave that way, so maybe the change was backported, or Matt Godbolt configured old gcc with a more modern config.</p> |
32,931,716 | ASP.NET Core Dependency Injection with Multiple Constructors | <p>I have a tag helper with multiple constructors in my ASP.NET Core application. This causes the following error at runtime when ASP.NET 5 tries to resolve the type:</p>
<blockquote>
<p>InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'MyNameSpace.MyTagHelper'. There should only be one applicable constructor.</p>
</blockquote>
<p>One of the constructors is parameterless and the other has some arguments whose parameters are not registered types. I would like it to use the parameterless constructor.</p>
<p>Is there some way to get the ASP.NET 5 dependency injection framework to select a particular constructor? Usually this is done through the use of an attribute but I can't find anything.</p>
<p>My use case is that I'm trying to create a single class that is both a TagHelper, as well as a HTML helper which is totally possible if this problem is solved.</p> | 32,937,952 | 4 | 4 | null | 2015-10-04 08:54:00.753 UTC | 8 | 2021-09-16 11:14:55.24 UTC | 2019-06-05 09:36:36.957 UTC | null | 1,212,017 | null | 1,212,017 | null | 1 | 66 | asp.net|dependency-injection|asp.net-core|asp.net-core-mvc | 59,087 | <p>Illya is right: the built-in resolver doesn't support types exposing multiple constructors... but nothing prevents you from registering a delegate to support this scenario:</p>
<pre><code>services.AddScoped<IService>(provider => {
var dependency = provider.GetRequiredService<IDependency>();
// You can select the constructor you want here.
return new Service(dependency, "my string parameter");
});
</code></pre>
<p><strong>Note:</strong> support for multiple constructors was added in later versions, as indicated in the other answers. Now, the DI stack will happily choose the constructor with the most parameters it can resolve. For instance, if you have 2 constructors - one with 3 parameters pointing to services and another one with 4 - it will prefer the one with 4 parameters.</p> |
45,984,345 | How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo) | <p>I know how to turn on/off wifi hot spot using reflection in android using below method.</p>
<pre><code>private static boolean changeWifiHotspotState(Context context,boolean enable) {
try {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,
Boolean.TYPE);
method.setAccessible(true);
WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null;
boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable);
return isSuccess;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
</code></pre>
<p><strong>But the above method is not working Android 8.0(Oreo).</strong> <br><br>
When I execute above method in Android 8.0, I am getting below statement in logcat.</p>
<pre><code>com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true
</code></pre>
<p>Is there any other way to on/off hotspot on android 8.0</p> | 45,996,578 | 3 | 3 | null | 2017-08-31 14:48:09.133 UTC | 9 | 2019-09-19 07:51:00.15 UTC | 2017-10-11 03:20:45.67 UTC | null | 1,033,581 | null | 4,349,688 | null | 1 | 19 | android|android-wifi|hotspot|android-8.0-oreo | 28,561 | <p>Finally I got the solution.
Android 8.0, they provided public api to turn on/off hotspot. <a href="https://developer.android.com/reference/android/net/wifi/WifiManager.html#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)" rel="noreferrer">WifiManager</a></p>
<p><strong>Below is the code to turn on hotspot</strong></p>
<pre><code>private WifiManager.LocalOnlyHotspotReservation mReservation;
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
Log.d(TAG, "Wifi Hotspot is on now");
mReservation = reservation;
}
@Override
public void onStopped() {
super.onStopped();
Log.d(TAG, "onStopped: ");
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.d(TAG, "onFailed: ");
}
}, new Handler());
}
private void turnOffHotspot() {
if (mReservation != null) {
mReservation.close();
}
}
</code></pre>
<p><code>onStarted(WifiManager.LocalOnlyHotspotReservation reservation)</code> method will be called if hotspot is turned on.. Using <code>WifiManager.LocalOnlyHotspotReservation</code> reference you call <code>close()</code> method to <strong>turn off hotspot</strong>.</p>
<p><strong>Note:</strong>
To turn on hotspot, the <code>Location(GPS)</code> should be enabled in the device. Otherwise, it will throw <code>SecurityException</code></p> |
19,527,564 | Mongo: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 | <p>When I try to run mongo in shell in ubuntu or open rockmongo I see this error: </p>
<pre><code>couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
</code></pre>
<p>What's the reason? I tried to reinstall mongo but this didn't help. When I type <code>sudo apt-get purge mongodb-10gen</code> returned error is</p>
<pre><code>E: Sub-process /usr/bin/dpkg returned an error code (1)
</code></pre>
<p>I tried this:</p>
<ul>
<li>first remove line about mongo in /etc/apt/sources.list</li>
<li><p>run this commands:</p>
<p><code>sudo dpkg pr mongofb-10gen</code>
<code>sudo apt-get -f install</code>
<code>sudo apt-get upadte</code>
<code>sudo apt-get upgrade</code></p></li>
<li><p>then <code>sudo apt-get purge mongodb-10gen</code> is successful</p></li>
<li><p>at the end:</p>
<p><code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10</code></p></li>
<li><p>add deb <a href="http://downloads-distro.mongodb.org/repo/ubuntu-upstart">http://downloads-distro.mongodb.org/repo/ubuntu-upstart</a> dist 10gen
in /etc/apt/sources.list</p>
<p><code>sudo apt-get update</code>
<code>sudo apt-get install mongodb-10gen</code></p></li>
</ul>
<p>Then when I try to start mongo i saw the same error. :o</p> | 19,527,974 | 6 | 3 | null | 2013-10-22 20:22:17.953 UTC | 12 | 2016-09-15 09:13:55.287 UTC | 2013-10-22 20:31:58.953 UTC | null | 1,560,062 | null | 842,692 | null | 1 | 19 | linux|mongodb|ubuntu | 58,512 | <p>I assume that you followed the steps, outlined <a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/" rel="noreferrer">here</a>.</p>
<p>Most probably you have a problem with mongo lock (or at least I had it once while installing on ubuntu). I solved it with the following commands:</p>
<pre><code>sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart
</code></pre>
<p><strong>P.S.</strong> I by myself recently experienced this problem when I was updating my <code>amazon ec2</code> instance. I have not properly shut down mongo before doing this and this resulted in a problem with mongo lock.</p> |
24,827,964 | Browserify with twitter bootstrap | <p>There are many similar questions including answers here on stack overflow, but none of them have worked for me, so here I am asking you guys. I appreciate everyone's time.</p>
<p>I recently started using gulp with browserify, and that works great.
I then tried to use browserify for the front-end using: Backbone and Bootstrap3.</p>
<p>things are appearing to work, until I try to require the js file that comes with Bootstrap. I get an error in my chrome tools stating: jQuery is undefined.</p>
<p>I have attempted to shim it in, but I am very confused by the shim. I am using jQuery 2.1.1, so I should not need to shim jQuery, but it exists in the shim now, as I was desperate and trying everything. Here is my package.json and my main.js file:</p>
<p>--------------package.json------------------</p>
<pre><code>{
"name": "gulp-backbone",
"version": "0.0.0",
"description": "Gulp Backbone Bootstrap",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rob Luton",
"license": "ISC",
"devDependencies": {
"jquery": "^2.1.1",
"backbone": "^1.1.2",
"browserify": "^4.2.1",
"gulp": "^3.8.6",
"vinyl-source-stream": "^0.1.1",
"gulp-sass": "^0.7.2",
"gulp-connect": "^2.0.6",
"bootstrap-sass": "^3.2.0",
"browserify-shim": "^3.6.0"
},
"browser": {
"bootstrap": "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js",
"jQuery": "./node_modules/jquery/dist/jquery.min.js"
},
"browserify": {
"transform": ["browserify-shim"]
},
"browserify-shim": {
"jquery": "global:jQuery",
"bootstrap": {
"depends": [
"jQuery"
]
}
}
}
</code></pre>
<p>------------------------- main.js ----------------------</p>
<pre><code>var shim = require('browserify-shim');
$ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var bootstrap = require('bootstrap');
/* the following logs fine if I comment out the bootstrap require, otherwise I get 'jQuery undefined' */
console.log(Backbone);
$(function() {
alert('jquery works');
});
</code></pre> | 24,834,257 | 4 | 2 | null | 2014-07-18 14:54:02.737 UTC | 25 | 2017-11-18 03:58:32.63 UTC | null | null | null | null | 1,250,629 | null | 1 | 37 | javascript|twitter-bootstrap-3|browserify|browserify-shim | 24,521 | <p>You shouldn't need to shim jquery that way if you've installed it with npm. The following works for a project I've been writing:</p>
<p>I've also learned that using npm for bootstrap is kind of a PITA. I've been using bower to install and maintain certain front-end components when they need to be shimmed like this.</p>
<p>package.json:</p>
<pre><code>{
"name": "...",
"version": "0.0.1",
"description": "...",
"repository": {
"type": "git",
"url": "..."
},
"browser": {
"d3js": "./bower_components/d3/d3.min.js",
"select2": "./bower_components/select2/select2.min.js",
"nvd3js": "./bower_components/nvd3/nv.d3.min.js",
"bootstrap": "./node_modules/bootstrap/dist/js/bootstrap.js"
},
"browserify": {
"transform": [
"browserify-shim",
"hbsfy"
]
},
"browserify-shim": {
"d3js": {
"exports": "d3",
"depends": [
"jquery:$"
]
},
"bootstrap": {
"depends": [
"jquery:jQuery"
]
},
"select2": {
"exports": null,
"depends": [
"jquery:$"
]
},
"nvd3js": {
"exports": "nv",
"depends": [
"jquery:$",
"d3js:d3"
]
}
},
"devDependencies": {
"browserify-shim": "~3.4.1",
"browserify": "~3.36.0",
"coffeeify": "~0.6.0",
"connect": "~2.14.3",
"gulp-changed": "~0.3.0",
"gulp-imagemin": "~0.1.5",
"gulp-notify": "~1.2.4",
"gulp-open": "~0.2.8",
"gulp": "~3.6.0",
"hbsfy": "~1.3.2",
"vinyl-source-stream": "~0.1.1",
"gulp-less": "~1.2.3",
"bower": "~1.3.3",
"cssify": "~0.5.1",
"gulp-awspublish": "0.0.16",
"gulp-util": "~2.2.14",
"gulp-rename": "~1.2.0",
"gulp-s3": "git+ssh://[email protected]/nkostelnik/gulp-s3.git",
"gulp-clean": "~0.2.4",
"process": "~0.7.0"
},
"dependencies": {
"backbone": "~1.1.2",
"jquery": "~2.1.0",
"lodash": "~2.4.1",
"d3": "~3.4.8",
"rickshaw": "~1.4.6",
"datejs": "~1.0.0-beta",
"moment": "~2.7.0"
}
}
</code></pre>
<p>js:</p>
<pre><code>$ = jQuery = require('jquery');
var _ = require('lodash');
var Rickshaw = require('rickshaw');
var d3 = require('d3js');
var nvd3 = require('nvd3js');
var moment = require('moment');
require('datejs');
require('select2');
var bootstrap = require('bootstrap');
console.log(bootstrap)
</code></pre>
<p>Also - one sometimes useful thing is to have browserify-shim output its diagnostics. This is what my browserify.js task looks like:</p>
<pre><code>var browserify = require('browserify');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var process = require('process');
process.env.BROWSERIFYSHIM_DIAGNOSTICS=1;
var hbsfy = require('hbsfy').configure({
extensions: ['html']
});
gulp.task('browserify', ['images', 'less'], function(){
return browserify({
transform: ['hbsfy', 'cssify'],
entries: ['./src/javascript/app.js'],
})
.bundle({debug: true})
.on('error', handleErrors)
.pipe(source('app.js'))
.pipe(gulp.dest('./build/'));
});
</code></pre> |
24,836,526 | Why C++11 in-class initializer cannot use parentheses? | <p>For example, I cannot write this:</p>
<pre><code>class A
{
vector<int> v(12, 1);
};
</code></pre>
<p>I can only write this:</p>
<pre><code>class A
{
vector<int> v1{ 12, 1 };
vector<int> v2 = vector<int>(12, 1);
};
</code></pre>
<p>What's the consideration for the differences in C++11 language design?</p> | 24,837,067 | 2 | 2 | null | 2014-07-19 03:44:44.293 UTC | 16 | 2022-02-20 08:41:12.1 UTC | 2014-08-03 17:23:07.123 UTC | null | 2,581,872 | null | 1,941,113 | null | 1 | 36 | c++|c++11 | 4,556 | <p>One possible reason is that allowing parentheses would lead us back to the <a href="https://en.wikipedia.org/wiki/Most_vexing_parse">most vexing parse</a> in no time. Consider the two types below:</p>
<pre><code>struct foo {};
struct bar
{
bar(foo const&) {}
};
</code></pre>
<p>Now, you have a data member of type <code>bar</code> that you want to initialize, so you define it as</p>
<pre><code>struct A
{
bar B(foo());
};
</code></pre>
<p>But what you've done above is declare a function named <code>B</code> that returns a <code>bar</code> object by value, and takes a single argument that's a function having the signature <code>foo()</code> (returns a <code>foo</code> and doesn't take any arguments).</p>
<p>Judging by the number and frequency of questions asked on StackOverflow that deal with this issue, this is something most C++ programmers find surprising and unintuitive. Adding the new <em>brace-or-equal-initializer</em> syntax was a chance to avoid this ambiguity and start with a clean slate, which is likely the reason the C++ committee chose to do so.</p>
<pre><code>bar B{foo{}};
bar B = foo();
</code></pre>
<p>Both lines above declare an object named <code>B</code> of type <code>bar</code>, as expected.</p>
<hr>
<p>Aside from the guesswork above, I'd like to point out that you're doing two vastly different things in your example above.</p>
<pre><code>vector<int> v1{ 12, 1 };
vector<int> v2 = vector<int>(12, 1);
</code></pre>
<p>The first line initializes <code>v1</code> to a vector that contains two elements, <code>12</code> and <code>1</code>. The second creates a vector <code>v2</code> that contains <code>12</code> elements, each initialized to <code>1</code>. </p>
<p>Be careful of this rule - if a type defines a constructor that takes an <code>initializer_list<T></code>, then that constructor is <em>always</em> considered first when the initializer for the type is a <em>braced-init-list</em>. The other constructors will be considered only if the one taking the <code>initializer_list</code> is not viable.</p> |
1,115,940 | Drawing Flame Fractals | <p>I am looking for information on how to draw flame fractals from googling around I could not find much, either pages explain how to use third party tools or way too complicated for me to grasp. Anyone know how/why they work? or point me in the direction of not overly complicated implementations?</p> | 1,244,011 | 5 | 0 | null | 2009-07-12 12:20:42.47 UTC | 9 | 2017-11-25 18:31:10.78 UTC | 2017-11-25 18:31:10.78 UTC | null | 4,099,593 | null | 89,904 | null | 1 | 11 | fractals | 6,314 | <p>I have written a beamer presentation that covers the basics in flame fractals:</p>
<p><a href="https://www.math.upenn.edu/~peal/files/Fractals[2009]Beamer[Eng]-PAXINUM.pdf" rel="nofollow noreferrer">https://www.math.upenn.edu/~peal/files/Fractals[2009]Beamer[Eng]-PAXINUM.pdf</a></p>
<p>All images are done from my java implementation of the flame algorithm.</p>
<p>The source code can be found here:</p>
<p><a href="http://sourceforge.net/projects/flamethyst/" rel="nofollow noreferrer">http://sourceforge.net/projects/flamethyst/</a></p>
<p>I believe that the pdf <a href="http://flam3.com/flame_draves.pdf" rel="nofollow noreferrer">http://flam3.com/flame_draves.pdf</a> together with the implementation in java above should get you a long way.</p> |
1,318,108 | CSS: limit element to 1 line | <p>I want to limit a element to display only 1 line of text, with the remainder hidden (overflow:hidden), without setting a specific height. Is this possible with just CSS? </p> | 1,318,119 | 5 | 0 | null | 2009-08-23 08:57:01.877 UTC | 9 | 2021-11-05 17:08:14.98 UTC | 2012-12-24 10:06:00.73 UTC | null | 745,188 | null | 118,547 | null | 1 | 57 | css | 64,499 | <p>It is possible:</p>
<pre><code>element (white-space: nowrap; overflow: scroll;)
</code></pre>
<p>Text parsed as HTML or XML is tokenized, which means all runs of whitespace are collapsed to a single space character. This means you will have a single line of text unless you specify something in addition to the overflow declaration that could cause your text to wrap.</p>
<p>EDIT: I failed to include the necessary write-space: nowrap property, otherwise the default is that a container will scroll vertically opposed to horizontally.</p> |
308,019 | jQuery slideUp().remove() doesn't seem to show the slideUp animation before remove occurs | <p>I have this line of JavaScript and the behavior I am seeing is that the <code>selectedLi</code> instantly disappears without "sliding up". This is not the behavior that I expected.</p>
<p>What should I be doing so that the <code>selectedLi</code> slides up before it is removed?</p>
<pre><code>selectedLi.slideUp("normal").remove();
</code></pre> | 308,034 | 5 | 0 | null | 2008-11-21 06:11:07.607 UTC | 16 | 2016-07-03 19:12:03.66 UTC | null | null | null | spoon16 | 3,957 | null | 1 | 99 | javascript|jquery|animation | 56,537 | <p>Might be able to fix it by putting the call to remove in a callback arg to slideUp? </p>
<p>e.g </p>
<pre><code>selectedLi.slideUp("normal", function() { $(this).remove(); } );
</code></pre> |
520,083 | C# lambda - curry usecases | <p>I read <a href="http://jacobcarpenter.wordpress.com/2008/01/02/c-abuse-of-the-day-functional-library-implemented-with-lambdas/" rel="noreferrer">This article</a> and i found it interesting.</p>
<p>To sum it up for those who don't want to read the entire post. The author implements a higher order function named Curry like this (refactored by me without his internal class):</p>
<pre><code> public static Func<T1, Func<T2, TResult>>
Curry<T1, T2, TResult>(this Func<T1, T2, TResult> fn)
{
Func<Func<T1, T2, TResult>, Func<T1, Func<T2, TResult>>> curry =
f => x => y => f(x, y);
return curry(fn);
}
</code></pre>
<p>That gives us the ability to take an expression like F(x, y)
eg. </p>
<pre><code>Func<int, int, int> add = (x, y) => x + y;
</code></pre>
<p>and call it in the F.Curry()(x)(y) manner;</p>
<p>This part i understood and i find it cool in a geeky way. What i fail to wrap my head around is the practical usecases for this approach. When and where this technique is necessary and what can be gained from it?</p>
<p>Thanks in advance.</p>
<p>Edited:
After the initial 3 responses i understand that the gain would be that in some cases when we create a new function from the curried some parameters are not re evalued.
I made this little test in C# (keep in mind that i'm only interested in the C# implementation and not the curry theory in general):</p>
<pre><code>public static void Main(string[] args)
{
Func<Int, Int, string> concat = (a, b) => a.ToString() + b.ToString();
Func<Int, Func<Int, string>> concatCurry = concat.Curry();
Func<Int, string> curryConcatWith100 = (a) => concatCurry(100)(a);
Console.WriteLine(curryConcatWith100(509));
Console.WriteLine(curryConcatWith100(609));
}
public struct Int
{
public int Value {get; set;}
public override string ToString()
{
return Value.ToString();
}
public static implicit operator Int(int value)
{
return new Int { Value = value };
}
}
</code></pre>
<p>On the 2 consecutive calls to curryConcatWith100 the ToString() evaluation for the value 100 is called twice (once for each call) so i dont see any gain in evaluation here. Am i missing something ?</p> | 520,101 | 6 | 0 | null | 2009-02-06 12:16:14.567 UTC | 11 | 2012-08-30 23:18:54.37 UTC | 2009-02-06 13:05:32.783 UTC | AZ | 35,128 | AZ | 35,128 | null | 1 | 12 | c#|.net|lambda | 6,560 | <p>Its easier to first consider fn(x,y,z). This could by curried using fn(x,y) giving you a function that only takes one parameter, the z. Whatever needs to be done with x and y alone can be done and stored by a closure that the returned function holds on to.</p>
<p>Now you call the returned function several times with various values for z without having to recompute the part the required x and y.</p>
<p><strong>Edit:</strong></p>
<p>There are effectively two reasons to curry.</p>
<br />
<h2>Parameter reduction</h2>
<p>As Cameron says to convert a function that takes say 2 parameters into a function that only takes 1. The result of calling this curried function with a parameter is the same as calling the original with the 2 parameters.</p>
<p>With Lambdas present in C# this has limited value since these can provide this effect anyway. Although it you are use C# 2 then the Curry function in your question has much greater value.<br />
<br /></p>
<h2>Staging computation</h2>
<p>The other reason to curry is as I stated earlier. To allow complex/expensive operations to be staged and re-used several times when the final parameter(s) are supplied to the curried function.</p>
<p>This type of currying isn't truely possible in C#, it really takes a functional language that can natively curry any of its functions to acheive.</p>
<br />
<h2>Conclusion</h2>
<p>Parameter reduction via the Curry you mention is useful in C# 2 but is considerably de-valued in C# 3 due to Lambdas.</p> |
348,850 | Code Coverage tools for PHP | <p>Is there any code coverage tool available for PHP?
I wish to check the code coverage of my code and API's written in PHP, but have not been able to lay my hands on any code coverage tool for PHP, as it is more of a server side language and dynamic in nature.</p>
<p>Does anyone know of a method by which code coverage for PHP can be executed?</p> | 348,856 | 6 | 0 | null | 2008-12-08 07:30:23.383 UTC | 14 | 2015-09-07 14:25:44.77 UTC | null | null | null | gagneet | 35,416 | null | 1 | 42 | php|code-coverage | 37,552 | <p><a href="http://www.xdebug.org/" rel="noreferrer">xdebug</a> has <a href="http://www.xdebug.org/docs/code_coverage" rel="noreferrer">Code Coverage Analysis</a>.</p>
<p>Check <a href="https://phpunit.de/manual/current/en/code-coverage-analysis.html" rel="noreferrer">this chapter</a> of the PHPUnit Manual</p> |
18,150,396 | Import a C++ .lib and .h file into a C# project? | <p>I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file. </p>
<p>I've read various posts that all mention .dll, rather than .lib, which is confusing me. </p>
<p>The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.</p>
<p><img src="https://i.stack.imgur.com/wu3d5.png" alt="enter image description here"></p>
<p>Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems. </p> | 18,151,259 | 3 | 2 | null | 2013-08-09 15:32:19.317 UTC | 3 | 2021-10-13 22:13:39.24 UTC | null | null | null | null | 1,184,801 | null | 1 | 28 | c#|c++|import|header|.lib | 61,210 | <p>What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.</p>
<p>To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.</p>
<p>Next create a new class (ref class) and wrap your library in it. An example might look something like this:</p>
<pre><code>LibHeader.h
int foo(...);
</code></pre>
<p>You write a wrapper class like this:
Header:</p>
<pre><code>Wrapper.h
public ref class MyWrapper
{
public:
int fooWrapped();
};
</code></pre>
<p>Your Implementation:</p>
<pre><code>Wrapper.cpp
#include Libheader.h
int MyWrapper::fooWrapped()
{
return foo();
}
</code></pre>
<p>Namespaces and all the good stuff omitted for simplicity.
Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.</p> |
33,339,057 | Can I add dns name in aws security group | <p>I have to connect my dynamic IP(which changes every time) to the AWS EC2 machine.<br>
For this I mapped my public IP to the domain name(xyz.com), now I am trying to add it to security group.<br>
But AWS security group not allowing to add DNS names.
Is it the right process to do it, if not please suggest me.</p> | 33,345,604 | 6 | 3 | null | 2015-10-26 05:35:30.567 UTC | 9 | 2020-10-12 20:49:28.493 UTC | null | null | null | null | 2,799,199 | null | 1 | 22 | amazon-web-services|amazon-ec2|aws-security-group | 34,174 | <p>Security Groups and ACLs are not able to resolve DNS hostnames. </p>
<p>You can use the AWS CLI to script the update of your IP dynamic address:</p>
<p>aws ec2 authorize-security-group-ingress --group-id --protocol tcp --port 22 --cidr /24</p>
<p><a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-sg.html" rel="noreferrer">http://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-sg.html</a></p> |
22,950,397 | Jenkins MultiJob Plugin does not aggregate downstream test results | <p>I am using the jenkins multijob plugin to execute a number of parallel builds in the same build phase and i want to display the test results in the main multijob project so i select a post-build action step to 'Aggregate down stream test results' and select both options 'Automatically aggregate all downstream tests' and 'Include failed builds in results' but when the jobs complete and i go into the main multijob project it shows 'no tests' under 'Latest Test Result' link...</p>
<p>Has anyone else encountered this issue? My downstream 'child' projects that run in parallel are multi-configuration projects.</p> | 24,128,712 | 1 | 2 | null | 2014-04-08 23:53:09.5 UTC | 8 | 2014-06-09 21:05:06.6 UTC | null | null | null | null | 390,116 | null | 1 | 9 | jenkins|jenkins-plugins | 11,227 | <p>As a previous poster indicated, this is an open issue in the Jenkins JIRA and does not work. There is a workaround to achieve what your looking for. Your going to need the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin" rel="noreferrer" title="Copy Artifact Plugin">Copy Artifact Plugin</a> and to also Archive the test result files as Artifacts in your jobs that are doing the test runs.</p>
<p>After you have installed this and configured your test run jobs properly, go to your Multijob and after all your test phases add a build step "Copy artifacts from another project" for each of the jobs you want the test results from. You can use "Specified by permalink" and use the "Last build" permalink to always retrieve the latest artifacts. Select the artifacts you want to copy (i.e. *.xml), and input your target directory as something like "job1". If you add multiple build steps to copy artifacts from another project, just name your target directories for the copied artifacts something similar like "job2", "job3", etc.</p>
<p>Then select a Post-build action in your Multijob as you would to Publish JUnit test result report (or whatever you prefer) and input **/job*/*.xml (or similar).</p>
<p>This is what I did, and it works just fine. It is a bit manual in the setup, but it works great once its configured.</p> |
1,712,101 | PHP MVC Best Practices/"Rules" for Success | <p>I'm sure that someone already posted this question; however, I would like to get all kind of recommendations for MVC on PHP. I know there are many experts out there willing to share their knowledge with people who has doubts about their coding best practices.</p>
<ul>
<li>How should you organize your Controller?</li>
<li>How should you organize your Model?</li>
<li>Should Controller call one Model Method and the Model call submethods or should controller call all Model Submethods?</li>
<li>etc.</li>
</ul>
<p>Hope this helps someone out there (because it'll help me for sure).</p> | 1,712,300 | 5 | 3 | null | 2009-11-10 23:58:22.423 UTC | 9 | 2016-01-25 12:02:31.557 UTC | null | null | null | null | 140,901 | null | 1 | 12 | php|model-view-controller | 12,760 | <p>MVC is the most misunderstood design pattern. There is by definition one model. </p>
<p>When an urban planner proposes a project, he designs one model for it. The separate entities that the model might be comprised of: buildings, streets, parks, are typically not represented by separate models: they are all facets of the single model.</p>
<p>So in MVC, the model can be comprised of different entities, and that is probably the best word for it: entity, as in an entity represented by a database table. The model in MVC might even be something more abstract than is actually represented in code, but rather a conceptual umbrella for all of the data that the application might need to act upon.</p>
<p>Considering this, if these entities have their own methods, notably methods that might correspond to the facets of CRUD (create, read, update, delete), they should <em>not</em> be exposed directly to the controller, it is too low a level of abstraction. These building blocks should be built up into a coarser grained interface, for instance you might delete a record but then return the list of records after the deletion. The controller just needs access to a coarser grained method that performs all of the above.</p>
<p>Furthermore, to expose the methods of the entities directly to the controller, could cause the controllers to have to be rewritten, along with the entity classes, if there is a change for instance as to what ORM (object relational mapping) system is being used. The intermediate layer I'm suggesting also is a good place for exception handling, logging and any other such administrivia that needs tending to.</p>
<p>The suggested layer of methods at a higher level of abstraction is sometimes referred to as the business delegate, or a "facade", but this is what I actually consider the model. Hope this isn't too theoretical, and is helpful to the OP or other readers.</p> |
2,219,333 | Nodejs in-memory storage | <p>How do I store data to be used for all the clients in my server? (like the messages of a chat)</p> | 2,222,004 | 5 | 0 | null | 2010-02-08 03:08:40.13 UTC | 3 | 2019-01-18 10:27:15.95 UTC | 2019-01-18 10:27:15.95 UTC | null | 567,854 | user259427 | null | null | 1 | 25 | storage|node.js | 40,989 | <p>The server that node.js allows you to build, is an application server, which means that state is preserved, between request, on the server side. The following snippet demonstrates this:</p>
<pre><code>var sys = require('sys'),
http = require('http');
var number = 0;
http.createServer(function (req, res) {
console.log(req.method, req.url);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Number is: ' + number + '</h1>');
res.end();
number++;
}).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
</code></pre> |
1,987,507 | How to deploy after a build with TeamCity? | <p>I'm setting up TeamCity as my build server. </p>
<p>I have my project set up, it is updating correctly from subversion, and building ok.</p>
<p>So what's next? </p>
<p>Ideally, I'd like to have it auto deploy to a test server, with a manual deploy to a live/staging server.</p>
<p>What's the best way to go about this?</p>
<p>Since I am using C#/ASP.Net, should I add a Web Deployment project to my solution?</p> | 4,151,222 | 5 | 2 | null | 2009-12-31 23:44:25.457 UTC | 45 | 2016-03-17 23:44:10.773 UTC | 2011-04-02 16:05:55.34 UTC | null | 55,164 | null | 55,164 | null | 1 | 76 | c#|asp.net|deployment|teamcity | 53,368 | <p>This article explains how to call Microsoft's WebDeploy tool from TeamCity to deploy a web application to a remote web server. I've been using it to deploy to a test web server and run selenium tests on check-in.</p>
<p><a href="http://www.agileatwork.com/automatic-deployment-from-teamcity-using-webdeploy/" rel="noreferrer">http://www.mikevalenty.com/automatic-deployment-from-teamcity-using-webdeploy/</a></p>
<ol>
<li>Install WebDeploy</li>
<li>Enable Web config transforms</li>
<li>Configure TeamCity BuildRunner</li>
<li>Configure TeamCity Build Dependencies</li>
</ol>
<p>The MSBuild arguments that worked for my application were:</p>
<pre><code>/p:Configuration=QA
/p:OutputPath=bin
/p:DeployOnBuild=True
/p:DeployTarget=MSDeployPublish
/p:MsDeployServiceUrl=https://myserver:8172/msdeploy.axd
/p:username=myusername
/p:password=mypassword
/p:AllowUntrustedCertificate=True
/p:DeployIisAppPath=ci
/p:MSDeployPublishMethod=WMSVC
</code></pre> |
1,849,693 | Simple Suggestion / Recommendation Algorithm | <p>I am looking for a simple suggestion algorithm to implement in to my Web App. Much like Netflix, Amazon, etc... But simpler. I don't need teams of Phd's working to get a better suggestion metric. </p>
<p>So say I have:</p>
<ul>
<li>User1 likes Object1.</li>
<li>User2 likes Object1 and Object2.</li>
</ul>
<p>I want to suggest to User1 they might also like Object2.</p>
<p>I can obviously come up with something naive. I'm looking for something vetted and easily implemented. </p> | 1,849,715 | 6 | 0 | null | 2009-12-04 21:18:30.14 UTC | 17 | 2015-12-10 00:13:39.403 UTC | 2011-10-23 14:20:19.9 UTC | null | 157,882 | null | 75,174 | null | 1 | 19 | performance|algorithm|autosuggest | 9,905 | <p>There are many simple and not so simple examples of suggestion algorithms in the excellent
<a href="https://rads.stackoverflow.com/amzn/click/com/0596529325" rel="noreferrer" rel="nofollow noreferrer">Programming Collective Intelligence</a></p>
<p>The <a href="http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient" rel="noreferrer">Pearson correlation coefficient</a> (a little dry Wikipedia article) can give pretty good results. Here's an implementation in <a href="http://www.dreamincode.net/code/snippet3042.htm" rel="noreferrer">Python</a> and another in <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2006/11/07/netflix-memoirs-using-the-pearson-correlation-coefficient.aspx" rel="noreferrer">TSQL</a> along with an interesting explanation of the algorithm.</p> |
1,834,826 | It is a bad practice to use Sun's proprietary Java classes? | <p>The compiler display warnings if you use Sun's proprietary Java classes. I'm of the opinion that it's generally a bad idea to use these classes. I read this somewhere. However, aside from the warnings are there any fundamental reasons why you should not use them?</p> | 1,834,836 | 7 | 5 | null | 2009-12-02 18:21:49.91 UTC | 5 | 2012-06-05 09:28:47.577 UTC | 2009-12-02 20:25:41.97 UTC | null | 63,550 | null | 124,982 | null | 1 | 29 | java|sun | 17,616 | <p>Because they are internal APIs: they are subject to change in a <strong>undocumented</strong> or <strong>unsupported</strong> way and they are bound to a specific JRE/JDK (<strong>Sun</strong> in your case), limiting portability of your programs.</p>
<p>Try to avoid uses of such APIs, always prefer a public documented and specified class.</p> |
1,557,959 | How can I find out where a Perl module is installed? | <p>How do get the path of a installed Perl module by name,
e.g. <code>Time::HiRes</code>?</p>
<p>I want this just because I have to run my perl script on different nodes of a SGE Grid Engine system. Sometimes, even run as other username.</p>
<p>I can use CPAN.pm to install packages for myself, but it is not so easy to install for other users without chmod 666 on folders.</p> | 32,342,090 | 10 | 2 | null | 2009-10-13 02:39:24.503 UTC | 16 | 2021-11-12 18:39:44.933 UTC | 2009-10-13 07:27:40.927 UTC | null | 159,695 | null | 159,695 | null | 1 | 60 | perl|path|module|config | 87,828 | <p><strong>Note</strong>: This solution proposes use of a (self-authored) <em>utility</em> that you must <em>download</em>. While it offers what I believe to be helpful features, installing a third-party solution first is <em>not an option for everyone</em>.</p>
<hr>
<p>I've created <a href="https://github.com/mklement0/whichpm" rel="noreferrer"><strong><code>whichpm</code></strong></a>, a <strong>cross-platform CLI</strong> (Linux, macOS, Window) that <strong>locates installed Perl modules by module (package) name</strong>, and optionally reports information about them, including detection of accidental duplicates.</p>
<p><strong>Examples</strong></p>
<pre><code># Locate the Data::Dumper module.
$ whichpm Data::Dumper
/usr/lib/perl/5.18/Data/Dumper.pm
# Locate the Data::Dumper module, and also print
# version information and core-module status.
$ whichpm -v Data::Dumper
Data::Dumper 2.145 core>=5.005 /usr/lib/perl/5.18/Data/Dumper.pm
# Locate the Data::Dumper module and open it in your system's default text
# editor.
$ whichpm -e Data::Dumper
# Look for accidental duplicates of the Foo::Bar module.
# Normally, only 1 path should be returned.
$ whichpm -a Foo::Bar
/usr/lib/perl/5.18/Foo/Bar.pm
./Foo/Bar.pm
# Print the paths of all installed modules.
$ whichpm -a
</code></pre>
<h2>Installation</h2>
<p>Prerequisites: <strong>Linux</strong>, <strong>macOS</strong>, or <strong>Windows</strong>, with <strong>Perl v5.4.50 or higher</strong> installed.</p>
<h3>Installation from the npm registry</h3>
<p>With <a href="http://nodejs.org/" rel="noreferrer">Node.js</a> or <a href="https://iojs.org/" rel="noreferrer">io.js</a> installed, install <a href="https://www.npmjs.com/package/whichpm" rel="noreferrer">the package</a> as follows:</p>
<pre><code>[sudo] npm install whichpm -g
</code></pre>
<h3>Manual installation (macOS and Linux)</h3>
<ul>
<li>Download <a href="https://raw.githubusercontent.com/mklement0/whichpm/stable/bin/whichpm" rel="noreferrer">the CLI</a> as <code>whichpm</code>.</li>
<li>Make it executable with <code>chmod +x whichpm</code>.</li>
<li>Move it or symlink it to a folder in your <code>$PATH</code>, such as <code>/usr/local/bin</code> (OSX) or <code>/usr/bin</code> (Linux).</li>
</ul> |
2,161,337 | Can we use any other TAG inside <ul> along with <li>? | <p>Can we use any other TAG in <code><ul></code> along with <code><li></code>?</p>
<p>like</p>
<pre><code><ul>
Some text here or <p>Some text here<p> etc
<li>item 1</li>
Some text here or <p>Some text here<p> etc
<li>item 1</li>
</ul>
</code></pre> | 2,161,486 | 11 | 1 | null | 2010-01-29 10:43:06.217 UTC | 2 | 2021-10-26 14:31:30.903 UTC | null | null | null | null | 84,201 | null | 1 | 56 | css|xhtml|accessibility|w3c | 70,361 | <p>For your code to be valid you can't put any tag inside a <code><ul></code> other than an <code><li></code>.</p>
<p>You can however, put any block level element inside the <code><li></code>, like so:</p>
<pre><code><ul>
<li>
<h2>...</h2>
<p>...</p>
<p>...</p>
</li>
</ul>
</code></pre> |
2,161,388 | Calling a parent window function from an iframe | <p>I want to call a parent window JavaScript function from an iframe. </p>
<pre><code><script>
function abc()
{
alert("sss");
}
</script>
<iframe id="myFrame">
<a onclick="abc();" href="#">Call Me</a>
</iframe>
</code></pre> | 2,161,402 | 11 | 1 | null | 2010-01-29 10:53:42.223 UTC | 91 | 2021-09-25 05:01:37.157 UTC | 2015-06-25 18:49:06.32 UTC | null | 2,842,458 | null | 261,751 | null | 1 | 313 | javascript|iframe|onclick | 484,146 | <pre><code><a onclick="parent.abc();" href="#" >Call Me </a>
</code></pre>
<p>See <a href="https://developer.mozilla.org/en/DOM/window.parent" rel="noreferrer">window.parent</a></p>
<p>Returns a reference to the parent of the current window or subframe.</p>
<p>If a window does not have a parent, its parent property is a reference to itself.</p>
<p>When a window is loaded in an <code><iframe></code>, <code><object></code>, or <code><frame></code>, its parent is the window with the element embedding the window.</p> |
2,024,566 | How to access outer class from an inner class? | <p>I have a situation like so...</p>
<pre><code>class Outer(object):
def some_method(self):
# do something
class Inner(object):
def __init__(self):
self.Outer.some_method() # <-- this is the line in question
</code></pre>
<p>How can I access the <code>Outer</code> class's method from the <code>Inner</code> class?</p> | 2,024,583 | 13 | 3 | null | 2010-01-07 23:49:05.7 UTC | 34 | 2022-07-29 22:19:14.097 UTC | 2020-03-04 18:25:20.473 UTC | null | 355,230 | null | 111,375 | null | 1 | 160 | python|scope|nested|inner-classes | 131,913 | <p>The methods of a nested class cannot directly access the instance attributes of the outer class. </p>
<p>Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.</p>
<p>In fact, it is often recommended against using nested classes, since the nesting does not imply any particular relationship between the inner and outer classes.</p> |
1,873,873 | Why does ReSharper want to use 'var' for everything? | <p>I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to <code>var</code> instead. For example:</p>
<pre><code>//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
</code></pre>
<p>and so on, even with simple types such as <code>int</code>, <code>bool</code>, etc.</p>
<p>Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.</p> | 1,873,885 | 23 | 2 | null | 2009-12-09 13:24:22.483 UTC | 32 | 2020-07-15 01:19:16.78 UTC | 2013-01-29 19:46:46.167 UTC | null | 825,637 | null | 58,244 | null | 1 | 228 | c#|.net|visual-studio|resharper|var | 56,650 | <p>One reason is improved readability. Which is better?</p>
<pre><code>Dictionary<int, MyLongNamedObject> dictionary = new Dictionary<int, MyLongNamedObject>();
</code></pre>
<p>or</p>
<pre><code>var dictionary = new Dictionary<int, MyLongNamedObject>();
</code></pre> |
2,208,480 | jQuery UI DatePicker to show month year only | <p>I am using jQuery date picker to display the calendar all over my app. I want to know if I can use it to display the month and year (May 2010) and not the calendar?</p> | 2,209,104 | 29 | 4 | null | 2010-02-05 16:02:43.143 UTC | 107 | 2022-04-21 03:13:41.44 UTC | 2018-03-10 06:25:12.617 UTC | null | 3,345,644 | null | 244,138 | null | 1 | 388 | javascript|jquery|date|jquery-ui|jquery-ui-datepicker | 690,104 | <p>Here's a hack (updated with entire .html file):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
</head>
<body>
<label for="startDate">Date :</label>
<input name="startDate" id="startDate" class="date-picker" />
</body>
</html>
</code></pre>
<p><strong>EDIT</strong>
jsfiddle for the above example:
<a href="http://jsfiddle.net/DBpJe/7755/" rel="noreferrer">http://jsfiddle.net/DBpJe/7755/</a></p>
<p><strong>EDIT 2</strong>
Adds the month year value to input box only on clicking of Done button.
Also allows to delete input box values, which isn't possible in above field
<a href="http://jsfiddle.net/DBpJe/5103/" rel="noreferrer">http://jsfiddle.net/DBpJe/5103/</a></p>
<p><strong>EDIT 3</strong>
updated Better Solution based on rexwolf's solution down.<br>
<a href="http://jsfiddle.net/DBpJe/5106" rel="noreferrer">http://jsfiddle.net/DBpJe/5106</a> </p> |
33,754,445 | Margin/padding in last Child in RecyclerView | <p>I'm trying to add Padding/Margin Bottom in the last row and Padding/Margin Top in the first row. I can not do it in the item xml as it would affect all of my Children.</p>
<p>I have headers and children in my RecyclerView Adapter so I can not use the</p>
<pre><code> android:padding="4dp"
android:clipToPadding="false"
</code></pre>
<p>I need to use it individually on the last first row of each header</p> | 53,691,028 | 10 | 3 | null | 2015-11-17 10:20:54.32 UTC | 22 | 2021-08-04 13:55:34.52 UTC | 2021-01-10 15:51:56.247 UTC | null | 2,246,798 | null | 4,738,178 | null | 1 | 163 | android|android-recyclerview|padding | 81,329 | <p>I use this in kotlin to give bottom margin to last item <strong>only</strong></p>
<pre><code>override fun onBindViewHolder(holder: RecyclerView.ViewHolder(view), position: Int) {
if (position == itemsList.lastIndex){
val params = holder.itemView.layoutParams as FrameLayout.LayoutParams
params.bottomMargin = 100
holder.itemView.layoutParams = params
}else{
val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
params.bottomMargin = 0
holder.itemView.layoutParams = params
}
//other codes ...
}
</code></pre> |
6,510,673 | in Screen, how do I send a command to all virtual terminal windows within a single screen session? | <p>I know how to create multiple windows within a single screen session, at startup:</p>
<p>But once I have them up and running, is there a way I can have my input be sent to all open windows, not just the one currently in focus?</p> | 6,514,516 | 3 | 0 | null | 2011-06-28 17:32:38.563 UTC | 19 | 2015-02-23 11:08:28.913 UTC | 2011-11-09 20:24:22.507 UTC | null | 496,830 | null | 39,529 | null | 1 | 24 | linux|gnu-screen | 22,145 | <p>I found a good tutorial here to do this:</p>
<p><a href="http://blog.cone.be/2009/11/24/gnu-screen-nethack-different-screen-windows-sending-commands-to-all-screen-windows/" rel="noreferrer">http://blog.cone.be/2009/11/24/gnu-screen-nethack-different-screen-windows-sending-commands-to-all-screen-windows/</a></p>
<p>From the post:</p>
<blockquote>
<p>Once you re used to the multiple windows, you might run into a situation where you want to send a same command to several of these open windows. Screen provides in the “at” command to do this. First you ll need to open command line mode.</p>
<p>C-a : (colon) Enter command line mode.</p>
<p>This way you can type a command once, but you ll still have to enter each separate window. But there is a better way. As an example we ‘ll send “ls -l” to all the windows.</p>
<p>at "#" stuff "ls -l^M"</p>
<p>This command is barely readable, so let's pick it apart! The first part is 'at [identifier][#|*|%] command'. The at command sends the text parameter to all the windows you specified in the identifier. You can match the criteria to either the window name or number with #, the user name with * or the displays, using %. The next part is the command you want to run in the selected windows. We’re using "stuff" to stuff the command we want to execute into the input buffer of the selected windows. Stuff is really straightforward. It simply stuffs the string you gave as a parameter. Next problem is the command. Or rather having it executed! To get screen to put an “enter” after the command, to execute the command, add “^M” at the end. You can do a lot more with this than just sending an ls to the input. Any screen command, like renaming, moving windows around, whatnot .. is available in combination with "at".</p>
</blockquote> |
6,950,230 | How to Calculate Jump Target Address and Branch Target Address? | <p>I am new to <strong>Assembly language</strong>. I was reading about <strong>MIPS</strong> architecture and I am stuck with <strong>Jump Target Address</strong> and <strong>Branch Target Address</strong> and <strong>how to calculate each</strong> of them.</p> | 9,795,721 | 4 | 0 | null | 2011-08-05 00:40:47.273 UTC | 35 | 2020-05-12 20:33:24.02 UTC | 2018-02-05 07:26:11.84 UTC | null | 224,132 | user379888 | null | null | 1 | 36 | assembly|mips|machine-code | 122,668 | <p>(In the diagrams and text below, <code>PC</code> is the address of the branch instruction itself. <code>PC+4</code> is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)</p>
<h1><strong>1. Branch Address Calculation</strong></h1>
<p>In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.</p>
<p>We also limit the branch distance to <code>-2^15 to +2^15 - 1</code> instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.</p>
<p><strong>So step by step :</strong></p>
<ul>
<li>Sign extend the 16 bit offset value to preserve its value.</li>
<li>Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.</li>
<li>Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.</li>
</ul>
<p><img src="https://i.stack.imgur.com/CbO85.png" alt="Branch address calculation"></p>
<hr>
<h1><strong>2. Jump Address Calculation</strong></h1>
<p>For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four. </p>
<p><strong>Again step by step:</strong></p>
<ul>
<li>Multiply 26 bit value with 4.</li>
<li>Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.</li>
<li>Resulting address is the jump value.</li>
</ul>
<p>In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.</p>
<p><img src="https://i.stack.imgur.com/Cjn3Y.png" alt="enter image description here"></p>
<p>Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. <strong>In the diagram above, PC has already advanced to the branch delay slot before the jump calculation.</strong> (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)</p>
<p><strong>Source:</strong> Bilkent University CS 224 Course Slides</p> |
18,371,090 | ActionBarCompat & Transparency | <p>I would like to make the ActionBar in the support library fully transparent, however, it seems that changing the background drawable won't suffice since the backgrounds stack. If you put a semi-transparent background you end up with the default background behind it.</p>
<p>Does anyone know a way to remove that background?</p>
<p>This is what happens:</p>
<p><img src="https://i.stack.imgur.com/Nfker.png" alt="Actionbar"></p>
<p>The code for the background drawable:</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#66336688"/>
</shape>
</code></pre>
<p>As you can see, the drawable has a transparent blue that overlaps with the default gray background.</p> | 18,374,205 | 2 | 4 | null | 2013-08-22 03:12:51.223 UTC | 9 | 2014-01-19 14:27:33.053 UTC | null | null | null | null | 2,442,389 | null | 1 | 11 | android|android-actionbar-compat | 5,194 | <p>Ok, I found the solution messing around with the SDK.
It seems that it is pretty simple, you need to do 3 things:</p>
<ul>
<li>Create a background drawable as shown on my question.</li>
<li><p>Create an ActionBar style like so:</p>
<pre><code><!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<!-- Support library compatibility -->
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<!-- ACTION BAR STYLES -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">
<item name="android:background">@drawable/actionbar_background</item>
<item name="android:windowActionBarOverlay">true</item>
<!-- Support library compatibility -->
<item name="background">@drawable/actionbar_background</item>
<item name="windowActionBarOverlay">true</item>
</style>
</code></pre></li>
<li><p>Use the Window feature for ActionBar overlay using the Support method (ignore Eclipse's warning regarding API level for the constant; I used the SuppressLint annotation to remove the warning):</p>
<pre><code>@SuppressLint("InlinedApi") @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_home);}
</code></pre></li>
</ul> |
40,049,648 | How to add icon to my repository? | <p>I have found that Gitlab and SourceTree support icons for every repositories which make them more specific and easy to find at one glance.</p>
<p>How is this possible?</p> | 40,049,649 | 2 | 3 | null | 2016-10-14 18:16:24.6 UTC | 3 | 2019-12-04 08:34:29.063 UTC | null | null | null | null | 2,359,762 | null | 1 | 45 | git|user-interface|gitlab|atlassian-sourcetree|sourcetree | 25,720 | <p>We as a developer sometimes need a change to make our tools look different.</p>
<p>You can add a small(I prefer 96px x 96px) <code>logo.png</code> image file to the root of your repository.</p>
<p><a href="https://i.stack.imgur.com/7D7sF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7D7sF.png" alt="repository screenshot"></a></p>
<p>Which makes your project more specific and easy to find with <a href="http://gitlab.com" rel="noreferrer">gitlab</a> or <a href="https://www.sourcetreeapp.com" rel="noreferrer">SourceTree</a> git client. Unfortunately github does not support this feature.</p>
<p><a href="https://i.stack.imgur.com/vQDnG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vQDnG.png" alt="gitlab screenshot"></a></p>
<p>It is very simple but it works!</p>
<p><a href="https://i.stack.imgur.com/iYAri.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iYAri.png" alt="sourcetree screenshot"></a></p>
<p><strong>Update</strong>: Thanks to your comments I have found another way within Gitlab repository settings:</p>
<p><a href="https://i.stack.imgur.com/l5eYO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l5eYO.png" alt="gitlab settings screenshot"></a></p>
<p>hope you enjoy this trick and make your tools more fun :)</p> |
63,782,544 | React open mailto E-Mail client onClick with body from textarea | <p>This sounds like it must have been asked before but I could only find how to do this in react native but <strong>I could not find how it's done in normal react for web</strong>. Preferably <em>not</em> with an a tag or Link tag that needs to be styled.</p>
<p>Here some code to illustrate what I want to do:</p>
<pre><code>const onClickMailtoHandler = () => {
//TODO: open default e-mail client e.g. via mailto link with text from (state) variable as body
}
<Button onClick={onClickMailtoHandler}>Send E-Mail</Button>
</code></pre>
<p>Here is how to do a mailto link in HTML:</p>
<pre><code><a href="mailto:[email protected]?body=My custom mail body">E-Mail to Max Mustermann</a>
</code></pre> | 63,819,003 | 4 | 4 | null | 2020-09-07 18:23:36.44 UTC | 5 | 2022-07-19 18:48:42.767 UTC | null | null | null | null | 828,184 | null | 1 | 15 | reactjs|mailto | 38,276 | <p>I ended up creating a component similar to what @GitGitBoom suggested in the comments.</p>
<p>Here for future Seekers:</p>
<pre><code>import React from "react";
import { Link } from "react-router-dom";
const ButtonMailto = ({ mailto, label }) => {
return (
<Link
to='#'
onClick={(e) => {
window.location.href = mailto;
e.preventDefault();
}}
>
{label}
</Link>
);
};
export default ButtonMailto;
</code></pre>
<p>Use it like this:</p>
<pre><code><ButtonMailto label="Write me an E-Mail" mailto="mailto:[email protected]" />
</code></pre> |
5,073,698 | Rails 3 Nested Forms | <p>I have a Person model and an Address Model:</p>
<pre><code>class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
belongs_to :person
end
</code></pre>
<p>In my people controller I have <code>@person.build_address</code> in my new action. My forms builds correctly. The problem is that when I submit the form, a person record and an address record is created but they aren't linked via the address_id column in the Person table.</p>
<p>Am I missing a step in the controller?</p>
<p>Thanks!</p>
<p>New Action
<strong>UPDATE</strong></p>
<pre><code>def new
@person = Person.new
@person.build_address
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @person }
end
end
</code></pre>
<p>Form Code
<strong>UPDATE</strong></p>
<pre><code><%= form_for(@person) do |f| %>
<% if @person.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@person.errors.count, "error") %> prohibited this person from being saved:</h2>
<ul>
<% @person.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :telephone %><br />
<%= f.text_field :telephone %>
</div>
<div class="field">
<%= f.label :mobile_phone %><br />
<%= f.text_field :mobile_phone %>
</div>
<div class="field">
<%= f.label :date_of_birth %><br />
<%= f.date_select :date_of_birth %>
</div>
<div class="field">
<%= f.label :gender %><br />
<%= f.select(:gender, Person::GENDER_TYPES) %>
</div>
<div class="field">
<%= f.label :notes %><br />
<%= f.text_area :notes %>
</div>
<div class="field">
<%= f.label :person_type %><br />
<%= f.select(:person_type, Person::PERSON_TYPES) %>
</div>
<%= f.fields_for :address do |address_fields| %>
<div class="field">
<%= address_fields.label :street_1 %><br />
<%= address_fields.text_field :street_1 %>
</div>
<div class="field">
<%= address_fields.label :street_2 %><br />
<%= address_fields.text_field :street_2 %>
</div>
<div class="field">
<%= address_fields.label :city %><br />
<%= address_fields.text_field :city %>
</div>
<div class="field">
<%= address_fields.label :state %><br />
<%= address_fields.select(:state, Address::STATES) %>
</div>
<div class="field">
<%= address_fields.label :zip_code %><br />
<%= address_fields.text_field :zip_code %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</code></pre> | 5,075,219 | 2 | 2 | null | 2011-02-22 03:28:17.783 UTC | 9 | 2013-02-26 18:10:02.25 UTC | 2011-02-22 03:37:25.353 UTC | null | 95,272 | null | 95,272 | null | 1 | 10 | ruby-on-rails|ruby-on-rails-3 | 20,621 | <p>You need to have <code>accepts_nested_attributes_for :address</code> on your <code>Person</code> model for this to work nicely. In your <code>create</code> action you can then do this:</p>
<pre><code>def create
@person = Person.new(params[:person])
...
end
</code></pre>
<p>Then Rails will take care of the rest.</p>
<p>UPDATE: if the <code>address_id</code> column is in the <code>people</code> table then it should be <code>belongs_to :address</code>, not <code>has_one :address</code></p> |
5,329,529 | I want HTML link to .ics file to open in calendar app when clicked, currently opens file as plain text. Suggestions? | <p>I am linking to an <code>.ics</code> file exported from Apple iCal in an HTML web page.</p>
<pre><code><a href="calendar.ics">
</code></pre>
<p>This link will open the <code>calendar.ics</code> file as plain text in my browser (Chrome). I want automatic opening in Outlook or iCal or other calendar apps. What can I add to the link tag in order to produce the desired behavior? What about modifying the HTTP headers on <code>.ics</code> files?</p>
<p>Any suggestions are appreciated!</p> | 19,367,636 | 2 | 5 | null | 2011-03-16 17:51:41.617 UTC | 14 | 2021-01-25 17:08:48.717 UTC | 2014-04-04 13:23:41.927 UTC | null | 241,211 | null | 224,187 | null | 1 | 27 | html|hyperlink|calendar|icalendar | 82,771 | <p>If your site is built on Linux like mine you can simply add a line to your htaccess file to make it open as a download instead of a text page.</p>
<p>add this to your htaccess file:</p>
<pre><code>AddType text/calendar .ics
</code></pre> |
16,557,637 | How to change active link color in bootstrap css? | <p>I am using joomla 3 and bootstrap.min.js
I am creating menu and giving special class in order to change hover, active, visited links and style of the menu.
I could not find how to change active link color of menu.
Suppose I have 2 menu. Home and Contact.
When I am in Home it is red, I want to change this color.
I could change a:active and a:hover.
Here is code;</p>
<pre><code>.topmenu .active a,
.topmenu .active a:hover {
background-color: white;
}
.topmenu > li > a{
color: orange;
font-weight:bold;
}
.topmenu > li > a:hover {
color: black;
background:white;
}
</code></pre>
<p>Even I used div to change color of active link.
Here is code </p>
<pre><code>#top-menu a{
background-color: white;
color: orange;
font-weight:bold;
}
#top-menu a:focus
{
color: orange;
}
#top-menu a:hover{
color: black;
}
</code></pre>
<p>Every time when I click to Home it is activated and the color is red. What I want to change it to orange. Can not find how to do it. </p>
<p>Here is my markup code</p>
<pre><code><div id="top-menu">
<ul class="nav menu nav-pills topmenu">
<li class="item-109 current active"><a href="/joomla3/">Home</a></li>
<li class="item-138"><a href="/joomla3/?Itemid=138"> Russian </a></li>
<li class="item-110"><a href="/joomla3/?Itemid=110"></a></li></ul>
</div>
</code></pre>
<p>What do you suggest me to do?</p> | 16,558,751 | 9 | 6 | null | 2013-05-15 05:38:48.553 UTC | 4 | 2020-01-12 09:12:36.527 UTC | 2013-05-15 06:32:53.47 UTC | null | 1,168,751 | null | 1,168,751 | null | 1 | 11 | css|twitter-bootstrap | 102,850 | <p>Finally with experiments I found how to capture it.</p>
<pre><code>#top-menu .current a
{
color: orange !important;
}
</code></pre>
<p>Thank you everyone for your time and help.
Much appreciated!</p> |
16,288,169 | HTTP requests trace | <p>Are there any tools to trace the exact HTTP requests sent by a program?</p>
<p>I have an application which works as a client to a website and facilitates certain tasks (particularly it's a bot which makes automatic offers in a social lending webstite, based on some predefined criteria), and I'm interested in monitoring the actual HTTP requests which it makes.</p>
<p>Any tutorials on the topic?</p> | 16,288,465 | 2 | 1 | null | 2013-04-29 21:01:40.31 UTC | 5 | 2020-11-27 10:08:38.417 UTC | 2014-05-26 02:14:04.663 UTC | null | 897,794 | null | 2,333,665 | null | 1 | 12 | http|monitoring|trace|http-request | 45,157 | <p>Some popular protocol/network sniffers are:</p>
<ul>
<li><a href="http://www.wireshark.org" rel="noreferrer">Wireshark</a> (previous the famous Ethereal)</li>
<li><a href="http://www.nirsoft.net/utils/smsniff.html" rel="noreferrer">Nirsoft SmartSniff</a> (using <a href="http://www.winpcap.org/" rel="noreferrer">WinPcap</a>) </li>
<li><a href="http://www.nirsoft.net/utils/socket_sniffer.html" rel="noreferrer">Nirsoft SocketSniff</a> (allows you to watch the WinSock activity of the selected process and watch the content of each send or receive call, in Ascii mode or as Hex Dump)</li>
<li>Microsoft's <a href="http://www.microsoft.com/en-us/download/details.aspx?id=4865" rel="noreferrer">Network Monitor</a> (and a <a href="http://blogs.technet.com/b/netmon/p/usagevideos.aspx" rel="noreferrer">list of video-tutorials here</a>, note video '<a href="http://www.youtube.com/watch?v=SDJ94i2nvPo" rel="noreferrer">Advanced Filtering 2 of 2</a>' where they specifically filter on process)</li>
</ul>
<p>Wikipedia article '<a href="https://en.wikipedia.org/wiki/Comparison_of_packet_analyzers" rel="noreferrer">Comparison of packet analyzers</a>' has a nice overview of some other tools to.</p>
<p>Alternatively you could also look into (man-in-the-middle) proxy tools like: </p>
<ul>
<li><a href="http://fiddler2.com/" rel="noreferrer">Fiddler</a></li>
<li><a href="http://mitmproxy.org/" rel="noreferrer">mitmproxy</a></li>
</ul>
<p>Both of the above actually record/decrypt/modify/replay <a href="https://stackoverflow.com/a/16022285/588079">HTTPS</a> to!! You'd need to point the application you are monitoring to this proxy. If nothing else uses that proxy the log would be application/process specific and another upside to this approach is that one could also run the monitor/logger on a different machine.</p>
<p>Once you choose a tool, you can easily google a tutorial to go along with it.<br>
However the core idea is usually the same: basically one sets a filter (on capture itself or display of captured data) on things like protocol, network/mac address, portno, etc. Depending on the tool, some can also filter on local application.</p>
<p>Hope this helps!</p> |
645,208 | java.rmi.NoSuchObjectException: no such object in table | <p>I am writing a very simple RMI server, and I am seeing intermittent <code>java.rmi.NoSuchObjectExceptions</code> in the unit tests. </p>
<p>I have a string of remote method calls on the same object, and while the first few go through, the later ones will sometimes fail. I am not doing anything to unregister the server object in between.</p>
<p>These error do not appear always, and if I put in breakpoints they tend to not appear. Are those Heisenbugs, whose race conditions dissolve when looking at them through the slowed down execution of the debugger? There is no multi-threading going on in my test or server code (though maybe inside of the RMI stack?).</p>
<p>I am running this on Mac OS X 10.5 (Java 1.5) through Eclipse's JUnit plugin, and the RMI server and client are both in the same JVM.</p>
<p>What can cause these exceptions?</p> | 854,097 | 7 | 0 | null | 2009-03-14 02:24:12.073 UTC | 17 | 2018-12-21 09:01:20.66 UTC | 2009-12-11 14:48:09.367 UTC | null | 13,940 | Thilo | 14,955 | null | 1 | 28 | java|exception|rmi | 69,059 | <p><strong>Keep a strong reference to the object that implements the <code>java.rmi.Remote</code> interface so that it remains <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.6.1" rel="noreferrer">reachable</a>, i.e. ineligible for garbage collection.</strong></p>
<p>Below is a short program that demonstrates a <a href="http://java.sun.com/javase/6/docs/api/java/rmi/NoSuchObjectException.html" rel="noreferrer"><code>java.rmi.NoSuchObjectException</code></a>. The script is self-contained, creating an RMI registry as well as a "client" and a "server" in a single JVM.</p>
<p>Simply copy this code and save it in a file named <code>RMITest.java</code>. Compile and invoke with your choice of command line arguments:</p>
<ul>
<li><strong><code>-gc</code></strong> (default) Explicitly instruct the JVM to make "a best effort" to run the garbage collector after the server is started, but before the client connects to the server. This will likely cause the <code>Remote</code> object to be reclaimed by the garbage collector <em>if the strong reference to the <code>Remote</code> object is <strong>released</em></strong>. A <code>java.rmi.NoSuchObjectException</code> is observed when the client connects after the <code>Remote</code> object is reclaimed.</li>
<li><strong><code>-nogc</code></strong> Do not explicitly request garbage collection. This will likely cause the <code>Remote</code> object to remain accessible by the client regardless of whether a strong reference is held or released <em>unless there is a sufficient <strong>delay</strong> between the server start and the client call such that the system "naturally" invokes the garbage collector and reclaims the <code>Remote</code> object</em>.</li>
<li><strong><code>-hold</code></strong> Retain a strong reference to the <code>Remote</code> object. In this case, a class variable refers to the <code>Remote</code> object.</li>
<li><strong><code>-release</code></strong> (default) A strong reference to the <code>Remote</code> object will be released. In this case, a method variable refers to the <code>Remote</code> object. After the method returns, the strong reference is lost.</li>
<li><strong><code>-delay<S></code></strong> The number of seconds to wait between server start and the client call. Inserting a delay provides time for the garbage collector to run "naturally." This simulates a process that "works" initially, but fails after some significant time has passed. Note there is no space before the number of seconds. Example: <code>-delay5</code> will make the client call 5 seconds after the server is started.</li>
</ul>
<p>Program behavior will likely vary from machine to machine and JVM to JVM because things like <code>System.gc()</code> are only hints and setting the <code>-delay<S></code> option is a guessing game with respect to the behavior of the garbage collector.</p>
<p>On my machine, after <code>javac RMITest.java</code> to compile, I see this behavior:</p>
<pre><code>$ java RMITest -nogc -hold
received: foo
$ java RMITest -nogc -release
received: foo
$ java RMITest -gc -hold
received: foo
$ java RMITest -gc -release
Exception in thread "main" java.rmi.NoSuchObjectException: no such object in table
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
at $Proxy0.remoteOperation(Unknown Source)
at RMITest.client(RMITest.java:69)
at RMITest.main(RMITest.java:46)
</code></pre>
<p>Here is the source code:</p>
<pre><code>import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import static java.util.concurrent.TimeUnit.*;
interface RemoteOperations extends Remote {
String remoteOperation() throws RemoteException;
}
public final class RMITest implements RemoteOperations {
private static final String REMOTE_NAME = RemoteOperations.class.getName();
private static final RemoteOperations classVariable = new RMITest();
private static boolean holdStrongReference = false;
private static boolean invokeGarbageCollector = true;
private static int delay = 0;
public static void main(final String... args) throws Exception {
for (final String arg : args) {
if ("-gc".equals(arg)) {
invokeGarbageCollector = true;
} else if ("-nogc".equals(arg)) {
invokeGarbageCollector = false;
} else if ("-hold".equals(arg)) {
holdStrongReference = true;
} else if ("-release".equals(arg)) {
holdStrongReference = false;
} else if (arg.startsWith("-delay")) {
delay = Integer.parseInt(arg.substring("-delay".length()));
} else {
System.err.println("usage: javac RMITest.java && java RMITest [-gc] [-nogc] [-hold] [-release] [-delay<seconds>]");
System.exit(1);
}
}
server();
if (invokeGarbageCollector) {
System.gc();
}
if (delay > 0) {
System.out.println("delaying " + delay + " seconds");
final long milliseconds = MILLISECONDS.convert(delay, SECONDS);
Thread.sleep(milliseconds);
}
client();
System.exit(0); // stop RMI server thread
}
@Override
public String remoteOperation() {
return "foo";
}
private static void server() throws Exception {
// This reference is eligible for GC after this method returns
final RemoteOperations methodVariable = new RMITest();
final RemoteOperations toBeStubbed = holdStrongReference ? classVariable : methodVariable;
final Remote remote = UnicastRemoteObject.exportObject(toBeStubbed, 0);
final Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
registry.bind(REMOTE_NAME, remote);
}
private static void client() throws Exception {
final Registry registry = LocateRegistry.getRegistry();
final Remote remote = registry.lookup(REMOTE_NAME);
final RemoteOperations stub = RemoteOperations.class.cast(remote);
final String message = stub.remoteOperation();
System.out.println("received: " + message);
}
}
</code></pre> |
686,905 | Labeling file upload button | <p>How can I internationalize the button text of the file picker? For example, what this code presents to the user:</p>
<pre><code> <input type="file" .../>
</code></pre> | 35,767,488 | 7 | 1 | null | 2009-03-26 18:03:54.77 UTC | 10 | 2019-09-30 07:06:52.35 UTC | 2010-03-12 20:48:56.753 UTC | Roger Pate | null | mkoryak | 26,188 | null | 1 | 54 | html|internationalization|dialog | 144,398 | <p>Pure CSS solution:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.inputfile {
/* visibility: hidden etc. wont work */
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.inputfile:focus + label {
/* keyboard navigation */
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}
.inputfile + label * {
pointer-events: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" name="file" id="file" class="inputfile">
<label for="file">Choose a file (Click me)</label></code></pre>
</div>
</div>
</p>
<p>source: <a href="http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/" rel="noreferrer">http://tympanus.net/codrops</a></p> |
798,655 | Embedding an external executable inside a C# program | <p>How do I embed an external executable inside my C# Windows Forms application?</p>
<p>Edit: I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded.</p>
<p>Second reason is a requirement to embed a Flash projector file inside a .NET application.</p> | 799,015 | 8 | 2 | null | 2009-04-28 15:55:55.533 UTC | 25 | 2016-04-25 13:52:48.677 UTC | 2010-07-26 23:03:20.94 UTC | null | 63,550 | null | 92,735 | null | 1 | 40 | c#|windows|embed|executable | 85,402 | <p>Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use.</p>
<pre><code>// extracts [resource] into the the file specified by [path]
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}
string exePath = "c:\temp\embedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );
</code></pre>
<p>The only tricky part is getting the right value for the first argument to <code>ExtractResource</code>. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to <code>GetManifestResourceStream</code>.</p> |
395,291 | Display stocks data from Google Finance or Yahoo! Finance | <p>Can I use the <a href="http://code.google.com/apis/finance/" rel="noreferrer">Google Finance API</a> to get stock data?</p>
<p>If there is a Flash or Javascript viewer for such stocks data it would be good.<br>
I found some chart components that could be used for the same:</p>
<ul>
<li><a href="http://www.amcharts.com/stock/" rel="noreferrer">amCharts</a></li>
<li><a href="http://teethgrinder.co.uk/open-flash-chart/tutorial.php" rel="noreferrer">Open Flash Chart</a></li>
</ul> | 395,631 | 9 | 0 | null | 2008-12-27 19:01:31.197 UTC | 18 | 2012-12-08 20:15:56.067 UTC | 2011-01-25 07:52:54.577 UTC | Jeremy Rudd | 41,021 | Jeremy Rudd | 41,021 | null | 1 | 14 | flash|charts|stocks|google-finance-api | 26,924 | <p><a href="http://finance.yahoo.com/q/hp" rel="noreferrer">Yahoo! Finance</a> gives you real-time stock quotes. Data is returned as a CSV.</p>
<p>See this NASDAQ page at <a href="http://finance.yahoo.com/q?s=" rel="noreferrer">http://finance.yahoo.com/q?s=</a>^IXIC</p>
<ol>
<li><p>Click the Download Data button to access live data</p></li>
<li><p>Click the Download To Spreadsheet button to access historical data</p></li>
</ol>
<p>You can access that data from Flash using the LoadVars or URLLoader classes.
Use unescape() to decode the string from its URL-encoded format.</p> |
765,419 | Javascript word-count for any given DOM element | <p>I'm wondering if there's a way to count the words inside a div for example. Say we have a div like so:</p>
<pre><code><div id="content">
hello how are you?
</div>
</code></pre>
<p>Then have the JS function return an integer of 4.</p>
<p>Is this possible? I have done this with form elements but can't seem to do it for non-form ones.</p>
<p>Any ideas?</p>
<p>g</p> | 765,427 | 9 | 0 | null | 2009-04-19 13:35:01.607 UTC | 11 | 2021-01-14 00:53:37.58 UTC | null | null | null | null | 71,809 | null | 1 | 19 | javascript | 20,278 | <p>If you know that the DIV is <em>only</em> going to have text in it, you can <a href="http://en.wikipedia.org/wiki/KISS_principle" rel="noreferrer">KISS</a>:</p>
<pre><code>var count = document.getElementById('content').innerHTML.split(' ').length;
</code></pre>
<p>If the div can have HTML tags in it, you're going to have to traverse its children looking for text nodes:</p>
<pre><code>function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
</code></pre>
<p>This is the same logic that the jQuery library uses to achieve the effect of its <a href="http://docs.jquery.com/Attributes/text" rel="noreferrer"><code>text()</code></a> function. jQuery is a pretty awesome library that in this case is not necessary. However, if you find yourself doing a lot of DOM manipulation or AJAX then you might want to check it out.</p>
<p><strong>EDIT</strong>:</p>
<p>As noted by Gumbo in the comments, the way we are splitting the strings above would count two consecutive spaces as a word. If you expect that sort of thing (and even if you don't) it's probably best to avoid it by splitting on a regular expression instead of on a simple space character. Keeping that in mind, instead of doing the above split, you should do something like this:</p>
<pre><code>var count = words.split(/\s+/).length;
</code></pre>
<p>The only difference being on what we're passing to the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/split" rel="noreferrer">split</a> function.</p> |
922,695 | removing provisioning profile from xcode | <p>How can I remove a previously installed development provisioning profile from xcode? </p> | 922,830 | 9 | 0 | null | 2009-05-28 19:16:37.643 UTC | 17 | 2018-11-04 02:22:18.567 UTC | null | null | null | null | 97,405 | null | 1 | 50 | iphone | 57,646 | <p>It sounds like you'd want to remove it from your iPhone. I'm not in front of my Mac at the moment but I believe that within XCode there is an Organizer (Look under the view menu option, make sure your iPhone is plugged in) you can open up where you can access your provisioning profile to remove or replace it. I'll check when I get home and update this answer.</p>
<p>Also, if you need to remove just the provisioning file for a single project you can do so by navigating to the build folder of your project and deleting it from there.</p>
<p>If you need to remove your signing keys you can do that through your keychain admin tool.</p>
<p>Edit: Within XCode goto Window->Organizer This will open up the organizer. From there you can do what you need to do to remove the provisioning file.</p> |
844,536 | Advantages of stateless programming? | <p>I've recently been learning about functional programming (specifically Haskell, but I've gone through tutorials on Lisp and Erlang as well). While I found the concepts very enlightening, I still don't see the practical side of the "no side effects" concept. What are the practical advantages of it? I'm trying to think in the functional mindset, but there are some situations that just seem overly complex without the ability to save state in an easy way (I don't consider Haskell's monads 'easy').</p>
<p>Is it worth continuing to learn Haskell (or another purely functional language) in-depth? Is functional or stateless programming actually more productive than procedural? Is it likely that I will continue to use Haskell or another functional language later, or should I learn it only for the understanding?</p>
<p>I care less about performance than productivity. So I'm mainly asking if I will be more productive in a functional language than a procedural/object-oriented/whatever.</p> | 844,548 | 9 | 0 | null | 2009-05-10 02:09:53.223 UTC | 84 | 2021-06-29 18:25:24.91 UTC | 2012-05-27 21:10:32.347 UTC | null | 104,184 | null | 104,184 | null | 1 | 149 | functional-programming|state|immutability | 65,300 | <p>Read <a href="http://www.defmacro.org/ramblings/fp.html" rel="noreferrer">Functional Programming in a Nutshell</a>.</p>
<p>There are lots of advantages to stateless programming, not least of which is <em>dramatically</em> multithreaded and concurrent code. To put it bluntly, mutable state is enemy of multithreaded code. If values are immutable by default, programmers don't need to worry about one thread mutating the value of shared state between two threads, so it eliminates a whole class of multithreading bugs related to race conditions. Since there are no race conditions, there's no reason to use locks either, so immutability eliminates another whole class of bugs related to deadlocks as well.</p>
<p>That's the big reason why functional programming matters, and probably the best one for jumping on the functional programming train. There are also lots of other benefits, including simplified debugging (i.e. functions are pure and do not mutate state in other parts of an application), more terse and expressive code, less boilerplate code compared to languages which are heavily dependent on design patterns, and the compiler can more aggressively optimize your code.</p> |
592,322 | PHP expects T_PAAMAYIM_NEKUDOTAYIM? | <p>Does anyone have a <code>T_PAAMAYIM_NEKUDOTAYIM</code>?</p> | 592,326 | 11 | 2 | null | 2009-02-26 20:34:52.957 UTC | 78 | 2022-04-11 23:17:38.713 UTC | 2022-04-11 23:17:38.713 UTC | null | 1,946,501 | Peter Turner | 1,765 | null | 1 | 625 | php|runtime-error|syntax-error|error-code | 177,531 | <p>It’s the double colon operator <a href="http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php" rel="noreferrer"><code>::</code></a> (see <a href="http://docs.php.net/manual/en/tokens.php" rel="noreferrer">list of parser tokens</a>).</p> |
186,918 | C# - How to change HTML elements attributes | <p>My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks.</p>
<pre><code><div id="menu">
<ul id="nav">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</div>
</code></pre> | 187,023 | 12 | 0 | null | 2008-10-09 11:56:36.677 UTC | 5 | 2019-10-08 10:22:37.59 UTC | 2015-02-01 16:58:21.673 UTC | Longhorn213 | 3,204,551 | Sir Psycho | 17,211 | null | 1 | 18 | c#|html|asp.net | 85,047 | <p>In order to access these controls from the server-side, you need to make them runat="server"</p>
<pre><code><ul id="nav" runat="server">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</code></pre>
<p>in the code-behind:</p>
<pre><code>foreach(Control ctrl in nav.controls)
{
if(!ctrl is HtmlAnchor)
{
string url = ((HtmlAnchor)ctrl).Href;
if(url == GetCurrentPage()) // <-- you'd need to write that
ctrl.Parent.Attributes.Add("class", "active");
}
}
</code></pre> |
128,618 | File-size format provider | <p>Is there any easy way to create a class that uses <strong>IFormatProvider</strong> that writes out a user-friendly file-size?</p>
<pre><code>public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
</code></pre>
<p>It should result in strings formatted something like "<em>2,5 MB</em>", "<em>3,9 GB</em>", "<em>670 bytes</em>" and so on.</p> | 128,683 | 12 | 2 | null | 2008-09-24 17:44:34.957 UTC | 27 | 2021-10-11 02:47:47.647 UTC | 2016-09-20 13:17:37.023 UTC | Seb Nilsson | 107,625 | Seb Nilsson | 2,429 | null | 1 | 72 | c#|formatting|filesize | 47,689 | <p>I use this one, I get it from the web</p>
<pre><code>public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private const Decimal OneKiloByte = 1024M;
private const Decimal OneMegaByte = OneKiloByte * 1024M;
private const Decimal OneGigaByte = OneMegaByte * 1024M;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
if (arg is string)
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneGigaByte)
{
size /= OneGigaByte;
suffix = "GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = "MB";
}
else if (size > OneKiloByte)
{
size /= OneKiloByte;
suffix = "kB";
}
else
{
suffix = " B";
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
IFormattable formattableArg = arg as IFormattable;
if (formattableArg != null)
{
return formattableArg.ToString(format, formatProvider);
}
return arg.ToString();
}
}
</code></pre>
<p>an example of use would be:</p>
<pre><code>Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000));
</code></pre>
<p>Credits for <a href="http://flimflan.com/blog/FileSizeFormatProvider.aspx" rel="noreferrer">http://flimflan.com/blog/FileSizeFormatProvider.aspx</a></p>
<p>There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :( </p>
<p>If you're using C# 3.0 you can use an extension method to get the result you want:</p>
<pre><code>public static class ExtensionMethods
{
public static string ToFileSize(this long l)
{
return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
}
}
</code></pre>
<p>You can use it like this.</p>
<pre><code>long l = 100000000;
Console.WriteLine(l.ToFileSize());
</code></pre>
<p>Hope this helps.</p> |
190,344 | WPF Blurry fonts issue- Solutions | <p>Problem is described and demonstrated on the following links:</p>
<ul>
<li><a href="https://web.archive.org/web/20081123055336/http://paulstovell.com/blog/wpf-why-is-my-text-so-blurry" rel="noreferrer">Paul Stovell WPF: Blurry Text Rendering </a></li>
<li><a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=445078" rel="noreferrer">www.gamedev.net forum</a></li>
<li><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=380919&wa=wsignin1.0" rel="noreferrer">Microsoft Connect: WPF text renderer produces badly blurred text on small font sizes</a></li>
</ul>
<p>Explanation: <a href="http://windowsclient.net/wpf/white-papers/wpftextclarity.aspx" rel="noreferrer">Text Clarity in WPF</a>. This link has font comparison.</p>
<p>I would like to collect all possible solutions for this problem. Microsoft Expression Blend uses WPF but fonts look readable. </p>
<ul>
<li>Dark background as in Microsoft Expression Blend</li>
<li>Increasing the font size and changing the font (Calibri ... ) <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#190521">[link]</a></li>
<li>Embed windows forms <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#190540">[link]</a></li>
<li>Use GDI+ and/or Windows Forms TextRenderer class to render text to a bitmap, and then render that bitmap as a WPF control. <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#283216">[link]</a></li>
</ul>
<p>Are there any more solutions?</p>
<p><a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem-solutions/1494126#1494126"><strong>This is going to be fixed in VS2010 (and WPF4) beta 2</strong></a></p>
<p><strong>IT LOOKS LIKE IT HAS BEEN FINALLY SOLVED !</strong> </p>
<p><a href="http://www.hanselman.com/blog/WPFAndTextBlurrinessNowWithCompleteClarity.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+ScottHanselman+%28Scott+Hanselman+-+ComputerZen.com%29&utm_content=Google+Reader" rel="noreferrer"><strong>Scott Hanselman's ComputerZen.com: WPF and Text Blurriness, now with complete Clarity</strong></a> </p> | 190,521 | 12 | 4 | null | 2008-10-10 06:50:27.183 UTC | 86 | 2022-07-15 19:39:54 UTC | 2019-04-11 06:47:36.6 UTC | Robert Vuković | 438,025 | Vule | 438,025 | null | 1 | 156 | wpf|fonts | 66,426 | <h3>Technical background</h3>
<p>There is a in-depth article about WPF Text rendering from one of the WPF Text Program Managers on windowsclient.net: <a href="http://windowsclient.net/wpf/white-papers/wpftextclarity.aspx" rel="noreferrer">Text Clarity in WPF</a>.</p>
<p>The problem boils down to WPF needing a linearly scaling font-renderer for smooth animations. Pure ClearType on the other hand takes quite a bit of freedom with the font to push vertical stems into the next pixel. </p>
<p>The difference is obvious if one compares the classic "cascade" pattern. WinForms on the lower left side, WPF on the top right side:</p>
<p><img src="https://club.black.co.at/david/pics/Fontcascade.png" width="640"/></p>
<p>While I'm no fan of WPF's font rendering idiosyncrasies either, I can imagine the clamor if the animations would jump like they do in the Winforms cascade. </p>
<h3>Playing with the registry</h3>
<p>Of special interest to me was the link to the MSDN article "<a href="http://msdn.microsoft.com/en-us/library/aa970267.aspx" rel="noreferrer">ClearType Registry Settings</a>", which explains the possible user-side adjustments in the registry:</p>
<ul>
<li>ClearType level: amount of subpixel hinting</li>
<li>Gamma level</li>
<li>Pixel structure: how the color stripes in a display-pixel are arranged</li>
<li>Text contrast level: adjusts the width of glyph stems to make the font heavier</li>
</ul>
<p>Playing around with these settings didn't really improve the underlying problem, but can help by reducing the color bleeding effect for sensitive users.</p>
<h3>Another approach</h3>
<p>The best advice the Text Clarity article gave was increasing the font size and changing the font. Calibri works for me better than the standard Segoe UI. Due to its popularity as web font, I tried Verdana too, but it has a nasty jump in weight between 14pt and 15pt which is very visible when animating the font size.</p>
<h3>WPF 4.0</h3>
<p>WPF 4 will have improved support for influencing the rendering of fonts. There is <a href="https://blogs.msdn.microsoft.com/text/2009/08/24/wpf-4-0-text-stack-improvements/" rel="noreferrer">an article on the WPF Text Blog</a> explaining the changes. Most prominently, there are now (at least) three different kinds of text rendering:</p>
<p><img src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/text/WindowsLiveWriter/WPF4.0TextStackImprovements_12DE7/CT%20vs%20Grayscale%20vs%20Aliased_4.png" alt="text rendering comparison"></p>
<p><sub><grumble>That should be enough rope for every designer.</grumble></sub></p> |
158,716 | How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N | <p>The question gives all necessary data: what is an efficient algorithm to generate a sequence of <em>K</em> non-repeating integers within a given interval <em>[0,N-1]</em>. The trivial algorithm (generating random numbers and, before adding them to the sequence, looking them up to see if they were already there) is very expensive if <em>K</em> is large and near enough to <em>N</em>.</p>
<p>The algorithm provided in <a href="https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list">Efficiently selecting a set of random elements from a linked list</a> seems more complicated than necessary, and requires some implementation. I've just found another algorithm that seems to do the job fine, as long as you know all the relevant parameters, in a single pass.</p> | 158,847 | 13 | 4 | null | 2008-10-01 17:21:30.637 UTC | 14 | 2022-06-20 17:17:07.493 UTC | 2017-05-23 11:47:16.903 UTC | null | -1 | tucuxi | 15,472 | null | 1 | 28 | arrays|algorithm|random|permutation | 19,731 | <p>The <a href="https://docs.python.org/2/library/random.html#random.sample" rel="nofollow noreferrer">random module</a> from Python library makes it extremely easy and effective:</p>
<pre><code>from random import sample
print sample(xrange(N), K)
</code></pre>
<p><code>sample</code> function returns a list of K unique elements chosen from the given sequence.<br>
<code>xrange</code> is a "list emulator", i.e. it behaves like a list of consecutive numbers without creating it in memory, which makes it super-fast for tasks like this one.</p> |
363,425 | How to wrap long lines without spaces in HTML? | <p>If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:</p>
<blockquote>
<p>HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................</p>
</blockquote>
<p>I've tried just using <code>wordwrap()</code> in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.</p>
<p>There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.</p>
<p>How do you solve this problem?</p> | 363,521 | 14 | 3 | null | 2008-12-12 17:03:49.393 UTC | 13 | 2017-06-22 23:00:28.323 UTC | 2011-11-09 09:41:49.483 UTC | Chris Bartow | 53,114 | Chris Bartow | 497 | null | 1 | 69 | php|html|css|word-wrap | 83,957 | <p>I haven't personally used it, but <a href="http://code.google.com/p/hyphenator/" rel="nofollow noreferrer">Hyphenator</a> looks promising.</p>
<p>Also see related (possibly duplicate) questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/322929/word-wrap-in-css-js">word wrap in css / js</a></li>
<li><a href="https://stackoverflow.com/questions/320184/who-has-solved-the-long-word-breaks-my-div-problem-hint-not-stackoverflow">Who has solved the long-word-breaks-my-div problem? (hint: not stackoverflow)</a></li>
</ul> |
Subsets and Splits