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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,561,315 | Alternative to <body onload="init ();"> | <p>I'm trying to fix an old script written for me. I need it to run without <code><body onload="init ();"></code>. I'd like to run the function from inside the script without inline code like that command. Sorry I'm not a JS expert but how do I do this?</p> | 7,561,332 | 5 | 0 | null | 2011-09-26 21:05:55.553 UTC | 6 | 2014-01-31 14:34:21.693 UTC | 2011-09-26 21:08:13.153 UTC | null | 118,068 | null | 334,776 | null | 1 | 17 | javascript | 67,167 | <pre><code><script type="text/javascript">
function init() {
// Put your code here
}
window.onload = init;
</script>
</code></pre>
<p>Or, if you are using jQuery:</p>
<pre><code>$(function() {
// Your code here
});
</code></pre> |
7,577,615 | Parallel wget in Bash | <p>I am getting a bunch of relatively small pages from a website and was wondering if I could somehow do it in parallel in Bash. Currently my code looks like this, but it takes a while to execute (I think what is slowing me down is the latency in the connection).</p>
<pre><code>for i in {1..42}
do
wget "https://www.example.com/page$i.html"
done
</code></pre>
<p>I have heard of using xargs, but I don't know anything about that and the man page is very confusing. Any ideas? Is it even possible to do this in parallel? Is there another way I could go about attacking this?</p> | 11,850,469 | 5 | 0 | null | 2011-09-28 02:12:35.68 UTC | 55 | 2020-09-04 13:08:36.557 UTC | 2012-08-13 15:54:16.667 UTC | null | 1,538,531 | null | 824,954 | null | 1 | 82 | bash|parallel-processing|wget | 67,926 | <p>Much preferrable to pushing <code>wget</code> into the background using <code>&</code> or <code>-b</code>, you can use <code>xargs</code> to the same effect, and better.</p>
<p>The advantage is that <code>xargs</code> will <strong>synchronize properly</strong> with no extra work. Which means that you are safe to access the downloaded files (assuming no error occurs). All downloads will have completed (or failed) once <code>xargs</code> exits, and you know by the exit code whether all went well. This is much preferrable to busy waiting with <code>sleep</code> and testing for completion manually.</p>
<p>Assuming that <code>URL_LIST</code> is a variable containing all the URLs (can be constructed with a loop in the OP's example, but could also be a manually generated list), running this:</p>
<pre><code>echo $URL_LIST | xargs -n 1 -P 8 wget -q
</code></pre>
<p>will pass one argument at a time (<code>-n 1</code>) to <code>wget</code>, and execute at most 8 parallel <code>wget</code> processes at a time (<code>-P 8</code>). <code>xarg</code> returns after the last spawned process has finished, which is just what we wanted to know. No extra trickery needed.</p>
<p>The "magic number" of 8 parallel downloads that I've chosen is not set in stone, but it is probably a good compromise. There are two factors in "maximising" a series of downloads:</p>
<p>One is filling "the cable", i.e. utilizing the available bandwidth. Assuming "normal" conditions (server has more bandwidth than client), this is already the case with one or at most two downloads. Throwing more connections at the problem will only result in packets being dropped and TCP congestion control kicking in, and <em>N</em> downloads with asymptotically <em>1/N</em> bandwidth each, to the same net effect (minus the dropped packets, minus window size recovery). Packets being dropped is a normal thing to happen in an IP network, this is how congestion control is supposed to work (even with a single connection), and normally the impact is practically zero. However, having an unreasonably large number of connections amplifies this effect, so it can be come noticeable. In any case, it doesn't make anything faster. </p>
<p>The second factor is connection establishment and request processing. Here, having a few extra connections in flight <em>really helps</em>. The problem one faces is the latency of two round-trips (typically 20-40ms within the same geographic area, 200-300ms inter-continental) plus the odd 1-2 milliseconds that the server actually needs to process the request and push a reply to the socket. This is not a lot of time <em>per se</em>, but multiplied by a few hundred/thousand requests, it quickly adds up.<br>
Having anything from half a dozen to a dozen requests in-flight hides most or all of this latency (it is still there, but since it overlaps, it does not sum up!). At the same time, having only a few concurrent connections does not have adverse effects, such as causing excessive congestion, or forcing a server into forking new processes.</p> |
7,101,743 | Can I style an image's ALT text with CSS? | <p>I have a dark blue page and when the image is loading (or missing) the ALT text is black and difficult to read (in FF). </p>
<p>Could I style it (with CSS) to be white?</p> | 7,101,786 | 7 | 0 | null | 2011-08-18 02:29:47.787 UTC | 6 | 2021-07-04 02:08:25.203 UTC | 2011-08-18 02:48:45.553 UTC | null | 398,242 | null | 192,910 | null | 1 | 59 | html|css | 132,226 | <p>Setting the <code>img</code> tag <code>color</code> works</p>
<pre><code>img {color:#fff}
</code></pre>
<p><a href="http://jsfiddle.net/YEkAt/" rel="noreferrer">http://jsfiddle.net/YEkAt/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background:#000022}
img {color:#fff}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /></code></pre>
</div>
</div>
</p> |
7,039,966 | jQuery difference between :eq() and :nth-child() | <p>In jQuery, what are some of the key differences between using :eq() and :nth-child() to select any elements ?</p>
<p>Also in general, for the starting index, in which case does it start from "0" and when it starts from "1" ?</p> | 7,040,002 | 8 | 0 | null | 2011-08-12 12:20:26.9 UTC | 13 | 2018-11-22 04:03:53.973 UTC | null | null | null | null | 485,743 | null | 1 | 33 | javascript|jquery|dom|jquery-selectors | 31,878 | <p><strong>:eq()</strong></p>
<blockquote>
<p>Select the element at index n within the matched set.</p>
<p>The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.</p>
</blockquote>
<p><strong>:nth-child()</strong></p>
<blockquote>
<p>Selects all elements that are the nth-child of their parent.</p>
<p>Because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript's "0-indexed" counting. Therefore, given a single containing two <code><li></code>s, <code>$('li:nth-child(1)')</code> selects the first <code><li></code> while <code>$('li:eq(1)')</code> selects the second.</p>
<p>The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.</p>
<p>The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.</p>
<p>In addition to this, :nth-child() can take ‘odd’ and ‘even’ as arguments instead. ‘odd’ has the same signification as 2n+1, and ‘even’ has the same signification as 2n. </p>
</blockquote>
<p><strong>Further discussion of this unusual usage can be found in the <a href="http://www.w3.org/TR/css3-selectors/#nth-child-pseudo">W3C CSS specification</a>.</strong></p>
<p><strong>Detailed Comparision</strong></p>
<p>See the Demo: <a href="http://jsfiddle.net/rathoreahsan/sXHtB/">http://jsfiddle.net/rathoreahsan/sXHtB/</a> -- Link updated</p>
<p>Also See the references </p>
<p><a href="http://api.jquery.com/eq-selector/">http://api.jquery.com/eq-selector/</a></p>
<p><a href="http://api.jquery.com/nth-child-selector/">http://api.jquery.com/nth-child-selector/</a></p> |
7,181,756 | Invoke or BeginInvoke cannot be called on a control until the window handle has been created | <p>I get the following exception thrown:</p>
<blockquote>
<p>Invoke or BeginInvoke cannot be called on a control until the window handle has been created.</p>
</blockquote>
<p>This is my code:</p>
<pre><code>if (InvokeRequired)
{
BeginInvoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
}
else
Invoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
</code></pre>
<p>I found pages about this topic on this site but I don't know what is wrong.</p> | 7,183,036 | 8 | 3 | null | 2011-08-24 20:20:06.657 UTC | 6 | 2021-06-26 20:54:27.383 UTC | 2011-08-25 20:23:07.333 UTC | null | 419 | null | 267,679 | null | 1 | 33 | c#|winforms | 66,469 | <p>The difference between Invoke and BeginInvoke is that the former is synchronous (waits for completion) while the later is asynchronous (sort of fire-and-forget). However, both work by posting a message to the UI message loop which will cause the delegate to be executed when it gets to that message.</p>
<p>The InvokeRequired property determines whether you need to Invoke at all or if it is already on the correct thread, not whether you want synchronous or asynchronous calling. If InvokeRequired is false you are (in theory) already running on the UI thread and can simply perform synchronous actions directly (or still BeginInvoke if you need to fire them off asynchronously). This also means you can't use Invoke if InvokeRequired is false, because there's no way for the message loop on the current thread to continue. So that's one big problem with your code above, but not necessarily the error you're reporting. You <em>can</em> actually use BeginInvoke in either case, if you watch out for recursive invocation, and so on.</p>
<p>However, you can't use either one without a window handle. If the Form/Control has been instantiated but not initialized (ie. before it is first shown) it may not have a handle yet. And the handle gets cleared by Dispose(), such as after the Form is closed. In either case InvokeRequired will return false because it is not possible to invoke without a handle. You can check IsDisposed, and there is also a property IsHandleCreated which more specifically tests if the handle exists. Usually, if IsDisposed is true (or if IsHandleCreated is false) you want to punt into a special case such as simply dropping the action as not applicable.</p>
<p>So, the code you want is probably more like:</p>
<pre><code>if (IsHandleCreated)
{
// Always asynchronous, even on the UI thread already. (Don't let it loop back here!)
BeginInvoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
return; // Fired-off asynchronously; let the current thread continue.
// WriteToForm will be called on the UI thread at some point in the near future.
}
else
{
// Handle the error case, or do nothing.
}
</code></pre>
<p>Or maybe:</p>
<pre><code>if (IsHandleCreated)
{
// Always synchronous. (But you must watch out for cross-threading deadlocks!)
if (InvokeRequired)
Invoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
else
WriteToForm(finished, numCount); // Call the method (or delegate) directly.
// Execution continues from here only once WriteToForm has completed and returned.
}
else
{
// Handle the error case, or do nothing.
}
</code></pre> |
7,625,862 | Validate an email inside an EditText | <p>I want to validate an email introduced inside an EditText and this the code that I already have:</p>
<blockquote>
<p>final EditText textMessage = (EditText)findViewById(R.id.textMessage);</p>
<p>final TextView text = (TextView)findViewById(R.id.text);</p>
</blockquote>
<pre><code> textMessage.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (textMessage.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && s.length() > 0)
{
text.setText("valid email");
}
else
{
text.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
</code></pre>
<p>The problem is that when I introduce 3 characters after the "@", it appears the message "valid email", when it must appear when I introduce the complete email.</p>
<p>Any suggerence?</p>
<p>Thank you all!</p> | 7,626,012 | 9 | 4 | null | 2011-10-02 10:34:44.323 UTC | 9 | 2013-12-05 13:58:37.157 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 974,633 | null | 1 | 17 | android|regex|email|android-edittext | 32,571 | <p>Just change your regular expression as follows:</p>
<pre><code>"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
</code></pre>
<p>Because . (dot) means match any single-char.ADD a double backslash before your dot to stand for a real dot.</p> |
13,973,963 | Easiest way to store data from web site (on server side) | <p>I have very simple web site (which is actually single page), there is one input field and a button.<br>
I need to store data submitted by users somewhere on server side. Perfect way could be simple text file and new lines appended to it after each button click. Log file will be also ok.<br>
As I understand it is not possible with JavaScript itself. I'm looking for <em>easiest solution</em>, preferably with no server-side programming (but if it is required, it should be as easy as possible and work out-of-box). I can use some side service if it could be helpful.<br>
Please help.<br>
Thanks in advance. </p>
<p>UPD. Just want to rephrase the main question. I do not really need to store something on server side. I need to collect some input from users. Is it possible? It would also be ok if it for example will be just sent to my e-mail.</p> | 13,974,070 | 4 | 2 | null | 2012-12-20 14:09:12.817 UTC | 10 | 2013-12-21 02:13:56.213 UTC | 2012-12-20 14:17:09.203 UTC | null | 682,336 | null | 682,336 | null | 1 | 17 | javascript|html | 49,775 | <p>For a very simple form-to-server-log script:</p>
<p>Your form:</p>
<pre><code><form action="save-to-log.php" method="POST">
<fieldset>
<legend>Add to log</legend>
<p>
Message:
<textarea name="message"></textarea>
</p>
<p>
<input type="submit" value="SAVE" />
</p>
</fieldset>
</form>
</code></pre>
<p>Then <strong>save-to-log.php</strong></p>
<pre><code><?php
$log_file_name = 'mylog.log'; // Change to the log file name
$message = $_POST['message']; // incoming message
file_put_contents($log_file_name, $message, FILE_APPEND);
header('Location: /'); // redirect back to the main site
</code></pre>
<p>if it's a unix host you'll need to add 755 permissions to the directory of the log so PHP has access to write to it. Other than that, you'll have a form that keeps appending information to <code>mylog.log</code>.</p>
<p><strong>Follow-Up</strong></p>
<p>If you don't necessarily need it store on the server (you mentioned email) you can use the following instead as the PHP script:</p>
<pre><code><?php
$to_email = '[email protected]';
$subject = 'User feedback from site';
$message = $_POST['message'];
// this may need configuring depending on your host. If you find the email isn't
// being sent, look up the error you're receiving or post another question here on
// SO.
mail($to_email, $subject, $message);
header('Location: /');
</code></pre> |
14,042,213 | Using WebAPI in LINQPad? | <p>When I tried to use the Selfhosted WebAPI in LINQPad, I just kept getting the same error that a controller for the class didn't exist. </p>
<p>Do I have to create separate assemblies for the WebAPI (Controllers/Classes) and then reference them in my query?</p>
<p>Here's the code I'm using</p>
<pre><code>#region namespaces
using AttributeRouting;
using AttributeRouting.Web.Http;
using AttributeRouting.Web.Http.SelfHost;
using System.Web.Http.SelfHost;
using System.Web.Http.Routing;
using System.Web.Http;
#endregion
public void Main()
{
var config = new HttpSelfHostConfiguration("http://192.168.0.196:8181/");
config.Routes.MapHttpAttributeRoutes(cfg =>
{
cfg.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
});
config.Routes.Cast<HttpRoute>().Dump();
AllObjects.Add(new UserQuery.PlayerObject { Type = 1, BaseAddress = "Hej" });
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
using(HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Server open, press enter to quit");
Console.ReadLine();
server.CloseAsync();
}
}
public static List<PlayerObject> AllObjects = new List<PlayerObject>();
public class PlayerObject
{
public uint Type { get; set; }
public string BaseAddress { get; set; }
}
[RoutePrefix("players")]
public class PlayerObjectController : System.Web.Http.ApiController
{
[GET("allPlayers")]
public IEnumerable<PlayerObject> GetAllPlayerObjects()
{
var players = (from p in AllObjects
where p.Type == 1
select p);
return players.ToList();
}
}
</code></pre>
<p>This code works fine when in a separate Console Project in VS2012.</p>
<p>I started using AttributeRouting via NuGET when I didn't get the "normal" WebAPI-routing to work.</p>
<p>The error I got in the browser was: <code>No HTTP resource was found that matches the request URI 'http://192.168.0.196:8181/players/allPlayers'.</code></p>
<p>Additional error: <code>No type was found that matches the controller named 'PlayerObject'</code></p> | 15,823,738 | 1 | 10 | null | 2012-12-26 14:49:42.01 UTC | 10 | 2015-04-25 17:52:27.67 UTC | 2012-12-28 09:15:53.09 UTC | null | 1,025,823 | null | 1,025,823 | null | 1 | 17 | asp.net-web-api|linqpad|self-hosting|attributerouting | 5,016 | <p>Web API by default will ignore controllers that are not public, and LinqPad classes are <em>nested public</em>, we had similar problem in <a href="https://github.com/scriptcs/" rel="noreferrer">scriptcs</a></p>
<p>You have to add a custom controller resolver, which will bypass that limitation, and allow you to discover controller types from the executing assembly manually.</p>
<p>This was actually fixed already (now Web API controllers only need to be <em>Visible</em> not public), but that happened in September and the latest stable version of self host is from August.</p>
<p>So, add this:</p>
<pre class="lang-cs prettyprint-override"><code>public class ControllerResolver: DefaultHttpControllerTypeResolver {
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
var types = Assembly.GetExecutingAssembly().GetExportedTypes();
return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
}
}
</code></pre>
<p>And then register against your configuration, and you're done:</p>
<pre class="lang-cs prettyprint-override"><code>var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());
</code></pre>
<p>Here is a full working example, I just tested against LinqPad. Note that you have to be running LinqPad as admin, otherwise you won't be able to listen at a port.</p>
<pre class="lang-cs prettyprint-override"><code>public class TestController: System.Web.Http.ApiController {
public string Get() {
return "Hello world!";
}
}
public class ControllerResolver: DefaultHttpControllerTypeResolver {
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
var types = Assembly.GetExecutingAssembly().GetExportedTypes();
return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
}
}
async Task Main() {
var address = "http://localhost:8080";
var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());
conf.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var server = new HttpSelfHostServer(conf);
await server.OpenAsync();
// keep the query in the 'Running' state
Util.KeepRunning();
Util.Cleanup += async delegate {
// shut down the server when the query's execution is canceled
// (for example, the Cancel button is clicked)
await server.CloseAsync();
};
}
</code></pre> |
14,044,761 | How to mute all sound in a page with JS? | <p>How can I mute all sound on my page with JS?</p>
<p>This should mute HTML5 <code><audio></code> and <code><video></code> tags along with Flash and friends.</p> | 14,045,788 | 6 | 5 | null | 2012-12-26 18:42:36.34 UTC | 6 | 2021-07-15 08:00:58.87 UTC | 2016-05-13 20:05:08.193 UTC | null | 2,065,702 | null | 172,776 | null | 1 | 25 | javascript|html|flash|audio|mute | 56,716 | <p>Rule #1: Never enable audio autoplay upon page loading.</p>
<p>Anyway I'll show for HTML5 using jQuery:</p>
<pre><code>// WARNING: Untested code ;)
window.my_mute = false;
$('#my_mute_button').bind('click', function(){
$('audio,video').each(function(){
if (!my_mute ) {
if( !$(this).paused ) {
$(this).data('muted',true); //Store elements muted by the button.
$(this).pause(); // or .muted=true to keep playing muted
}
} else {
if( $(this).data('muted') ) {
$(this).data('muted',false);
$(this).play(); // or .muted=false
}
}
});
my_mute = !my_mute;
});
</code></pre>
<p>Flash Media Players depends on the custom API (hopefuly) exposed to JavaScript.</p>
<p>But you get the idea, iterate through media, check/store playing status, and mute/unmute.</p> |
14,306,903 | How to find the main() entry point in a VB.Net winforms app? | <p>When I create a WinForms app in C#, the output type is <code>Windows Application</code> and I get a <code>program.cs</code> with a <code>static void Main()</code> which I can use to handle command-line parameters, etc...</p>
<p>However, when I create an equivalent project for VB, the application type is <code>Windows Forms Application</code> and I'm forced to pick a startup form.</p>
<p>Is there an equivalent mechanism to run my own code before I decide which form to display in VB.Net? I'm assuming the same code exists but is auto-generated and hidden somewhere? If so, where?</p> | 14,307,397 | 2 | 5 | null | 2013-01-13 18:49:09.737 UTC | 4 | 2016-02-27 23:59:17.453 UTC | 2013-11-07 00:53:43.443 UTC | null | 156,755 | null | 156,755 | null | 1 | 35 | .net|vb.net|winforms | 30,188 | <p>In VB you'll need to create your sub main by hand as it were so what I generally do is create a new Module named Program. </p>
<p>Within that as a very basic setup you'll need to add the following code.</p>
<pre><code>Public Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1)
End Sub
</code></pre>
<p>Once you've done that go to the application tab of the project's settings and uncheck the 'Enable Application framework' setting and then from the drop down under Startup object select your new Sub Main procedure.</p>
<p>You can then put any start-up code that you want to run before your program opens its main form before the Application.Run line.</p>
<p>Hope that helps</p> |
14,287,386 | Change string color with NSAttributedString? | <p>I have a slider for a survey that display the following strings based on the value of the slider: "Very Bad, Bad, Okay, Good, Very Good". </p>
<p>Here is the code for the slider:</p>
<pre><code>- (IBAction) sliderValueChanged:(UISlider *)sender {
scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
NSArray *texts=[NSArray arrayWithObjects:@"Very Bad", @"Bad", @"Okay", @"Good", @"Very Good", @"Very Good", nil];
NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
self.scanLabel.text=[texts objectAtIndex:sliderValue];
}
</code></pre>
<p>I want "Very Bad" to be red, "Bad" to be orange, "Okay" to be yellow, "Good" and "Very Good" to be green. </p>
<p>I don't understand how to use <code>NSAttributedString</code> to get this done. </p> | 14,287,939 | 9 | 4 | null | 2013-01-11 22:01:51.223 UTC | 23 | 2022-08-12 13:01:18.503 UTC | 2015-09-30 14:13:47.857 UTC | null | 916,299 | null | 1,914,552 | null | 1 | 162 | ios|cocoa-touch|nsattributedstring | 202,501 | <p>There is no need for using <code>NSAttributedString</code>. All you need is a simple label with the proper <code>textColor</code>. Plus this simple solution will work with all versions of iOS, not just iOS 6. </p>
<p>But if you needlessly wish to use <code>NSAttributedString</code>, you can do something like this:</p>
<pre><code>UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;
</code></pre> |
14,221,579 | How do I add comments to package.json for npm install? | <p>I've got a simple package.json file and I want to add a comment. Is there a way to do this, or are there any hacks to make this work?</p>
<pre class="lang-js prettyprint-override"><code>{
"name": "My Project",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x",
"mongoose": "3.x"
},
"devDependencies" : {
"should": "*"
/* "mocha": "*" not needed as should be globally installed */
}
}
</code></pre>
<p>The example comment above doesn't work as npm breaks. I've also tried // style comments.</p> | 14,221,781 | 21 | 5 | null | 2013-01-08 18:23:59.907 UTC | 72 | 2022-07-05 09:29:27.907 UTC | 2020-08-07 05:26:43.417 UTC | null | 1,402,846 | null | 68,567 | null | 1 | 508 | comments|npm | 184,826 | <p>This has recently been discussed on the <a href="https://groups.google.com/d/msg/nodejs/NmL7jdeuw0M/yTqI05DRQrIJ" rel="noreferrer">Node.js mailing list</a>.</p>
<p>According to Isaac Schlueter who created npm:</p>
<blockquote>
<p>... the "//" key will never be used by npm for any purpose, and is reserved for comments ... If you want to use a multiple line comment, you can use either an array, or multiple "//" keys.</p>
</blockquote>
<p>When using your usual tools (npm, yarn, etc.), multiple "//" keys will be removed. This survives:</p>
<pre><code>{ "//": [
"first line",
"second line" ] }
</code></pre>
<p>This will not survive:</p>
<pre><code>{ "//": "this is the first line of a comment",
"//": "this is the second line of the comment" }
</code></pre> |
29,074,376 | 404 not found , the requested URL <<url name>> not found on this server in wordpress | <p>I recently installed wordpress , I am facing issues when I try to change the permalinks format , </p>
<p>when I change the permalink from default to day and time </p>
<pre><code> Default http://127.0.0.1/?p=123
Day and name http://127.0.0.1/2015/03/16/sample-post/
</code></pre>
<p>the link generated does't working , it gives the same <code>error 404</code> all the
time ,</p>
<pre><code> The requested URL /2015/03/16/post-5-problem/ was not found on this server.
</code></pre>
<p>But when the permalink type was default this works perfectly.</p>
<p>I found some solutions which are </p>
<pre><code>sudo a2enmod rewrite
Module rewrite already enabled
</code></pre>
<p>Another solution is to <strong>change the mode permissions of .htaccess file to 666(giving write permission to wordpress of .htaccess file) before change the permalink from default to some other type ,</strong></p>
<pre><code>sudo chmod 666 /address_of_.htaccess
</code></pre>
<p>i checked the .htaccess file </p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>but the above seems to be correct , the above included by the wordpress itself </p>
<p>Both the solutions does't seem to work , is there any other thing do I have to change to enable the permalink options ?</p> | 29,074,865 | 4 | 2 | null | 2015-03-16 10:20:46.123 UTC | 2 | 2020-07-01 19:54:19.823 UTC | 2015-03-16 10:26:04.177 UTC | null | 2,264,606 | null | 2,264,606 | null | 1 | 8 | php|linux|wordpress|apache|.htaccess | 57,022 | <p>If it is a fresh install of web server it is possible that .htaccess rules are not allowed by default. To fix that, edit you httpd.conf (usually it is in /etc/apache2), find </p>
<pre><code><Directory "path/to/your/document/root">
# ....
AllowOverride None
# ....
</Directory>
</code></pre>
<p>and change </p>
<pre><code>AllowOverride None
</code></pre>
<p>to </p>
<pre><code>AllowOverride All
</code></pre>
<p>Then restart your web server and try again.</p> |
19,565,116 | redirect QEMU window output to terminal running qemu | <p>Im trying to debug the boot sequence of a linux kernel with qemu,
the command i'm running is:</p>
<pre><code> qemu -serial stdio -kernel <path to kernel> -hda <path to rootfs> -append "root=/dev/sda terminal = ttyS0"
</code></pre>
<p>During boot all the kernel messages are printed to the QEMU window.
Only when the boot has finished i get my prompt back to the terminal i ran QEMU in.</p>
<p>Now i can start using the kernel terminal I'm running and seeing the output in the terminal and not in QEMU window.</p>
<p>How do i get all messages including the boot messages to my terminal and not to QEMU window (because i cant scroll up in that window..) ?</p> | 19,569,340 | 3 | 2 | null | 2013-10-24 11:49:45.803 UTC | 8 | 2016-10-14 09:55:53.187 UTC | 2015-05-23 09:34:39.003 UTC | null | 895,245 | null | 976,281 | null | 1 | 28 | linux|debugging|linux-kernel|qemu | 61,865 | <ol>
<li>remove <code>-serial stdio</code> parameter</li>
<li>add <code>-nographic</code> parameter</li>
<li>and change the kernel parameter <code>terminal = ttyS0</code> to <code>console=ttyS0</code>. This should do the trick.</li>
</ol>
<p><code>qemu -nographic -kernel ./bzImage -hda ./image.hda -append root=/dev/sda console=ttyS0</code></p>
<p>You may want to check the script I use for kernel development: <a href="https://github.com/arapov/wrap-qemukvm" rel="noreferrer">https://github.com/arapov/wrap-qemukvm</a> (it's not very "production", but you can find useful <code>qemu</code> <code>cli</code> parameters there)</p> |
45,099,688 | ERROR : error.NonExistentClass Kotlin In multi module Dagger project | <p>I'm using Dagger 2 and Kotlin for Android development.
My project is also a multi-module project.
My settings.gradle file is like this:</p>
<pre><code>include :app
include :lib
</code></pre>
<p>I'm also maintaining the lib module.</p>
<p>In the Dagger Files (for example in the component), I try to get the item from other module. For example:</p>
<pre><code>@Component
interface AppComponent{
fun getPresenter() : Presenter
}
</code></pre>
<p>The Presenter object is defined in lib module. I was working in linux environment and I'm using Android Studio 3 preview canary 5. The code is working well and I am able to generate APK.</p>
<p>But my company wanted to generate the APK using stable version of Android Studio. I'm using Android Studio 2.3.3.</p>
<p>When compiling the Android Project, I encountered this error:</p>
<pre><code>error: error.NonExistentClass
</code></pre>
<p>The error appears when </p>
<pre><code>:app:kaptDebugKotlin
</code></pre>
<p>is performed and caused by the dagger class cannot found, the class is defined in the other project. What can be the possible workaround for this? Sorry for my bad English.</p> | 45,330,452 | 18 | 2 | null | 2017-07-14 09:41:34.007 UTC | 7 | 2021-10-13 07:42:12.11 UTC | 2018-08-27 12:42:58.933 UTC | null | 6,720,576 | null | 8,122,696 | null | 1 | 62 | android|kotlin|dagger-2|multi-module | 54,892 | <h2>The Root Cause</h2>
<p>Basically, there's not much that can be done to fix this <strong>when using <code>kapt</code></strong>. To quote <a href="https://github.com/gen0083/KotlinDaggerDataBinding/blob/master/README.md" rel="noreferrer">this link</a> that tackles the same problem in another library that uses pre-processors (OrmaDatabase):</p>
<blockquote>
<p>Because Kotlin makes its stubs before Java Annotation Processing runs,
Kotlin knows just nothing about OrmaDatabase, and the name of the
declaration in stubs will be error.NonExistentClass. This breaks the
Annotation Processing tool. It's a kind of kapt limitation</p>
</blockquote>
<h2>How to fix it (the workaround)</h2>
<p>Just use plain <code>apt</code> or <code>annotationProcessor</code> for running Dagger compiler. As soon as I changed:</p>
<pre><code>kapt libs.daggerCompiler
</code></pre>
<p>to </p>
<pre><code>annotationProcessor libs.daggerCompiler
</code></pre>
<p>in my module level <code>build.gradle</code> file, I was able to get the errors. After you've fixed the errors, you gotta revert the line back to <code>kapt</code> because otherwise dagger classes wouldn't be generated since they're defined in Kotlin.</p> |
320,999 | Execute javascript function after asp.net postback without Ajax | <p>I wish to execute a javascript function after asp.net postback with out using ajax.</p>
<p>I've tried the following in my even method with no luck:</p>
<pre><code>Page.ClientScript.RegisterStartupScript(GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);");
</code></pre> | 2,689,646 | 5 | 2 | null | 2008-11-26 15:03:58.62 UTC | 3 | 2017-06-23 17:46:24.767 UTC | null | null | null | Alexandre Brisebois | 18,619 | null | 1 | 25 | c#|asp.net|.net-2.0 | 65,029 | <p>You should rather use the ScriptManager class, since the Page.ClientScript property is deprecated...</p>
<blockquote>
<p>The ClientScriptManager class is new in ASP.NET 2.0 and replaces Page class methods for managing scripts that are now deprecated.<br />
<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx" rel="noreferrer">Reference: MSDN - Page.ClientScript Property</a></p>
</blockquote>
<p>The advantage with ScriptManager is that it works with asynchronous postbacks, so if you are using AJAX it will not work with the ClientScriptManager.</p>
<p>Your code would look like this:</p>
<pre><code>ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);", true);
</code></pre>
<p>Note also that if you are using AJAX and have a piece of javascript code, that you want executed on multiple postbacks, then you should refer to your UpdatePanel in the firstargument e.g.:</p>
<pre><code>ScriptManager.RegisterStartupScript(MainUpdatePanel, typeof(string), "ShowPopup", "showCheckOutPopIn('Livraison',556);", true);
</code></pre> |
204,184 | How to 'smooth' data and calculate line gradient? | <p>I'm reading data from a device which measures distance. My sample rate is high so that I can measure large changes in distance (i.e. velocity) but this means that, when the velocity is low, the device delivers a number of measurements which are identical (due to the granularity of the device). This results in a 'stepped' curve.</p>
<p>What I need to do is to smooth the curve in order to calculate the velocity. Following that I then need to calculate the acceleration.</p>
<p>How to best go about this?</p>
<p>(Sample rate up to 1000Hz, calculation rate of 10Hz would be ok. Using C# in VS2005)</p> | 204,229 | 6 | 0 | null | 2008-10-15 09:45:32.747 UTC | 11 | 2009-11-07 03:02:18.44 UTC | 2008-10-15 09:52:30.11 UTC | paul | 11,249 | paul | 11,249 | null | 1 | 9 | algorithm|curvesmoothing | 11,445 | <p>The wikipedia entry from moogs is a good starting point for smoothing the data. But it does not help you in making a decision.</p>
<p>It all depends on your data, and the needed processing speed.</p>
<p><strong>Moving Average</strong>
Will flatten the top values. If you are interrested in the minimum and maximum value, don't use this. Also I think using the moving average will influence your measurement of the acceleration, since it will flatten your data (a bit), thereby acceleration will appear to be smaller. It all comes down to the needed accuracy.</p>
<p><strong>Savitzky–Golay</strong>
Fast algorithm. As fast as the moving average. That will preserve the heights of peaks. Somewhat harder to implement. And you need the correct coefficients. I would pick this one.</p>
<p><strong>Kalman filters</strong>
If you know the distribution, this can give you good results (it is used in GPS navigation systems). Maybe somewhat harder to implement. I mention this because I have used them in the past. But they are probably not a good choice for a starter in this kind of stuff.</p>
<p>The above will reduce noise on your signal.</p>
<p>Next you have to do is detect the start and end point of the "acceleration". You could do this by creating a <a href="http://en.wikipedia.org/wiki/Derivative" rel="noreferrer">Derivative</a> of the original signal. The point(s) where the derivative crosses the Y-axis (zero) are probably the peaks in your signal, and might indicate the start and end of the acceleration.</p>
<p>You can then create a second degree derivative to get the minium and maximum acceleration itself.</p> |
1,190,646 | ant, jar files, and Class-Path oh my | <p>I am trying to rearchitect my build technique for creating Java jar files which depend on common 3rd party jar files. (GlazedLists, Apache Commons, etc.)</p>
<p>I had been chucking them all into {Java JRE dir}/lib/ext so they would automatically be seen by the JRE, but that led to problems like not remembering that I need to distribute certain jar files, so I'd like to learn to be more explicit.</p>
<p>So I moved them all into c:\appl\java\common\, added them to the Eclipse build path, aand defined this in my ant file:</p>
<p></p>
<pre><code><path id="javac_classpath">
<fileset dir="${libDir}">
<include name="*.jar"/>
</fileset>
<fileset dir="c:/appl/java/common">
<include name="*.jar"/>
</fileset>
</path>
</code></pre>
<p>I have my Class-Path manifest header set to "." in my <code>jar</code> task but that doesn't seem to work even if I put the relevant jar files into the same directory as my application jar file. I can add them all manually one-by-one to the Class-Path header, but I'm wondering, is there an easier way to get the Class-Path header setup properly?</p> | 1,191,020 | 6 | 0 | null | 2009-07-27 21:14:13.91 UTC | 8 | 2016-12-09 16:03:36.233 UTC | 2013-04-11 01:37:19.667 UTC | null | 214,149 | null | 44,330 | null | 1 | 22 | java|ant|jar | 45,373 | <p>This is all you need:</p>
<pre><code><path id="build-classpath">
<fileset dir="${dist}/lib">
<include name="*.jar"/>
</fileset>
</path>
<manifestclasspath property="lib.list" jarfile="${dist}/lib/myprog.jar">
<classpath refid="build-classpath"/>
</manifestclasspath>
<jar jarfile="${dist}/lib/myprog.jar"
basedir="${build}"
includes="com/my/prog/**" >
<manifest>
<attribute name="Main-Class" value="com.my.prog.MyProg"/>
<attribute name="Class-Path" value="${lib.list}"/>
</manifest>
</jar>
</code></pre>
<p>As you can probably see, it assumes you've compiled your Java classes and output them to <code>${build}</code>. It also assumes you've copied your jarfiles to <code>${dist}/lib</code>.</p>
<p>That said, it would be worth looking into other build systems which have built-in support for dependencies, such as Maven and Gradle. These other build systems have already thought through many common project structures and build operations, so you don't have to script everything down to the last detail.</p> |
3,823 | Suggestions for implementing audit tables in SQL Server? | <p>One simple method I've used in the past is basically just creating a second table whose structure mirrors the one I want to audit, and then create an update/delete trigger on the main table. Before a record is updated/deleted, the current state is saved to the audit table via the trigger.</p>
<p>While effective, the data in the audit table is not the most useful or simple to report off of. I'm wondering if anyone has a better method for auditing data changes?</p>
<p>There shouldn't be too many updates of these records, but it is highly sensitive information, so it is important to the customer that all changes are audited and easily reported on.</p> | 3,848 | 6 | 3 | null | 2008-08-06 18:39:33.56 UTC | 8 | 2016-05-07 03:13:05.32 UTC | 2016-05-07 03:13:05.32 UTC | Oli | 116 | null | 423 | null | 1 | 32 | sql|sql-server|database|audit | 13,820 | <p>How much writing vs. reading of this table(s) do you expect?</p>
<p>I've used a single audit table, with columns for Table, Column, OldValue, NewValue, User, and ChangeDateTime - generic enough to work with any other changes in the DB, and while a LOT of data got written to that table, reports on that data were sparse enough that they could be run at low-use periods of the day.</p>
<p><strong>Added:</strong>
If the amount of data vs. reporting is a concern, the audit table could be replicated to a read-only database server, allowing you to run reports whenever necessary without bogging down the master server from doing their work.</p> |
908,672 | Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code? | <p>Consider:</p>
<pre><code>import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.io.*;
public class EncryptURL extends JApplet implements ActionListener {
Container content;
JTextField userName = new JTextField();
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JTextField email = new JTextField();
JTextField phone = new JTextField();
JTextField heartbeatID = new JTextField();
JTextField regionCode = new JTextField();
JTextField retRegionCode = new JTextField();
JTextField encryptedTextField = new JTextField();
JPanel finishPanel = new JPanel();
public void init() {
//setTitle("Book - E Project");
setSize(800, 600);
content = getContentPane();
content.setBackground(Color.yellow);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
JButton submit = new JButton("Submit");
content.add(new JLabel("User Name"));
content.add(userName);
content.add(new JLabel("First Name"));
content.add(firstName);
content.add(new JLabel("Last Name"));
content.add(lastName);
content.add(new JLabel("Email"));
content.add(email);
content.add(new JLabel("Phone"));
content.add(phone);
content.add(new JLabel("HeartBeatID"));
content.add(heartbeatID);
content.add(new JLabel("Region Code"));
content.add(regionCode);
content.add(new JLabel("RetRegionCode"));
content.add(retRegionCode);
content.add(submit);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Submit"){
String subUserName = userName.getText();
String subFName = firstName.getText();
String subLName = lastName.getText();
String subEmail = email.getText();
String subPhone = phone.getText();
String subHeartbeatID = heartbeatID.getText();
String subRegionCode = regionCode.getText();
String subRetRegionCode = retRegionCode.getText();
String concatURL =
"user=" + subUserName + "&f=" + subFName +
"&l=" + subLName + "&em=" + subEmail +
"&p=" + subPhone + "&h=" + subHeartbeatID +
"&re=" + subRegionCode + "&ret=" + subRetRegionCode;
concatURL = padString(concatURL, ' ', 16);
byte[] encrypted = encrypt(concatURL);
String encryptedString = bytesToHex(encrypted);
content.removeAll();
content.add(new JLabel("Concatenated User Input -->" + concatURL));
content.add(encryptedTextField);
setContentPane(content);
}
}
public static byte[] encrypt(String toEncrypt) throws Exception{
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
}
catch(Exception e){
}
}
public static byte[] decrypt(byte[] toDecrypt) throws Exception{
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decrypted = cipher.doFinal(toDecrypt);
return decrypted;
}
public static String bytesToHex(byte[] data) {
if (data == null)
{
return null;
}
else
{
int len = data.length;
String str = "";
for (int i=0; i<len; i++)
{
if ((data[i]&0xFF) < 16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
}
public static String padString(String source, char paddingChar, int size)
{
int padLength = size-source.length() % size;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
}
</code></pre>
<p>I'm getting an unreported exception:</p>
<pre><code>java.lang.Exception; must be caught or declared to be thrown
byte[] encrypted = encrypt(concatURL);
</code></pre>
<p>As well as:</p>
<pre><code>.java:109: missing return statement
</code></pre>
<p>How do I solve these problems?</p> | 908,714 | 6 | 1 | null | 2009-05-26 02:22:57.05 UTC | 12 | 2018-04-15 20:55:20.873 UTC | 2018-04-15 20:55:20.873 UTC | null | 63,550 | null | 51,898 | null | 1 | 48 | java|exception | 206,426 | <p>All your problems derive from this</p>
<pre><code>byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
</code></pre>
<p>Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):</p>
<pre><code>public static byte[] encrypt(String toEncrypt) throws Exception{
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
} catch(Exception e){
return null; // Always must return something
}
}
</code></pre>
<p>For the second one you must catch the Exception from the <em>encrypt</em> method call, like this (also modify it as your program logic stands):</p>
<pre><code>public void actionPerformed(ActionEvent e)
.
.
.
try {
byte[] encrypted = encrypt(concatURL);
String encryptedString = bytesToHex(encrypted);
content.removeAll();
content.add(new JLabel("Concatenated User Input -->" + concatURL));
content.add(encryptedTextField);
setContentPane(content);
} catch (Exception exc) {
// TODO: handle exception
}
}
</code></pre>
<p>The lessons you must learn from this:</p>
<ul>
<li>A method with a return-type must <strong>always</strong> return an object of that type, I mean in all possible scenarios</li>
<li>All checked exceptions must <strong>always</strong> be handled</li>
</ul> |
39,144,688 | AWS lambda invoke not calling another lambda function - Node.js | <p>After giving all the rights to invoke function. My Lambda function is not able to invoke another function . Every time I am getting timeout having <code>30 seconds timeout</code> issue. It looks like lambda is not able to get another lambda function</p>
<p>My lambdas are in same region, same policy, same security group .. Also VPC are same in both lambdas. The only thing is different now is lambda functions </p>
<p>Here are the role rights </p>
<p>1) created <code>AWSLambdaExecute</code> and <code>AWSLambdaBasicExecutionRole</code> </p>
<p>2) Created one lambda function which is to be called
<strong>Lambda_TEST</strong></p>
<pre><code>exports.handler = function(event, context) {
console.log('Lambda TEST Received event:', JSON.stringify(event, null, 2));
context.succeed(event);
};
</code></pre>
<p>3) Here is a another function from where it is called .</p>
<pre><code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var lambda = new AWS.Lambda();
exports.handler = function(event, context) {
var params = {
FunctionName: 'Lambda_TEST', // the lambda function we are going to invoke
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: '{ "name" : "Arpit" }'
};
lambda.invoke(params, function(err, data) {
if (err) {
context.fail(err);
} else {
context.succeed('Lambda_TEST said '+ data.Payload);
}
})
};
</code></pre>
<p>Reference taken from : <a href="https://stackoverflow.com/questions/35754766/nodejs-invoke-an-aws-lambda-function-from-within-another-lambda-function">This link</a></p> | 39,206,646 | 3 | 9 | null | 2016-08-25 11:57:31.907 UTC | 15 | 2021-11-24 20:00:13.413 UTC | 2018-08-01 06:03:48.547 UTC | null | 4,122,849 | null | 224,519 | null | 1 | 55 | amazon-web-services|aws-lambda|aws-sdk|amazon-iam | 21,476 | <h2>Note</h2>
<p>I will denote by <em>executor</em> the <code>lambda</code> that executes the second <code>lambda</code>.</p>
<hr>
<h2>Why Timeout?</h2>
<p>Since the <em>executor</em> is "locked" behind a <code>VPC</code> - all internet communications are blocked.</p>
<p>That results in any <code>http(s)</code> calls to be timed out as they request packet never gets to the destination.</p>
<p>That is why all actions done by <code>aws-sdk</code> result in a timeout.</p>
<hr>
<h2>Simple Solution</h2>
<p>If the <em>executor</em> does not <strong>have</strong> to be in a <code>VPC</code> - just put it out of it, a <code>lambda</code> can work as well without a <code>VPC</code>. </p>
<p>Locating the <code>lambda</code> in a <code>VPC</code> is required when the <code>lambda</code> calls resources inside the <code>VPC</code>.</p>
<h2>Real Solution</h2>
<p>From the above said, it follows that any resource located inside a <code>VPC</code> cannot access the internet - <strong>that is not correct</strong> - just few configurations need to be made.</p>
<ol>
<li>Create a <code>VPC</code>.</li>
<li>Create 2 <em>Subnets</em>, let one be denoted as <em>private</em> and the second <em>public</em> (these terms are explained ahead, keep reading).</li>
<li>Create an <em>Internet Gateway</em> - this is a virtual router that connects a <code>VPC</code> to the internet.</li>
<li>Create a <em>NAT Gateway</em> - pick the <strong>public</strong> subnet and create a new <code>elastic IP</code> for it (this IP is local to your <code>VPC</code>) - this component will pipe communications to the <code>internet-gateway</code>.</li>
<li><p>Create 2 <em>Routing Tables</em> - one named <em>public</em> and the second <em>private</em>.</p>
<ol>
<li>In the <em>public</em> routing table, go to <em>Routes</em> and add a new route:</li>
</ol>
<blockquote>
<p>Destination: 0.0.0.0/0 </p>
<p>Target: the ID of the <code>internet-gateway</code></p>
</blockquote>
<ol start="2">
<li>In the <em>private</em> routing table, go to <em>Routes</em> and add a new route:</li>
</ol>
<blockquote>
<p>Destination: 0.0.0.0/0 </p>
<p>Target: the ID of the <code>nat-gateway</code></p>
</blockquote>
<ul>
<li><p>A <em>private</em> subnet is a subnet that in its routing table - there <strong>is no</strong> route to an <code>internet-gateway</code>.</p></li>
<li><p>A <em>public</em> subnet is a subnet that in its routing table - there <strong>exists</strong> a route to an <code>internet-gateway</code></p></li>
</ul></li>
</ol>
<hr>
<h2>What we had here?</h2>
<p>We created something like this:</p>
<p><a href="https://i.stack.imgur.com/X53oI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X53oI.png" alt="VPC with NAT and IGW"></a></p>
<p>This, what allows resources in <em>private</em> subnets to call out the internet.
You can find more documentation <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html" rel="noreferrer">here</a>.</p> |
35,625,247 | Android - Is it ok to put @IntDef values inside @interface? | <p>I'm trying to implement <code>@IntDef</code> annotation in Android development.</p>
<p><strong>First Method</strong>: it looks great with the definition separated in a <code>Constant.java</code> class:</p>
<pre><code>public class Constant {
@IntDef(value={SORT_PRICE, SORT_TIME, SORT_DURATION})
@Retention(RetentionPolicy.SOURCE)
public @interface SortType{}
public static final int SORT_PRICE = 0;
public static final int SORT_TIME = 1;
public static final int SORT_DURATION = 2;
}
</code></pre>
<p>Usage:</p>
<pre><code>@Constant.SortType int sortType = Constant.SORT_PRICE;
</code></pre>
<p>But things get a lot messier when there's multiple definition (e.g UserType, StoreType, etc) in one file. </p>
<p><strong>Second Method:</strong> So I came up with something like this to separate values between definition:</p>
<pre><code>public class Constant {
@IntDef(value={SortType.SORT_PRICE, SortType.SORT_TIME, SortType.SORT_DURATION})
@Retention(RetentionPolicy.SOURCE)
public @interface SortTypeDef{}
public static class SortType{
public static final int PRICE = 0;
public static final int TIME = 1;
public static final int DURATION = 2;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>@Constant.SortTypeDef int sortType = Constant.SortType.PRICE;
</code></pre>
<p>But as you can see, I created two different name for it: <code>SortTypeDef</code> and <code>SortType</code></p>
<p><strong>Third Method:</strong> I tried to move the list of possible values inside <code>@interface</code>:</p>
<pre><code>public class Constant {
@IntDef(value={SortType.SORT_PRICE, SortType.SORT_TIME, SortType.SORT_DURATION})
@Retention(RetentionPolicy.SOURCE)
public @interface SortType{
int PRICE = 0;
int TIME = 1;
int DURATION = 2;
}
}
</code></pre>
<p>Usage </p>
<pre><code>@Constant.SortType int sortType = Constant.SortType.PRICE;
</code></pre>
<p>While it does work, I don't know what is the drawback.
Is it okay to put the possible values of <code>@IntDef</code> inside <code>@interface</code>? Is there any performance differences across the three methods above?</p> | 45,175,692 | 4 | 3 | null | 2016-02-25 10:53:33.767 UTC | 7 | 2018-08-06 09:42:50.693 UTC | 2016-05-06 18:28:43.037 UTC | null | 1,404,939 | null | 1,404,939 | null | 1 | 44 | java|android|annotations | 5,607 | <p><strong>Short answer</strong>: for simple projects, it is OK, but for more complex ones the first method is preferred.</p>
<p><strong>Long answer</strong>:
Although bytecode for <code>sortType</code> is identical in all three cases, there is a difference. The key lies in the <code>Retention</code> annotation, which sets retention policy to <code>SOURCE</code>. That means that your <code>SortType</code> annotation is "<a href="https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html" rel="noreferrer">to be discarded by the compiler</a>", so bytecode for annotation itself is not generated.</p>
<p>First method defines regular static fields outside the annotations, with the regular bytecode generated for them. Second and third cases define constants within annotations, and bytecode for the constants is not generated.</p>
<p>If compiler has access to the source file containing your <code>SortType</code> declaration, either method is fine and bytecode for <code>sortType</code> is identical. But if source code is not accessible (e.g. you have only compiled library), annotation is not accessible. For the first approach, only annotation itself is not accessible, but for the latter ones, constants values are not accessible too.</p>
<p>I used to prefer the third method as the most clean and structured. I used to until one day I ran into an issue: when I started writing Espresso tests for that code, compiler did not have access to the source code defining the annotation. I had to either switch to the canonical <code>IntDef</code> declaration or to use integer values instead of symbolic constants for the test.</p>
<p>So the bottom line is:</p>
<ul>
<li>stick to the canonical way unless your annotation is internal to your code and you do not refer to it from anywhere else, including tests</li>
</ul> |
1,967,604 | How can I get functionality similar to Spy++ in my C# app? | <p>I'm interested in working on a plugin for <a href="http://keepass.info/" rel="noreferrer">Keepass</a>, the open-source password manager. Right now, <a href="http://keepass.info/" rel="noreferrer">Keepass</a> currently detects what password to copy/paste for you based off of the window title. This prevents Keepass from detecting the current password you need for apps that don't actively update their window title based on the current site (Chrome for instance).</p>
<p>How can I walk through another processes window elements (buttons, labels, textbox) similar to how Spy++ works? When you run Spy++ you can hover over other programs windows and get all kinds of information about various properties concerning various controls (labels, textboxes, etc). Ideally, I'd like my Keepass plugin to enhance the current window detection by walking through the active window's elements in an effort to find a matching account to copy/paste the password.</p>
<p>How can I walk other processes window elements and be able to retrieve label and textbox values using C#?</p> | 1,967,699 | 5 | 1 | null | 2009-12-28 01:02:22.467 UTC | 17 | 2016-05-26 20:01:47.137 UTC | 2009-12-28 21:45:02.63 UTC | anon | null | anon | null | null | 1 | 10 | c#|winapi|spy++ | 23,054 | <p>I've being answering similar questions like this here: <a href="https://stackoverflow.com/questions/1922982/how-can-i-detect-if-a-thread-has-windows-handles/1926162#1926162">How can I detect if a thread has windows handles?</a>. Like it states, the main idea is to enumerate through process windows and their child windows using <a href="http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx" rel="nofollow noreferrer">EnumWindows</a> and <a href="http://msdn.microsoft.com/en-us/library/ms633494(VS.85).aspx" rel="nofollow noreferrer">EnumChildWindows</a> API calls to get window handles and then call GetWindowText or SendDlgItemMessage with WM_GETTEXT to get window text. I've modified code to make an example which should be doing what you need (sorry it's a bit long :). It iterates through processes and their windows and dumps window text into console.</p>
<pre><code>static void Main(string[] args)
{
foreach (Process procesInfo in Process.GetProcesses())
{
Console.WriteLine("process {0} {1:x}", procesInfo.ProcessName, procesInfo.Id);
foreach (ProcessThread threadInfo in procesInfo.Threads)
{
// uncomment to dump thread handles
//Console.WriteLine("\tthread {0:x}", threadInfo.Id);
IntPtr[] windows = GetWindowHandlesForThread(threadInfo.Id);
if (windows != null && windows.Length > 0)
foreach (IntPtr hWnd in windows)
Console.WriteLine("\twindow {0:x} text:{1} caption:{2}",
hWnd.ToInt32(), GetText(hWnd), GetEditText(hWnd));
}
}
Console.ReadLine();
}
private static IntPtr[] GetWindowHandlesForThread(int threadHandle)
{
_results.Clear();
EnumWindows(WindowEnum, threadHandle);
return _results.ToArray();
}
// enum windows
private delegate int EnumWindowsProc(IntPtr hwnd, int lParam);
[DllImport("user32.Dll")]
private static extern int EnumWindows(EnumWindowsProc x, int y);
[DllImport("user32")]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowsProc callback, int lParam);
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
private static List<IntPtr> _results = new List<IntPtr>();
private static int WindowEnum(IntPtr hWnd, int lParam)
{
int processID = 0;
int threadID = GetWindowThreadProcessId(hWnd, out processID);
if (threadID == lParam)
{
_results.Add(hWnd);
EnumChildWindows(hWnd, WindowEnum, threadID);
}
return 1;
}
// get window text
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
private static string GetText(IntPtr hWnd)
{
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
// get richedit text
public const int GWL_ID = -12;
public const int WM_GETTEXT = 0x000D;
[DllImport("User32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int index);
[DllImport("User32.dll")]
public static extern IntPtr SendDlgItemMessage(IntPtr hWnd, int IDDlgItem, int uMsg, int nMaxCount, StringBuilder lpString);
[DllImport("User32.dll")]
public static extern IntPtr GetParent(IntPtr hWnd);
private static StringBuilder GetEditText(IntPtr hWnd)
{
Int32 dwID = GetWindowLong(hWnd, GWL_ID);
IntPtr hWndParent = GetParent(hWnd);
StringBuilder title = new StringBuilder(128);
SendDlgItemMessage(hWndParent, dwID, WM_GETTEXT, 128, title);
return title;
}
</code></pre>
<p>hope this helps, regards</p> |
1,936,682 | How do I display a file's Properties dialog from C#? | <p>how to open an file's Properties dialog by a button </p>
<pre><code>private void button_Click(object sender, EventArgs e)
{
string path = @"C:\Users\test\Documents\tes.text";
// how to open this propertie
}
</code></pre>
<p>Thank you.</p>
<p>For example if want the System properties </p>
<pre><code>Process.Start("sysdm.cpl");
</code></pre>
<p>But how do i get the Properties dialog for a file path?</p> | 1,936,957 | 5 | 3 | null | 2009-12-20 19:20:19.22 UTC | 12 | 2022-05-02 14:58:16.95 UTC | 2009-12-20 19:49:51.35 UTC | null | 61,700 | null | 224,998 | null | 1 | 32 | c# | 13,735 | <p>Solution is:</p>
<pre><code>using System.Runtime.InteropServices;
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;
public static bool ShowFileProperties(string Filename)
{
SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
info.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
info.lpVerb = "properties";
info.lpFile = Filename;
info.nShow = SW_SHOW;
info.fMask = SEE_MASK_INVOKEIDLIST;
return ShellExecuteEx(ref info);
}
// button click
private void button1_Click(object sender, EventArgs e)
{
string path = @"C:\Users\test\Documents\test.text";
ShowFileProperties(path);
}
</code></pre> |
2,262,704 | iPhone Core Data "Production" Error Handling | <p>I've seen in the example code supplied by Apple references to how you should handle Core Data errors. I.e:</p>
<pre><code>NSError *error = nil;
if (![context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
</code></pre>
<p>But never any examples of how you <em>should</em> implement it.</p>
<p>Does anyone have (or can point me in the direction of) some actual "production" code that illustrates the above method.</p>
<p>Thanks in advance,
Matt</p> | 2,262,808 | 5 | 1 | null | 2010-02-14 20:49:13.597 UTC | 47 | 2017-06-24 09:32:59.503 UTC | 2015-01-22 01:04:24.417 UTC | null | 2,357,233 | null | 84,431 | null | 1 | 87 | iphone|core-data|error-handling | 10,632 | <p>No one is going to show you production code because it depends 100% on your application and where the error occurs.</p>
<p>Personally, I put an assert statement in there because 99.9% of the time this error is going to occur in development and when you fix it there it is <em>highly</em> unlikely you will see it in production. </p>
<p>After the assert I would present an alert to the user, let them know an unrecoverable error occurred and that the application is going to exit. You can also put a blurb in there asking them to contact the developer so that you can hopefully track this done.</p>
<p>After that I would leave the abort() in there as it will "crash" the app and generate a stack trace that you can hopefully use later to track down the issue.</p> |
1,812,473 | Difference between Url Encode and HTML encode | <p>What’s the difference between an <a href="http://meyerweb.com/eric/tools/dencoder/" rel="noreferrer">URL Encode</a> and a <a href="http://www.opinionatedgeek.com/dotnet/tools/htmlencode/Encode.aspx" rel="noreferrer">HTML Encode</a>? </p> | 1,812,486 | 5 | 3 | null | 2009-11-28 12:56:48.953 UTC | 34 | 2021-01-28 02:01:27.997 UTC | null | null | null | null | 113,247 | null | 1 | 94 | html|url|encoding|character-encoding | 82,528 | <p>HTML Encoding escapes special characters in strings used in HTML documents to prevent confusion with HTML elements like changing</p>
<pre><code>"<hello>world</hello>"
</code></pre>
<p>to</p>
<pre><code>"&lt;hello&gt;world&lt;/hello&gt;"
</code></pre>
<p>URL Encoding does a similar thing for string values in a URL like changing</p>
<pre><code>"hello+world = hello world"
</code></pre>
<p>to</p>
<pre><code>"hello%2Bworld+%3D+hello+world"
</code></pre> |
1,779,117 | How to get a List<string> collection of values from app.config in WPF? | <p>The following example fills the <strong>ItemsControl</strong> with a List of <strong>BackupDirectories</strong> which I get from code.</p>
<p><strong>How can I change this so that I get the same information from the app.config file?</strong></p>
<p><strong>XAML:</strong></p>
<pre class="lang-xml prettyprint-override"><code><Window x:Class="TestReadMultipler2343.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="160"/>
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Text="Title:"/>
<TextBlock
Grid.Row="0"
Grid.Column="1"
Text="{Binding Title}"/>
<TextBlock
Grid.Row="1"
Grid.Column="0"
Text="Backup Directories:"/>
<ItemsControl
Grid.Row="1"
Grid.Column="1"
ItemsSource="{Binding BackupDirectories}"/>
</Grid>
</Window>
</code></pre>
<p><strong>code-behind:</strong></p>
<pre><code>using System.Collections.Generic;
using System.Windows;
using System.Configuration;
using System.ComponentModel;
namespace TestReadMultipler2343
{
public partial class Window1 : Window, INotifyPropertyChanged
{
#region ViewModelProperty: Title
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
#endregion
#region ViewModelProperty: BackupDirectories
private List<string> _backupDirectories = new List<string>();
public List<string> BackupDirectories
{
get
{
return _backupDirectories;
}
set
{
_backupDirectories = value;
OnPropertyChanged("BackupDirectories");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
Title = ConfigurationManager.AppSettings.Get("title");
GetBackupDirectoriesInternal();
}
void GetBackupDirectoriesInternal()
{
BackupDirectories.Add(@"C:\test1");
BackupDirectories.Add(@"C:\test2");
BackupDirectories.Add(@"C:\test3");
BackupDirectories.Add(@"C:\test4");
}
void GetBackupDirectoriesFromConfig()
{
//BackupDirectories = ConfigurationManager.AppSettings.GetValues("backupDirectories");
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
</code></pre>
<p><strong>app.config:</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="title" value="Backup Tool" />
<!--<add key="backupDirectories">
<add value="C:\test1"/>
<add value="C:\test2"/>
<add value="C:\test3"/>
<add value="C:\test4"/>
</add>-->
</appSettings>
</configuration>
</code></pre> | 1,779,453 | 8 | 4 | null | 2009-11-22 15:59:34.647 UTC | 22 | 2021-08-06 23:09:10.927 UTC | 2017-01-30 07:15:53.367 UTC | null | 3,214,843 | null | 4,639 | null | 1 | 84 | c#|wpf|itemscontrol|app-config | 187,222 | <p>You can create your own custom config section in the app.config file. There are quite a <a href="http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx#elementcolls" rel="noreferrer">few</a> <a href="http://msdn.microsoft.com/en-us/library/2tw134k3.aspx" rel="noreferrer">tutorials</a> <a href="http://www.codeproject.com/KB/files/CustomConfigSection.aspx" rel="noreferrer">around</a> to get you started. Ultimately, you could have something like this:</p>
<pre><code><configSections>
<section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
</configSections>
<backupDirectories>
<directory location="C:\test1" />
<directory location="C:\test2" />
<directory location="C:\test3" />
</backupDirectories>
</code></pre>
<p>To complement Richard's answer, this is the C# you could use with his sample configuration:</p>
<pre><code>using System.Collections.Generic;
using System.Configuration;
using System.Xml;
namespace TestReadMultipler2343
{
public class BackupDirectoriesSection : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
List<directory> myConfigObject = new List<directory>();
foreach (XmlNode childNode in section.ChildNodes)
{
foreach (XmlAttribute attrib in childNode.Attributes)
{
myConfigObject.Add(new directory() { location = attrib.Value });
}
}
return myConfigObject;
}
}
public class directory
{
public string location { get; set; }
}
}
</code></pre>
<p>Then you can access the backupDirectories configuration section as follows:</p>
<pre><code>List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;
</code></pre> |
1,370,449 | Debug.WriteLine not working | <p>In the past, perhaps versions of Visual Studio prior to the 2008 that I am using now, I would do something like this in my VB.NET code:</p>
<pre><code>System.Diagnostics.Debug.WriteLine("Message")
</code></pre>
<p>..and the output would go to the output window.</p>
<p>Now it doesn't. Something must first apparently be enabled. </p>
<p>If this involves "attaching a debugger", please explain how to do it. It seems to me that it should just work without too much of a fuss.</p>
<p>Here's a video explaining the issue in real time and showing you all my settings:</p>
<p><a href="http://screencast.com/t/YQnPb0mJcs" rel="noreferrer">http://screencast.com/t/YQnPb0mJcs</a></p>
<p>I'm using Visual Studio 2008.</p> | 7,196,388 | 13 | 0 | null | 2009-09-02 22:18:02.313 UTC | 7 | 2017-02-22 20:37:18.707 UTC | 2016-02-25 10:08:02.703 UTC | null | 63,550 | null | 109,676 | null | 1 | 35 | vb.net|debugging | 46,332 | <p>All good suggestions. I noticed that I don't see this tip mentioned, so I'll say it: <strong>In your app.config file, make sure you don't have a <code><clear/></code> element</strong> in your trace listeners.</p>
<p>You will effectively be clearing the list of trace listeners, <em>including the default trace listener used for Debug statements.</em></p>
<p>Here's what this would look like in your app.config file:</p>
<pre><code><system.diagnostics>
<trace>
<listeners>
<!-- This next line is the troublemaker. It looks so innocent -->
<clear/>
</listeners>
</trace>
</system.diagnostics>
</code></pre>
<p>If you want to have a placeholder for trace listeners in your app.config file, you should instead use something like this:</p>
<pre><code><system.diagnostics>
<trace>
<listeners>
</listeners>
</trace>
</system.diagnostics>
</code></pre> |
2,043,999 | Easiest way to simulate no free disk space situation? | <p>I need to test my web app in a scenario where there’s no disk space remaining, i.e. I cannot write any more files. But I don’t want to fill my hard drive with junk just to make sure there’s really no space left. What I want is to simulate this situation withing a particular process (actually, a PHP app).</p>
<p>Indeed, temporarily prohibiting disk writes to a process must be enough.</p>
<p>What’s the easiest way to do this? I’m using Mac OS X 10.6.2 with built-in Apache/PHP bundle. Thanks.</p>
<p><strong>Edit</strong>: Disk free space check is not going to be reliable since it can change any moment. Many pages are being served simultaneously. There can be enough free space when checking, but none by the moment you actually write something. Also, checking for disk free space will require changing the code everywhere I write a file, which is not what I want :-) Finally, this solution is exactly the opposite of what I’m trying to test: how my app will behave when it cannot write any more.</p> | 2,044,044 | 13 | 0 | null | 2010-01-11 18:37:15.52 UTC | 6 | 2010-11-19 17:04:27.84 UTC | 2010-01-12 07:37:02.413 UTC | null | 65,813 | null | 65,813 | null | 1 | 35 | php|apache|macos|testing|diskspace | 9,641 | <p>I bet you could also create your own .dmg file with file system of size ... say 2Mb and write to it. If this works, then it is super-easy for testing - you just mount it and switch the path for testing. If the dmg is small enough, you could probably even upload it to the source control.</p> |
46,317,061 | How do I use Safe Area Layout programmatically? | <p>Since I don't use storyboards to create my views, I was wondering if there's the "Use Safe Area Guides" option programmatically or something like that. </p>
<p>I've tried to anchor my views to </p>
<p><code>view.safeAreaLayoutGuide</code></p>
<p>but they keep overlapping the top notch in the iPhone X simulator.</p> | 46,318,300 | 11 | 4 | null | 2017-09-20 08:30:20.76 UTC | 57 | 2021-05-27 10:31:54.52 UTC | 2020-02-22 10:23:08.733 UTC | null | 5,367,106 | null | 781,322 | null | 1 | 124 | ios|swift|iphone-x|safearealayoutguide | 169,376 | <p>Here is sample code (Ref from: <a href="https://useyourloaf.com/blog/safe-area-layout-guide/" rel="noreferrer">Safe Area Layout Guide</a>):
<br>If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:</p>
<p>Assuming we have the green view as a property in our view controller:</p>
<pre><code>private let greenView = UIView()
</code></pre>
<p>We might have a function to set up the views and constraints called from viewDidLoad:</p>
<pre><code>private func setupView() {
greenView.translatesAutoresizingMaskIntoConstraints = false
greenView.backgroundColor = .green
view.addSubview(greenView)
}
</code></pre>
<p>Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:</p>
<pre><code> let margins = view.layoutMarginsGuide
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
])
</code></pre>
<p>Now, unless you are targeting iOS 11 and later, you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:</p>
<pre><code>if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
])
} else {
let standardSpacing: CGFloat = 8.0
NSLayoutConstraint.activate([
greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
])
}
</code></pre>
<p><strong>Result:</strong></p>
<p><img src="https://i.stack.imgur.com/Aqh7X.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/w02LN.gif" alt="enter image description here"></p>
<p><br>
Here is Apple Developer Official Documentation for <a href="https://developer.apple.com/documentation/uikit/uiview/2891102-safearealayoutguide" rel="noreferrer">Safe Area Layout Guide</a></p>
<p><br>Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for <a href="https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/" rel="noreferrer">How to design user interface for iPhone-X using Safe Area Layout</a></p> |
6,844,462 | polygon union without holes | <p>Im looking for some fairly easy (I know polygon union is NOT an easy operation but maybe someone could point me in the right direction with a relativly easy one) algorithm on merging two intersecting polygons. Polygons could be concave without holes and also output polygon should not have holes in it. Polygons are represented in counter-clockwise manner. What I mean is presented on a picture. As you can see even if there is a hole in union of polygons I dont need it in the output. Input polygons are for sure without holes. I think without holes it should be easier to do but still I dont have an idea.
<img src="https://i.stack.imgur.com/2QzP5.png" alt="Polygons - blue and red are input, green is output"></p> | 6,844,668 | 3 | 1 | null | 2011-07-27 12:42:20.083 UTC | 13 | 2020-11-18 15:00:25.777 UTC | 2011-08-12 12:50:30.62 UTC | null | 811,001 | null | 507,549 | null | 1 | 23 | algorithm|math|geometry|polygon|computational-geometry | 13,225 | <ol>
<li>Remove all the vertices of the polygons which lie inside the other polygon: <a href="http://paulbourke.net/geometry/insidepoly/" rel="noreferrer">http://paulbourke.net/geometry/insidepoly/</a></li>
<li>Pick a starting point that is guaranteed to be in the union polygon (one of the extremes would work)</li>
<li>Trace through the polygon's edges in counter-clockwise fashion. These are points in your union. Trace until you hit an intersection (note that an edge may intersect with more than one edge of the other polygon).</li>
<li>Find the first intersection (if there are more than one). This is a point in your Union.</li>
<li>Go back to step 3 with the other polygon. The next point should be the point that makes the greatest angle with the previous edge.</li>
</ol> |
6,511,096 | __cdecl or __stdcall on Windows? | <p>I'm currently developing a C++ library for Windows which will be distributed as a DLL. My goal is to maximize binary interoperability; more precisely, the functions in my DLL must be usable from code compiled with multiple versions of MSVC++ and MinGW without having to recompile the DLL. However, I'm confused about which calling convention is best, <a href="http://msdn.microsoft.com/en-us/library/zkwh89ks.aspx" rel="noreferrer"><code>cdecl</code></a> or <a href="http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx" rel="noreferrer"><code>stdcall</code></a>.</p>
<p>Sometimes I hear statements like "the C calling convention is the only one guaranteed to be the same accross compilers", which contrasts with statements like "<a href="http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl" rel="noreferrer">There are some variations in the interpretation of <code>cdecl</code>, particularly in how to return values</a>". This doesn't seem to stop certain library developers (like <a href="http://www.mega-nerd.com/libsndfile/" rel="noreferrer">libsndfile</a>) to use the C calling convention in the DLLs they distribute, without any visible problems.</p>
<p>On the other hand, the <code>stdcall</code> calling convention seems to be well-defined. From what I've been told, all Windows compilers are basically required to follow it because it's the convention used for Win32 and COM. This is based on the assumption that a Windows compiler without Win32/COM support would not be very useful. A lot of code snippets posted on forums declare functions as <code>stdcall</code> but I can't seem to find one single post which clearly explains <em>why</em>.</p>
<p>There's too much conflicting information out there, and every search I run gives me different answers which doesn't really help me decide between the two. I'm searching for a clear, detailed, argumented explanation as to why I should choose one over the other (or why the two are equivalent).</p>
<p>Note that this question not only applies to "classic" functions, but also to virtual member function calls, since most client code will interface with my DLL through "interfaces", pure virtual classes (following patterns described e.g. <a href="https://stackoverflow.com/questions/232926/how-to-make-consistent-dll-binaries-across-vs-versions/232959#232959">here</a> and <a href="http://chadaustin.me/cppinterface.html" rel="noreferrer">there</a>).</p> | 6,635,067 | 3 | 2 | null | 2011-06-28 18:07:57.383 UTC | 38 | 2014-06-13 13:49:29.753 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 172,594 | null | 1 | 90 | c++|windows|dll|calling-convention|binary-compatibility | 56,326 | <p>I just did some real-world testing (compiling DLLs and applications with MSVC++ and MinGW, then mixing them). As it appears, I had better results with the <code>cdecl</code> calling convention.</p>
<p>More specifically: the problem with <code>stdcall</code> is that MSVC++ mangles names in the DLL export table, even when using <code>extern "C"</code>. For example <code>foo</code> becomes <code>_foo@4</code>. This only happens when using <code>__declspec(dllexport)</code>, not when using a DEF file; however, DEF files are a maintenance hassle in my opinion, and I don't want to use them.</p>
<p>The MSVC++ name mangling poses two problems:</p>
<ul>
<li>Using <a href="http://msdn.microsoft.com/en-us/library/ms683212%28v=VS.85%29.aspx"><code>GetProcAddress</code></a> on the DLL becomes slightly more complicated;</li>
<li>MinGW by default doesn't prepend an undescore to the decorated names (e.g. MinGW will use <code>foo@4</code> instead of <code>_foo@4</code>), which complicates linking. Also, it introduces the risk of seeing "non-underscore versions" of DLLs and applications pop up in the wild which are incompatible with the "underscore versions".</li>
</ul>
<p>I've tried the <code>cdecl</code> convention: interoperability between MSVC++ and MinGW works perfectly, out-of-the-box, and names stay undecorated in the DLL export table. It even works for virtual methods.</p>
<p>For these reasons, <code>cdecl</code> is a clear winner for me.</p> |
6,422,199 | What is the difference between `after_create` and `after_save` and when to use which? | <p>Are <code>after_create</code> and <code>after_save</code> the same as per functionality?</p>
<p>I want to do an operation with the email of a user after its account creation.</p>
<p>I want to do that operation when it is saved in the database.</p>
<p>which is preferable to use: <code>after_create</code> or <code>after_save</code>?</p> | 6,422,221 | 3 | 0 | null | 2011-06-21 08:10:01.913 UTC | 16 | 2017-04-22 08:05:03.05 UTC | 2015-04-24 17:32:57.947 UTC | null | 2,202,702 | null | 617,631 | null | 1 | 133 | ruby-on-rails|ruby|ruby-on-rails-3 | 50,990 | <p><code>after_create</code> only works once - just after the record is first created.</p>
<p><code>after_save</code> works every time you save the object - even if you're just updating it many years later</p>
<p>So if you want to do this email operation only just the once (and then never again) then use <code>after_create</code>.</p>
<p>If you want to do it <em>every</em> time the object is saved, then do it in <code>after_save</code></p> |
18,581,379 | How to save the contents of a div as a image? | <p>Basically, I am doing what the heading states, attempting to save the contents of a div as an image.</p>
<p>I plan on making a small online application for the iPad.</p>
<p>One function that is a must is having a 'Save' button that can save the full webpage as an image, and save that image to the iPad's camera roll. I wish to save the full contents of a div, not just the visible area.</p>
<p>I have searched briefly online, but couldn't find much documentation on anything. I found a lot on HTML5 Canvas. Here is some code I put together:</p>
<pre><code><script>
function saveimg()
{
var c = document.getElementById('mycanvas');
var t = c.getContext('2d');
window.location.href = image;
window.open('', document.getElementById('mycanvas').toDataURL());
}
</script>
<div id="mycanvas">
This is just a test<br />
12344<br />
</div>
<button onclick="saveimg()">Save</button>
</code></pre>
<p>Although, I am getting this error:</p>
<pre><code>TypeError: c.getContext is not a function
</code></pre>
<p>This application will be built only with HTML, CSS and jQuery (or other Javascript libraries).</p> | 18,581,496 | 2 | 3 | null | 2013-09-02 22:06:26.97 UTC | 17 | 2020-08-19 08:54:22.263 UTC | 2013-09-02 22:18:46.907 UTC | null | 1,799,136 | null | 1,799,136 | null | 1 | 71 | javascript|jquery|html|screenshot | 217,658 | <p>There are several of this same question (<a href="https://stackoverflow.com/questions/6887183/how-to-take-screen-shot-of-a-div-with-javascript">1</a>, <a href="https://stackoverflow.com/questions/7339490/saving-div-contents-or-canvas-as-image">2</a>). One way of doing it is using canvas. <a href="http://html2canvas.hertzen.com/" rel="noreferrer">Here's a working solution</a>. <a href="https://html2canvas.hertzen.com/documentation" rel="noreferrer">Here</a> you can see some working examples of using this library.</p> |
15,888,716 | How do I play an audio file with jQuery? | <p>I'm having a difficult time getting audio to work with jQuery. I've tried this with both .wav and .ogg formats. (Firefox 19.0.2)</p>
<p>Clicking the <kbd>Start</kbd> button yields:</p>
<blockquote>
<p>TypeError: buzzer.play is not a function</p>
</blockquote>
<p>I'm not sure if jQuery selectors return an array, but I've tried the capture the audio file with both:</p>
<pre><code>var buzzer = $('buzzer');
</code></pre>
<p>and</p>
<pre><code>var buzzer = $('buzzer')[0];
</code></pre>
<p>Regardless, I can't get the audio elements to play.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<audio id="buzzer" src="buzzer.ogg" type="audio/ogg">Your browser does not support the &#60;audio&#62; element.</audio>
<form id='sample' action="#" data-ajax="false">
<fieldset>
<input value="Start" type="submit">
</fieldset>
</form>
<script type="text/javascript">
var buzzer = $('buzzer')[0];
$(document).on('submit', '#sample', function() {
buzzer.play();
return false;
});
</script>
</body>
</html>
</code></pre> | 15,888,798 | 3 | 2 | null | 2013-04-08 20:50:02.777 UTC | 1 | 2016-07-21 08:56:41.237 UTC | 2014-05-19 01:16:08.34 UTC | null | 1,950,231 | null | 86,731 | null | 1 | 7 | jquery|html5-audio | 45,176 | <p>You forgot the hash <code>#</code> in your ID selector :</p>
<pre><code>var buzzer = $('#buzzer')[0];
$(document).on('submit', '#sample', function() {
buzzer.play();
return false;
});
</code></pre>
<p>And <code>document.getElementById('buzzer')</code> does seem more appropriate!</p>
<p>I'd change the HTML to:</p>
<pre><code><audio id="buzzer" src="buzzer.ogg" type="audio/ogg"></audio>
<input type="button" value="Start" id="start" />
</code></pre>
<p>and do:</p>
<pre><code>$('#start').on('click', function() {
$('#buzzer').get(0).play();
});
</code></pre> |
40,815,238 | Convert dataframe index to datetime | <p>How do I convert a pandas index of strings to datetime format?</p>
<p>My dataframe <code>df</code> is like this:</p>
<pre class="lang-none prettyprint-override"><code> value
2015-09-25 00:46 71.925000
2015-09-25 00:47 71.625000
2015-09-25 00:48 71.333333
2015-09-25 00:49 64.571429
2015-09-25 00:50 72.285714
</code></pre>
<p>but the index is of type string, but I need it a datetime format because I get the error:</p>
<pre class="lang-none prettyprint-override"><code>'Index' object has no attribute 'hour'
</code></pre>
<p>when using</p>
<pre class="lang-py prettyprint-override"><code>df["A"] = df.index.hour
</code></pre> | 40,815,950 | 4 | 4 | null | 2016-11-26 05:22:28.6 UTC | 27 | 2022-09-22 20:56:55.827 UTC | 2022-09-22 20:56:55.827 UTC | null | 7,758,804 | null | 6,056,160 | null | 1 | 111 | python|pandas|datetime | 266,983 | <p>It should work as expected. Try to run the following example.</p>
<pre><code>import pandas as pd
import io
data = """value
"2015-09-25 00:46" 71.925000
"2015-09-25 00:47" 71.625000
"2015-09-25 00:48" 71.333333
"2015-09-25 00:49" 64.571429
"2015-09-25 00:50" 72.285714"""
df = pd.read_table(io.StringIO(data), delim_whitespace=True)
# Converting the index as date
df.index = pd.to_datetime(df.index)
# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df
# value A B
# 2015-09-25 00:46:00 71.925000 0 46
# 2015-09-25 00:47:00 71.625000 0 47
# 2015-09-25 00:48:00 71.333333 0 48
# 2015-09-25 00:49:00 64.571429 0 49
# 2015-09-25 00:50:00 72.285714 0 50
</code></pre> |
40,946,046 | Wait for a redux action to finish dispatching | <p>I have the following action creator:</p>
<pre><code>export function scrolltoNextItem(item) {
return (dispatch, getState) => {
dispatch(appendItem(Item));
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
}
}
</code></pre>
<p>Problem is that <code>scrollToNextItem</code> runs before appendItem has finished and the scroll position ends up being incorrect. I can prove this is the case by adding a <code>setTimeout</code> to make the execution of the script wait for the next tick before running <code>scrollToNextItem</code>:</p>
<pre><code>export function scrolltoNextItem(item) {
return (dispatch, getState) => {
dispatch(appendItem(Item));
setTimeout(() => {
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
}, 0);
}
}
</code></pre>
<p>How can I wait for the <code>appendItem</code> action to finish? In standard react land I would just use the <code>setState</code> callback:</p>
<pre><code>this.setState({something: 'some thing'}, () => {
console.log('something is set');
});
</code></pre>
<p>But <code>dispatch</code> doesn't provide any callback functionality.</p> | 40,946,401 | 1 | 5 | null | 2016-12-03 09:03:27.07 UTC | 7 | 2016-12-03 10:28:53.407 UTC | null | null | null | null | 392,572 | null | 1 | 41 | reactjs|redux | 72,857 | <p>You can always wrap appendItem into a promise and pass <code>dispatch</code> as an argument to it</p>
<pre><code>const appendItem = (item, dispatch) => new Promise((resolve, reject) => {
// do anything here
dispatch(<your-action>);
resolve();
}
</code></pre>
<p>Then you can call it like this from <code>scrolltoNextItem</code></p>
<pre><code>export function scrolltoNextItem(item) {
return (dispatch, getState) => {
appendItem(Item, dispatch).then(() => {
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
})
}
}
</code></pre> |
5,385,312 | IPPROTO_IP vs IPPROTO_TCP/IPPROTO_UDP | <p>I'm having some trouble finding documentation on what the distinction between these settings for the third argument to <code>socket</code> is. I know about TCP and UDP and their differences and also that IP is one layer up (down?) on the stack... My UDP code seems to work the same whether I set it to <code>IPPROTO_IP</code> or <code>IPPROTO_UDP</code>. </p> | 34,901,144 | 2 | 1 | null | 2011-03-22 00:21:29.26 UTC | 12 | 2021-04-19 06:06:55.477 UTC | null | null | null | null | 340,947 | null | 1 | 28 | sockets|ip | 56,109 | <p>Documentation for <code>socket()</code> on Linux is split between various manpages including <code>ip(7)</code> that specifies that you have to use <code>0</code> or <code>IPPROTO_UDP</code> for UDP and <code>0</code> or <code>IPPROTO_TCP</code> for TCP. When you use <code>0</code>, which happens to be the value of <code>IPPROTO_IP</code>, UDP is used for <code>SOCK_DGRAM</code> and TCP is used for <code>SOCK_STREAM</code>.</p>
<p>In my opinion the clean way to create a UDP or a TCP IPv4 socket object is as follows:</p>
<pre><code>int sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int sock_tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
</code></pre>
<p>The reason is that it is generally better to be explicit than implicit. In this specific case using <code>0</code> or worse <code>IPPROTO_IP</code> for the third argument doesn't gain you anything.</p>
<p>Also imagine using a protocol that can do both streams and datagrams like <em>sctp</em>. By always specifying both <em>socktype</em> and <em>protocol</em> you are safe from any ambiguity.</p> |
5,403,121 | whats the difference between function foo(){} and foo = function(){}? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">JavaScript: var functionName = function() {} vs function functionName() {}</a> </p>
</blockquote>
<p>are they the same? I've always wondered</p> | 5,403,166 | 2 | 0 | null | 2011-03-23 09:29:07.383 UTC | 8 | 2017-07-05 12:39:02.927 UTC | 2017-05-23 12:18:16.903 UTC | null | -1 | null | 200,066 | null | 1 | 29 | javascript|functional-programming | 22,997 | <p>No, they're not the same, although they do both result in a function you can call via the symbol <code>foo</code>. One is a function <em>declaration</em>, the other is a function <em>expression</em>. They are evaluated at different times, have different effects on the scope in which they're defined, and are legal in different places.</p>
<p>Quoting <a href="https://stackoverflow.com/questions/5142286/two-functions-with-the-same-name-in-javascript-how-can-this-work/5142335#5142335">my answer to this other question</a> here (edited a bit for relevance), in case the other question were ever removed for some reason (and to save people following the link):</p>
<hr>
<p>JavaScript has two different but related things: Function <em>declarations</em>, and function <em>expressions</em>. There are marked differences between them:</p>
<p>This is a function <em>declaration</em>:</p>
<pre><code>function foo() {
// ...
}
</code></pre>
<p>Function declarations are evaluated upon entry into the enclosing scope, before any step-by-step code is executed. The function's name (<code>foo</code>) is added to the enclosing scope (technically, the <em>variable object</em> for the <em>execution context</em> the function is defined in).</p>
<p>This is a function <em>expression</em> (specifically, an anonymous one, like your quoted code):</p>
<pre><code>var foo = function() {
// ...
};
</code></pre>
<p>Function expressions are evaluated as part of the step-by-step code, at the point where they appear (just like any other expression). That one creates a function with no name, which it assigns to the <code>foo</code> variable.</p>
<p>Function expressions can also be <em>named</em> rather than anonymous. A named one looks like this:</p>
<pre><code>var x = function foo() { // Valid, but don't do it; see details below
// ...
};
</code></pre>
<p>A named function expression <em>should</em> be valid, according to the spec. It should create a function with the name <code>foo</code>, but <em>not</em> put <code>foo</code> in the enclosing scope, and then assign that function to the <code>x</code> variable (all of this happening when the expression is encountered in the step-by-step code). When I say it shouldn't put <code>foo</code> in the enclosing scope, I mean exactly that:</p>
<pre><code>var x = function foo() {
alert(typeof foo); // alerts "function" (in compliant implementations)
};
alert(typeof foo); // alerts "undefined" (in compliant implementations)
</code></pre>
<p>Note how that's different from the way function <em>declarations</em> work (where the function's name <strong>is</strong> added to the enclosing scope).</p>
<p>Named function expressions work on compliant implementations, but there used to be several bugs in implementations in the wild, most especially Internet Explorer 8 and earlier (and some early versions of Safari). IE8 processes a named function expresssion <em>twice</em>: First as a function <em>declaration</em> (upon entry into the execution context), and then later as a function <em>expression</em>, generating two distinct functions in the process. (Really.)</p>
<p>More here: <a href="https://stackoverflow.com/questions/5142286/two-functions-with-the-same-name-in-javascript-how-can-this-work/5142335#5142335"><em>Double take</em></a> and here: <a href="http://kangax.github.com/nfe/" rel="noreferrer"><em>Named function expressions demystified</em></a></p>
<hr>
<p><strong>NOTE:</strong> The below was written in 2011. In 2015, function declarations in control blocks were added to the language as part of ECMAScript 2015. Their semantics vary depending on whether you're in strict or loose mode, and in loose mode if the environment is a web browser. And of course, on whether the environment you're using has correct support for the ES2015 definition for them. (To my surprise, as of this writing in July 2017, <a href="https://babeljs.io" rel="noreferrer">Babel</a> doesn't correctly transpile them, either.) Consequently, you can only reliably use function declarations within control-flow structures in specific situations, so it's still probably best, for now, to use function expressions instead.</p>
<p><s>
And finally, another difference between them is where they're legal. A function expression can appear anywhere an expression can appear (which is virtually anywhere). A function <em>declaration</em> can only appear at the top level of its enclosing scope, outside of any control-flow statements. So for instance, this is valid:</p>
<pre><code>function bar(x) {
var foo;
if (x) {
foo = function() { // Function expression...
// Do X
};
}
else {
foo = function() { // ...and therefore legal
// Do Y
};
}
foo();
}
</code></pre>
<p>...but this is not, and <strong>does not</strong> do what it looks like it does on most implementations:</p>
<pre><code>function bar(x) {
if (x) {
function foo() { // Function declaration -- INVALID
// Do X
}
}
else {
function foo() { // INVALID
// Do Y
}
}
foo();
}
</code></pre>
<p>And it makes perfect sense: Since the <code>foo</code> function declarations are evaluated upon entry into the <code>bar</code> function, before any step-by-step code is executed, the interpreter has no idea which <code>foo</code> to evaluate. This isn't a problem for expressions since they're done during the control-flow.</p>
<p>Since the syntax is invalid, implementations are free to do what they want. I've never met one that did what I would have expected, which is to throw a syntax error and fail. Instead, nearly all of them just ignore the control flow statements and do what they should do if there are two <code>foo</code> function declarations at the top level (which is use the second one; that's in the spec). So only the second <code>foo</code> is used. Firefox's SpiderMonkey is the standout, it seems to (effectively) convert them into expressions, and so which it uses depends on the value of <code>x</code>. <a href="http://jsbin.com/oyiti5" rel="noreferrer">Live example</a>. </s></p> |
163,647 | Lightweight .NET debugger? | <p>I frequently need to debug .NET binaries on test machines (by test-machine, I mean that the machine doesn't have Visual Studio installed on it, it's frequently re-imaged, It's not the same machine that I do my development on, etc). </p>
<p>I love the Visual Studio debugger, but it's not practical for me to install visual studios on a freshly imaged test-machine just to debug an assertion or crash (the install takes way too long, the footprint is too large, etc). </p>
<p>I'd really like a quickly installed program that could break into a running process, let me specify the location of symbols/source code, and let me jump right into debugging. For native binaries, windbg works great, but I haven't found anything similiar for managed binaries. Any recommendations?</p>
<p>(as a side note, I am aware of visual studios remote debugging capabilities, but for some reason it never seems to work consistently for me... I often have connection issues)</p> | 4,950,346 | 8 | 0 | null | 2008-10-02 17:47:45.9 UTC | 12 | 2018-09-08 14:08:40.477 UTC | null | null | null | brad | 24,573 | null | 1 | 29 | .net|debugging | 21,473 | <p>I've finally found extensions for Windbg that do just what I wanted: <a href="http://www.stevestechspot.com/">Sosex.dll</a>, lets me use windbg to debug managed applications with very minimal installation required. I've used it for more than a year now, and It's worked, without fault, for every debugging scenario I've encountered. </p> |
933,460 | Unique hardware ID in Mac OS X | <p>Mac OS X development is a fairly new animal for me, and I'm in the process of porting over some software. For software licensing and registration I need to be able to generate some kind of hardware ID. It doesn't have to be anything fancy; Ethernet MAC address, hard drive serial, CPU serial, something like that.</p>
<p>I've got it covered on Windows, but I haven't a clue on Mac. Any idea of what I need to do, or where I can go for information on this would be great! </p>
<p>Edit:</p>
<p>For anybody else that is interested in this, this is the code I ended up using with Qt's QProcess class:</p>
<pre><code>QProcess proc;
QStringList args;
args << "-c" << "ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { print $3; }'";
proc.start( "/bin/bash", args );
proc.waitForFinished();
QString uID = proc.readAll();
</code></pre>
<p>Note: I'm using C++.</p> | 944,103 | 9 | 0 | null | 2009-06-01 03:32:36.103 UTC | 24 | 2022-09-24 16:33:50.177 UTC | 2010-08-02 22:57:12.857 UTC | null | 63,550 | null | 19,404 | null | 1 | 32 | c++|macos|unique|hardware-id | 30,011 | <p>Try this Terminal command:</p>
<pre><code>ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { split($0, line, "\""); printf("%s\n", line[4]); }'
</code></pre>
<p>From <a href="http://www.jaharmi.com/2008/03/15/get_uuid_for_mac_with_ioreg" rel="noreferrer">here</a></p>
<p>Here is that command wrapped in Cocoa (which could probably be made a bit cleaner):</p>
<pre><code>NSArray * args = [NSArray arrayWithObjects:@"-rd1", @"-c", @"IOPlatformExpertDevice", @"|", @"grep", @"model", nil];
NSTask * task = [NSTask new];
[task setLaunchPath:@"/usr/sbin/ioreg"];
[task setArguments:args];
NSPipe * pipe = [NSPipe new];
[task setStandardOutput:pipe];
[task launch];
NSArray * args2 = [NSArray arrayWithObjects:@"/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }", nil];
NSTask * task2 = [NSTask new];
[task2 setLaunchPath:@"/usr/bin/awk"];
[task2 setArguments:args2];
NSPipe * pipe2 = [NSPipe new];
[task2 setStandardInput:pipe];
[task2 setStandardOutput:pipe2];
NSFileHandle * fileHandle2 = [pipe2 fileHandleForReading];
[task2 launch];
NSData * data = [fileHandle2 readDataToEndOfFile];
NSString * uuid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
</code></pre> |
116,574 | java get file size efficiently | <p>While googling, I see that using <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29" rel="noreferrer"><code>java.io.File#length()</code></a> can be slow.
<a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html" rel="noreferrer"><code>FileChannel</code></a> has a <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#size%28%29" rel="noreferrer"><code>size()</code></a> method that is available as well.</p>
<p>Is there an efficient way in java to get the file size?</p> | 116,916 | 9 | 8 | null | 2008-09-22 18:21:40.423 UTC | 34 | 2016-06-10 07:54:16.503 UTC | 2013-04-20 17:52:14.95 UTC | jjnguy | 629,493 | joshjdevl | 20,641 | null | 1 | 170 | java|filesize | 221,006 | <p>Well, I tried to measure it up with the code below:</p>
<p>For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:</p>
<pre><code>LENGTH sum: 10626, per Iteration: 10626.0
CHANNEL sum: 5535, per Iteration: 5535.0
URL sum: 660, per Iteration: 660.0
</code></pre>
<p>For runs = 5 and iterations = 50 the picture draws different.</p>
<pre><code>LENGTH sum: 39496, per Iteration: 157.984
CHANNEL sum: 74261, per Iteration: 297.044
URL sum: 95534, per Iteration: 382.136
</code></pre>
<p>File must be caching the calls to the filesystem, while channels and URL have some overhead.</p>
<p>Code:</p>
<pre><code>import java.io.*;
import java.net.*;
import java.util.*;
public enum FileSizeBench {
LENGTH {
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
return me.length();
}
},
CHANNEL {
@Override
public long getResult() throws Exception {
FileInputStream fis = null;
try {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
fis = new FileInputStream(me);
return fis.getChannel().size();
} finally {
fis.close();
}
}
},
URL {
@Override
public long getResult() throws Exception {
InputStream stream = null;
try {
URL url = FileSizeBench.class
.getResource("FileSizeBench.class");
stream = url.openStream();
return stream.available();
} finally {
stream.close();
}
}
};
public abstract long getResult() throws Exception;
public static void main(String[] args) throws Exception {
int runs = 5;
int iterations = 50;
EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);
for (int i = 0; i < runs; i++) {
for (FileSizeBench test : values()) {
if (!durations.containsKey(test)) {
durations.put(test, 0l);
}
long duration = testNow(test, iterations);
durations.put(test, durations.get(test) + duration);
// System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
}
}
for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
System.out.println();
System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
}
}
private static long testNow(FileSizeBench test, int iterations)
throws Exception {
long result = -1;
long before = System.nanoTime();
for (int i = 0; i < iterations; i++) {
if (result == -1) {
result = test.getResult();
//System.out.println(result);
} else if ((result = test.getResult()) != result) {
throw new Exception("variance detected!");
}
}
return (System.nanoTime() - before) / 1000;
}
}
</code></pre> |
525,512 | Drop all tables command | <p>What is the command to drop all tables in SQLite? </p>
<p>Similarly I'd like to drop all indexes.</p> | 527,072 | 11 | 0 | null | 2009-02-08 10:34:02.4 UTC | 21 | 2021-01-05 11:06:36.73 UTC | 2009-02-14 14:33:23.497 UTC | Noah | 12,113 | alamodey | 58,521 | null | 1 | 99 | sql|sqlite|rdbms|database | 139,905 | <pre><code>rm db/development.sqlite3
</code></pre> |
347,614 | Storing WPF Image Resources | <p>For a WPF application which will need 10 - 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go?</p>
<p>If so, how do I specify in XAML that an Image control should load the image from an embedded resource?</p> | 606,986 | 11 | 0 | null | 2008-12-07 14:14:53.397 UTC | 128 | 2022-06-02 18:37:02.883 UTC | 2020-11-03 13:48:53 UTC | null | 70,345 | driis | 13,627 | null | 1 | 448 | c#|.net|wpf|embedded-resource | 495,678 | <p>If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all <code>Image</code> elements.</p>
<p>To do this, create a <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx" rel="noreferrer"><code>BitmapSource</code></a> as a resource somewhere:</p>
<pre class="lang-xml prettyprint-override"><code><BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />
</code></pre>
<p>Then, in your code, use something like:</p>
<pre class="lang-xml prettyprint-override"><code><Image Source="{StaticResource MyImageSource}" />
</code></pre>
<p>In my case, I found that I had to set the <code>Image.png</code> file to have a build action of <code>Resource</code> rather than just <code>Content</code>. This causes the image to be carried within your compiled assembly.</p> |
640,190 | Image width/height as an attribute or in CSS? | <p>What's the "correct" semantic way to specify image height and width? In CSS...</p>
<pre><code>width:15px;
</code></pre>
<p>or inline...</p>
<pre><code><img width="15"
</code></pre>
<p>?</p>
<p>CSS seems like the right place to put visual information. On the other hand, few would argue that image "src" should not be specified as an attribute and the height/width seem as tied to the binary image data as the "src" is.</p>
<p>(Yes, I realize from a technical, end-user perspective this really doesn't matter.)</p> | 640,232 | 12 | 0 | null | 2009-03-12 19:47:19.353 UTC | 26 | 2017-06-04 01:23:14.33 UTC | null | null | null | Wayne Kao | 3,284 | null | 1 | 106 | html|css | 94,461 | <p>It should be defined inline. If you are using the img tag, that image should have semantic value to the content, which is why the alt attribute is required for validation. </p>
<p>If the image is to be part of the layout or template, you should use a tag other than the img tag and assign the image as a CSS background to the element. In this case, the image has no semantic meaning and therefore doesn't require the alt attribute. I'm fairly certain that most screen readers would not even know that a CSS image exists.</p> |
520,527 | Why do some claim that Java's implementation of generics is bad? | <p>I've occasionally heard that with generics, Java didn't get it right. (nearest reference, <a href="https://stackoverflow.com/questions/457822/what-are-the-things-java-got-right">here</a>)</p>
<p>Pardon my inexperience, but what would have made them better?</p> | 520,568 | 13 | 0 | null | 2009-02-06 14:45:52.473 UTC | 48 | 2022-02-18 00:59:38.627 UTC | 2017-05-23 12:25:53.82 UTC | null | -1 | sdellysse | 41,200 | null | 1 | 128 | java|generics | 23,697 | <p>Bad:</p>
<ul>
<li>Type information is lost at compile time, so at execution time you can't tell what type it's "meant" to be</li>
<li>Can't be used for value types (this is a biggie - in .NET a <code>List<byte></code> really is backed by a <code>byte[]</code> for example, and no boxing is required)</li>
<li>Syntax for calling generic methods sucks (IMO)</li>
<li>Syntax for constraints can get confusing</li>
<li>Wildcarding is generally confusing</li>
<li>Various restrictions due to the above - casting etc</li>
</ul>
<p>Good:</p>
<ul>
<li>Wildcarding allows covariance/contravariance to be specified at calling side, which is very neat in many situations</li>
<li>It's better than nothing!</li>
</ul> |
978,252 | Logging in Scala | <p>What is a good way to do logging in a Scala application? Something that is consistent with the language philosophy, does not clutter the code, and is low-maintenance and unobtrusive. Here's a basic requirement list:</p>
<ul>
<li>simple</li>
<li>does not clutter the code. Scala is great for its brevity. I don't want half of my code to be logging statements</li>
<li>log format can be changed to fit the rest of my enterprise logs and monitoring software</li>
<li>supports levels of logging (ie debug, trace, error)</li>
<li>can log to disk as well as other destinations (i.e. socket, console, etc.)</li>
<li>minimum configuration, if any</li>
<li>works in containers (ie, web server)</li>
<li>(optional, but nice to have) comes either as part of the language or as a maven artifact, so I don't have to hack my builds to use it</li>
</ul>
<p>I know I can use the existing Java logging solutions, but they fail on at least two of the above, namely clutter and configuration.</p>
<p>Thanks for your replies.</p> | 978,262 | 14 | 0 | null | 2009-06-10 21:28:17.35 UTC | 69 | 2020-09-18 18:55:26.587 UTC | null | null | null | null | 64,679 | null | 1 | 179 | logging|scala | 124,619 | <h1>slf4j wrappers</h1>
<p>Most of Scala's logging libraries have been some wrappers around a Java logging framework (slf4j, log4j etc), but as of March 2015, the surviving log libraries are all slf4j. These log libraries provide some sort of <code>log</code> object to which you can call <code>info(...)</code>, <code>debug(...)</code>, etc. I'm not a big fan of slf4j, but it now seems to be the predominant logging framework. Here's the description of <a href="http://www.slf4j.org/" rel="noreferrer">SLF4J</a>:</p>
<blockquote>
<p>The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.</p>
</blockquote>
<p>The ability to change underlying log library at deployment time brings in unique characteristic to the entire slf4j family of loggers, which you need to be aware of:</p>
<ol>
<li><em>classpath as configuration</em> approach. The way slf4j knows which underlying logging library you are using is by loading a class by some name. I've had issues in which slf4j not recognizing my logger when classloader was customized.</li>
<li>Because the <em>simple facade</em> tries to be the common denominator, it's limited only to actual log calls. In other words, the configuration cannot be done via the code.</li>
</ol>
<p>In a large project, it could actually be convenient to be able to control the logging behavior of transitive dependencies if everyone used slf4j.</p>
<h3>Scala Logging</h3>
<p><a href="https://github.com/typesafehub/scala-logging" rel="noreferrer">Scala Logging</a> is written by Heiko Seeberger as a successor to his <a href="https://github.com/w11k/slf4s" rel="noreferrer">slf4s</a>. It uses macro to expand calls into if expression to avoid potentially expensive log call.</p>
<blockquote>
<p>Scala Logging is a convenient and performant logging library wrapping logging libraries like SLF4J and potentially others.</p>
</blockquote>
<h1>Historical loggers</h1>
<ul>
<li><a href="https://github.com/codahale/logula" rel="noreferrer">Logula</a>, a Log4J wrapper written by Coda Hale. Used to like this one, but now it's abandoned.</li>
<li><a href="https://github.com/robey/configgy" rel="noreferrer">configgy</a>, a java.util.logging wrapper that used to be popular in the earlier days of Scala. Now abandoned.</li>
</ul> |
764,439 | Why binary and not ternary computing? | <p>Isn't a three state object immedately capable of holding more information and handling larger values? I know that processors currently use massive nets of XOR gates and that would need to be reworked. </p>
<p>Since we are at 64 bit (we can represent 2^63 possible states) computing the equivalent <a href="http://en.wikipedia.org/wiki/Ternary_computer" rel="noreferrer">ternary</a> generation could support number with 30 more tens places log(3^63-2^63).</p>
<p>I imagine it is as easy to detect the potential difference between +1 and 0 as it is between -1 and 0.</p>
<p>Would some compexity of the hardware, power consumption, or chip density offset any gains in storage and computing power?</p> | 764,892 | 15 | 1 | null | 2009-04-18 23:15:47.447 UTC | 22 | 2016-05-13 07:36:09.277 UTC | 2012-03-17 05:25:36.143 UTC | null | 240,633 | null | 66,519 | null | 1 | 86 | computer-science|ternary-representation | 65,979 | <ul>
<li><p>It is much harder to build components that use more than two states/levels/whatever. For example, the transistors used in logic are either closed and don't conduct at all, or wide open. Having them half open would require much more precision and use extra power. Nevertheless, sometimes more states are used for packing more data, but rarely (e.g. modern NAND flash memory, modulation in modems).</p></li>
<li><p>If you use more than two states you need to be compatible to binary, because the rest of the world uses it. Three is out because the conversion to binary would require expensive multiplication or division with remainder. Instead you go directly to four or a higher power of two.</p></li>
</ul>
<p>These are practical reasons why it is not done, but mathematically it is perfectly possible to build a computer on ternary logic.</p> |
136,419 | Get integer value of the current year in Java | <p>I need to determine the current year in Java as an integer. I could just use <code>java.util.Date()</code>, but it is deprecated.</p> | 136,434 | 16 | 1 | null | 2008-09-25 21:53:52.837 UTC | 51 | 2022-09-07 15:08:43.87 UTC | 2017-12-19 14:58:13.603 UTC | KG | 1,788,806 | KG | 318 | null | 1 | 354 | java|datetime|date | 574,577 | <pre><code>int year = Calendar.getInstance().get(Calendar.YEAR);
</code></pre>
<p>Not sure if this meets with the criteria of not setting up a new Calendar? (Why the opposition to doing so?)</p> |
401,331 | examining history of deleted file | <p>If I delete a file in Subversion, how can I look at it's history and contents? If I try to do <code>svn cat</code> or <code>svn log</code> on a nonexistent file, it complains that the file doesn't exist.</p>
<p>Also, if I wanted to resurrect the file, should I just <code>svn add</code> it back?</p>
<p>(I asked specifically about Subversion, but I'd also like to hear about how Bazaar, Mercurial, and Git handle this case, too.)</p> | 401,353 | 17 | 0 | null | 2008-12-30 20:05:29.63 UTC | 42 | 2017-03-17 02:22:20.053 UTC | 2013-06-06 18:05:43.003 UTC | Benjamin Peterson | 138,719 | Benjamin Peterson | 33,795 | null | 1 | 168 | svn|version-control|bazaar | 91,134 | <p>To get the log of a deleted file, use</p>
<pre><code>svn log -r lastrevisionthefileexisted
</code></pre>
<p>If you want to resurrect the file and keep its version history, use</p>
<pre><code>svn copy url/of/file@lastrevisionthefileexisted -r lastrevisionthefileexisted path/to/workingcopy/file
</code></pre>
<p>If you just want the file content but unversioned (e.g., for a quick inspection), use</p>
<pre><code>svn cat url/of/file@lastrevisionthefileexisted -r latrevisionthefileexisted > file
</code></pre>
<p>In any case, DO NOT use 'svn up' to get a deleted file back!</p> |
958,949 | Difference Between Select and SelectMany | <p>I've been searching the difference between <code>Select</code> and <code>SelectMany</code> but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are standard array examples. </p>
<p>Can someone provide a LINQ To SQL example?</p> | 959,057 | 18 | 3 | null | 2009-06-06 03:54:16.847 UTC | 300 | 2021-08-27 11:06:36.89 UTC | 2014-11-24 23:47:05.377 UTC | user4039065 | null | null | 44,852 | null | 1 | 1,285 | c#|linq-to-sql|linq | 672,989 | <p><code>SelectMany</code> flattens queries that return lists of lists. For example</p>
<pre><code>public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
public string Name { get; set; }
}
IEnumerable<Person> people = new List<Person>();
// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
// And to include data from the parent in the result:
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
.SelectMany(p => p.PhoneNumbers,
(parent, child) => new { parent.Name, child.Number });
</code></pre>
<p><a href="https://dotnetfiddle.net/LNyymI" rel="noreferrer">Live Demo on .NET Fiddle</a></p> |
13,049 | What's the difference between struct and class in .NET? | <p>What's the difference between struct and class in .NET?</p> | 13,275 | 19 | 1 | null | 2008-08-16 08:21:47.947 UTC | 300 | 2021-11-01 11:10:29.89 UTC | 2017-12-16 22:41:15.127 UTC | Don Kirkby | 1,709,587 | Keith | 905 | null | 1 | 860 | .net|class|struct|value-type|reference-type | 476,289 | <p>In .NET, there are two categories of types, <em>reference types</em> and <em>value types</em>.</p>
<p>Structs are <em>value types</em> and classes are <em>reference types</em>.</p>
<p>The general difference is that a <em>reference type</em> lives on the heap, and a <em>value type</em> lives inline, that is, wherever it is your variable or field is defined.</p>
<p>A variable containing a <em>value type</em> contains the entire <em>value type</em> value. For a struct, that means that the variable contains the entire struct, with all its fields.</p>
<p>A variable containing a <em>reference type</em> contains a pointer, or a <em>reference</em> to somewhere else in memory where the actual value resides.</p>
<p>This has one benefit, to begin with:</p>
<ul>
<li><em>value types</em> always contains a value</li>
<li><em>reference types</em> can contain a <em>null</em>-reference, meaning that they don't refer to anything at all at the moment</li>
</ul>
<p>Internally, <em>reference type</em>s are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:</p>
<ul>
<li>copying the contents of a <em>value type</em> variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other</li>
<li>copying the contents of a <em>reference type</em> variable into another variable, copies the reference, which means you now have two references to the same <em>somewhere else</em> storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places</li>
</ul>
<p>When you declare variables or fields, here's how the two types differ:</p>
<ul>
<li>variable: <em>value type</em> lives on the stack, <em>reference type</em> lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note <a href="https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/" rel="noreferrer">Eric Lipperts article series: The Stack Is An Implementation Detail</a>.)</li>
<li>class/struct-field: <em>value type</em> lives completely inside the type, <em>reference type</em> lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.</li>
</ul> |
87,350 | What are good grep tools for Windows? | <p>Any recommendations on <a href="http://en.wikipedia.org/wiki/Grep" rel="noreferrer">grep</a> tools for Windows? Ideally ones that could leverage 64-bit OS.</p>
<p>I'm aware of <a href="http://www.cygwin.com/" rel="noreferrer">Cygwin</a>, of course, and have also found <a href="http://www.powergrep.com/" rel="noreferrer">PowerGREP</a>, but I'm wondering if there are any hidden gems out there?</p> | 87,382 | 28 | 0 | 2015-01-08 22:10:06.17 UTC | 2008-09-17 20:34:48.173 UTC | 173 | 2022-03-04 19:49:18.953 UTC | 2013-07-26 17:47:45.923 UTC | Portman | 15,168 | Portman | 1,690 | null | 1 | 288 | windows|grep | 557,871 | <h2>Based on recommendations in the comments, I've started using <a href="https://tools.stefankueng.com/grepWin.html" rel="nofollow noreferrer">grepWin</a> and it's fantastic and <em>free</em>.</h2>
<hr />
<p>(I'm still a fan of <a href="http://www.powergrep.com/" rel="nofollow noreferrer">PowerGREP</a>, but I don't use it anymore.)</p>
<p>I know you already mentioned it, but PowerGREP is <strong>awesome</strong>.</p>
<p>Some of my favorite features are:</p>
<ul>
<li>Right-click on a folder to run PowerGREP on it</li>
<li>Use regular expressions or literal text</li>
<li>Specify wildcards for files to include & exclude</li>
<li>Search & replace</li>
<li>Preview mode is nice because you can make sure you're replacing what you intend to.</li>
</ul>
<p>Now I realize that the other grep tools can do all of the above. It's just that PowerGREP packages all of the functionality into a very easy-to-use GUI.</p>
<p><em><strong>From the same wonderful folks who brought you <a href="http://en.wikipedia.org/wiki/RegexBuddy" rel="nofollow noreferrer">RegexBuddy</a> and who I have no affiliation with beyond loving their stuff.</strong></em> (It should be noted that RegexBuddy includes a basic version of grep (for Windows) itself and it costs a lot less than PowerGREP.)</p>
<hr />
<h2>Additional solutions</h2>
<h3>Existing Windows commands</h3>
<ul>
<li><a href="http://ss64.com/nt/findstr.html" rel="nofollow noreferrer">FINDSTR</a></li>
<li><a href="https://technet.microsoft.com/en-us/library/hh849903.aspx" rel="nofollow noreferrer">Select-String</a> in PowerShell</li>
</ul>
<h3>Linux command implementations on Windows</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a></li>
<li><a href="https://github.com/dthree/cash" rel="nofollow noreferrer">Cash</a></li>
</ul>
<h3>Grep tools with a graphical interface</h3>
<ul>
<li><a href="http://astrogrep.sourceforge.net/screenshots/" rel="nofollow noreferrer">AstroGrep</a></li>
<li><a href="https://www.baremetalsoft.com/baregrep/" rel="nofollow noreferrer">BareGrep</a></li>
<li><a href="http://stefanstools.sourceforge.net/grepWin.html" rel="nofollow noreferrer">GrepWin</a></li>
</ul>
<h3>Additional Grep tools</h3>
<ul>
<li><a href="http://code.google.com/p/dngrep/" rel="nofollow noreferrer">dnGrep</a></li>
</ul> |
1,053,052 | A generic error occurred in GDI+, JPEG Image to MemoryStream | <p>This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn't fit. An exception gets thrown when I save the image to the stream.</p>
<p>Weirdly this works perfectly with a png but gives the above error with jpg and gif which is rather confusing.</p>
<p>Most similar problem out there relate to saving images to files without permissions. Ironically the solution is to use a memory stream as I am doing....</p>
<pre><code>public static byte[] ConvertImageToByteArray(Image imageToConvert)
{
using (var ms = new MemoryStream())
{
ImageFormat format;
switch (imageToConvert.MimeType())
{
case "image/png":
format = ImageFormat.Png;
break;
case "image/gif":
format = ImageFormat.Gif;
break;
default:
format = ImageFormat.Jpeg;
break;
}
imageToConvert.Save(ms, format);
return ms.ToArray();
}
}
</code></pre>
<p>More detail to the exception. The reason this causes so many issues is the lack of explanation :(</p>
<pre><code>System.Runtime.InteropServices.ExternalException was unhandled by user code
Message="A generic error occurred in GDI+."
Source="System.Drawing"
ErrorCode=-2147467259
StackTrace:
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
at Caldoo.Infrastructure.PhotoEditor.ConvertImageToByteArray(Image imageToConvert) in C:\Users\Ian\SVN\Caldoo\Caldoo.Coordinator\PhotoEditor.cs:line 139
at Caldoo.Web.Controllers.PictureController.Croppable() in C:\Users\Ian\SVN\Caldoo\Caldoo.Web\Controllers\PictureController.cs:line 132
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
</code></pre>
<p>OK things I have tried so far. </p>
<ol>
<li>Cloning the image and working on that.</li>
<li>Retrieving the encoder for that MIME passing that with jpeg quality setting.</li>
</ol> | 1,053,123 | 35 | 3 | null | 2009-06-27 15:40:29.277 UTC | 62 | 2022-04-25 11:54:04.327 UTC | 2017-02-19 11:44:22.183 UTC | null | 1,033,581 | null | 58,656 | null | 1 | 357 | c#|gdi+ | 558,540 | <p>OK I seem to have found the cause just by sheer luck and its nothing wrong with that particular method, it's further back up the call stack.</p>
<p>Earlier I resize the image and as part of that method I return the resized object as follows. I have inserted two calls to the above method and a direct save to a file.</p>
<pre><code>// At this point the new bitmap has no MimeType
// Need to output to memory stream
using (var m = new MemoryStream())
{
dst.Save(m, format);
var img = Image.FromStream(m);
//TEST
img.Save("C:\\test.jpg");
var bytes = PhotoEditor.ConvertImageToByteArray(img);
return img;
}
</code></pre>
<p>It appears that the memory stream that the object was created on <strong>has</strong> to be open at the time the object is saved. I am not sure why this is. Is anyone able to enlighten me and how I can get around this. </p>
<p>I only return from a stream because after using the resize code similar to <a href="https://stackoverflow.com/questions/30569/resize-transparent-images-using-c">this</a> the destination file has an unknown mime type (img.RawFormat.Guid) and Id like the Mime type to be correct on all image objects as it makes it hard write generic handling code otherwise.</p>
<p><strong>EDIT</strong></p>
<p>This didn't come up in my initial search but <a href="https://stackoverflow.com/questions/336387/image-save-throws-a-gdi-exception-because-the-memory-stream-is-closed">here's</a> the answer from Jon Skeet</p> |
34,423,873 | Docker push to AWS ECR private repo failing with malformed JSON | <p>I am trying out AWS ECR and pushing a new tag to our private repossitory.</p>
<p>it goes like this:</p>
<pre><code>export DOCKER_REGISTRY=0123123123123.dkr.ecr.us-east-1.amazonaws.com
export TAG=0.1
docker build -t vendor/app-name .
`aws ecr get-login --region us-east-1`" # generates docker login
docker tag vendor/app-name $DOCKER_REGISTRY/vendor/app-name:$TAG
docker push $DOCKER_REGISTRY/vendor/app-name:$TAG
</code></pre>
<p>Login works, the tag is created and I see it with <code>docker images</code>, but the push fails cryptically.</p>
<pre><code>The push refers to a repository [0123123123123.dkr.ecr.us-east-1.amazonaws.com/vendor/app-name] (len: 2)
b1a1d76b9e52: Pushing [==================================================>] 32 B/32 B
Error parsing HTTP response: unexpected end of JSON input: ""
</code></pre>
<p>It very well might be a misconfiguration, but I can't figure out how to get more output out of it. The command has no debug level options, there are no other logs and I can't intercept network traffic since it seems encrypted.</p> | 34,425,139 | 3 | 5 | null | 2015-12-22 20:22:08.45 UTC | 4 | 2020-04-21 21:02:17.637 UTC | 2015-12-22 20:59:17.753 UTC | null | 942,390 | null | 942,390 | null | 1 | 31 | amazon-web-services|docker|docker-toolbox|amazon-ecs | 8,398 | <p>Ran into the same issue. For me, ensuring that the IAM user I was pushing as had the <code>ecr:BatchCheckLayerAvailability</code> permission cleared this up.</p>
<p>I had originally intended to have a "push-only" policy and didn't realize this permission was required to push successfully.</p> |
34,802,667 | Unit test Java class that loads native library | <p>I'm running unit tests in Android Studio. I have a Java class that loads a native library with the following code</p>
<pre><code> static
{
System.loadLibrary("mylibrary");
}
</code></pre>
<p>But when I test this class inside my <code>src/test</code> directory I get </p>
<pre><code>java.lang.UnsatisfiedLinkError: no mylibrary in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
</code></pre>
<p>How can I make it find the path of native .so libraries which is located at <code>src/main/libs</code> in order to unit test without errors?</p>
<p>Note: inside <code>src/main/libs</code> directory I have 3 more subdirectories: <code>armeabi</code>, <code>mips</code> and <code>x86</code>. Each one of those contains the proper .so file. I'm using the <strong>Non experimental version</strong> for building NDK libs.</p>
<p>I don't wanna use other 3rd party testing libraries as all my other "pure" java classes can be unit tested fine. But if that's not possible then I'm open to alternatives.</p>
<p>Here is my test code which throws the error</p>
<pre><code> @Test
public void testNativeClass() throws Exception
{
MyNativeJavaClass test = new MyNativeJavaClass("lalalal")
List<String> results = test.getResultsFromNativeMethodAndPutThemInArrayList();
assertEquals("There should be only three result", 3, results.size());
}
</code></pre> | 35,190,032 | 9 | 7 | null | 2016-01-15 00:59:47.053 UTC | 8 | 2021-12-27 11:19:14.763 UTC | 2017-08-16 20:47:26.24 UTC | null | 340,175 | null | 2,722,870 | null | 1 | 70 | java|android|unit-testing|junit4 | 22,233 | <p>The only solution I found that works without hacks is to use JUnit through instrumentation testing (androidTest directory).
My class can now be tested fine but with help of the android device or emulator.</p> |
6,630,356 | AVPlayer rate property does not work? | <p>so it would appear that the only values that actually work are 0.0, 0.5, 1.0, and 2.0...</p>
<p>i tried setting it to 0.25 since I want it to play at 1/4th of the natural speed, but it played it at 1/2 of the natural speed instead. can anyone confirm this?</p> | 9,936,346 | 6 | 2 | null | 2011-07-08 20:48:45.977 UTC | 10 | 2020-08-06 21:15:53.503 UTC | null | null | null | null | 514,315 | null | 1 | 19 | avplayer | 12,822 | <p>Confirmed. I actually had a ticket with Apple DTS open for this issue and a bug filed. The only supported values are 0.50, 0.67, 0.80, 1.0, 1.25, 1.50, and 2.0. All other settings are rounded to nearest value.</p> |
6,583,158 | Finding open file descriptors for a process linux ( C code )? | <p>I wanted to find all fds opened for a process in linux.</p>
<p>Can I do it with glib library functions ?</p> | 6,583,249 | 6 | 0 | null | 2011-07-05 13:08:54.107 UTC | 13 | 2016-07-01 10:23:01.823 UTC | null | null | null | null | 303,986 | null | 1 | 30 | c|linux|process|file-descriptor | 51,180 | <p>Since you're on Linux, you've (almost certainly) got the <code>/proc</code> filesystem mounted. That means that the easiest method is going to be to get a list of the contents of <code>/proc/self/fd</code>; each file in there is named after a FD. (Use <code>g_dir_open</code>, <code>g_dir_read_name</code> and <code>g_dir_close</code> to do the listing, of course.)</p>
<p>Getting the information otherwise is moderately awkward (there's no helpful POSIX API for example; this is an area that wasn't standardized).</p> |
6,710,350 | Copying text to the clipboard using Java | <p>I want to copy text from a <code>JTable</code>'s cell to the clipboard, making it available to be pasted into other programs such as Microsoft Word. I have the text from the <code>JTable</code>, but I am unsure how to copy it to the clipboard.</p> | 6,713,290 | 6 | 0 | null | 2011-07-15 16:41:02.89 UTC | 42 | 2021-08-03 22:16:36.447 UTC | 2018-02-09 22:14:23.52 UTC | null | 63,550 | null | 765,134 | null | 1 | 178 | java|swing|text|clipboard | 140,989 | <p>This works for me and is quite simple:</p>
<p>Import these:</p>
<pre><code>import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
</code></pre>
<p>And then put this snippet of code wherever you'd like to alter the clipboard:</p>
<pre><code>String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
</code></pre> |
6,860,525 | C++: What is faster - lookup in hashmap or switch statement? | <p>I have a code pattern which translates one integer to another. Just like this:</p>
<pre><code>int t(int value) {
switch (value) {
case 1: return const_1;
case 3: return const_2;
case 4: return const_3;
case 8: return const_4;
default: return 0;
}
}
</code></pre>
<p>It has about 50 entries currently, maybe later on there will be some more, but probably no more than hundred or two. All the values are predefined, and of course I can order case labels by their values. So the question is, what will be faster - this approach or put this into hash map (I have no access to std::map, so I'm speaking about custom hash map available in my SDK) and perform lookups in that table? Maybe it's a bit of premature optimization, though... But I just need your opinions. </p>
<p>Thanks in advance.</p>
<p><strong>EDIT</strong>: My case values are going to be in range from 0 to 0xffff. And regarding the point of better readability of hash map. I'm not sure it really will have better readability, because I still need to populate it with values, so that sheet of constants mapping is still needs to be somewhere in my code.</p>
<p><strong>EDIT-2</strong>: Many useful answers were already given, much thanks. I'd like to add some info here. My hash key is integer, and my hash function for integer is basically just one multiplication with integral overflow:</p>
<pre><code>EXPORT_C __NAKED__ unsigned int DefaultHash::Integer(const int& /*aInt*/)
{
_asm mov edx, [esp+4]
_asm mov eax, 9E3779B9h
_asm mul dword ptr [edx]
_asm ret
}
</code></pre>
<p>So it should be quite fast.</p> | 6,860,557 | 9 | 13 | null | 2011-07-28 14:22:19.91 UTC | 8 | 2013-05-15 19:14:00.327 UTC | 2011-07-28 17:09:30.94 UTC | null | 371,804 | null | 371,804 | null | 1 | 31 | c++|performance|hashmap|switch-statement | 17,283 | <p>A <code>switch</code> construct is faster (or at least not slower).</p>
<p>That's mostly because a <code>switch</code> construct gives static data to the compiler, while a runtime structure like a hash map doesn't.</p>
<p>When possible compilers should compile <code>switch</code> constructs into array of code pointers: each item of the array (indexed by your indexes) points to the associated code. At runtime this takes O(1), while a hash map could take more: O(log n) at average case or O(n) at worst case, usually, and anyway a bigger constant number of memory accesses.</p> |
15,958,026 | Getting Errno 9: Bad file descriptor in python socket | <p>My code is this:</p>
<pre><code>while 1:
# Determine whether the server is up or down
try:
s.connect((mcip, port))
s.send(magic)
data = s.recv(1024)
s.close()
print data
except Exception, e:
print e
sleep(60)
</code></pre>
<p>It works fine on the first run, but gives me Errno 9 every time after. What am I doing wrong?</p>
<p>BTW,</p>
<pre><code>mcip = "mau5ville.com"
port = 25565
magic = "\xFE"
</code></pre> | 15,958,099 | 2 | 0 | null | 2013-04-11 20:13:23.51 UTC | 6 | 2020-10-28 22:06:10.197 UTC | null | null | null | null | 1,547,317 | null | 1 | 40 | python|sockets | 114,397 | <p>You're calling <code>connect</code> on the same socket you closed. You can't do that.</p>
<p>As for <a href="http://docs.python.org/2/library/socket.html#socket.socket.close" rel="noreferrer">the docs</a> for <code>close</code> say:</p>
<blockquote>
<p>All future operations on the socket object will fail.</p>
</blockquote>
<p>Just move the <code>s = socket.socket()</code> (or whatever you have) into the loop. (Or, if you prefer, use <a href="http://docs.python.org/2/library/socket.html#socket.create_connection" rel="noreferrer"><code>create_connection</code></a> instead of doing it in two steps, which makes this harder to get wrong, as well as meaning you don't have to guess at IPv4 vs. IPv6, etc.)</p> |
15,543,607 | AssertionError in Gson EnumTypeAdapter when using Proguard Obfuscation | <p>My project implements a <code>TypeAdapter</code> in <code>Gson</code> during serialization/deserialization for preserving object's polymorphism state. Anyhow, the project works fine during development tests, but when it is released with <strong>proguard obfuscation</strong> and tested, it just crashes.</p>
<pre><code>03-21 10:06:53.632: E/AndroidRuntime(12441): FATAL EXCEPTION: main
03-21 10:06:53.632: E/AndroidRuntime(12441): java.lang.AssertionError
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(SourceFile:724)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.TypeAdapters$26.create(SourceFile:753)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson.getAdapter(SourceFile:353)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(SourceFile:82)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(SourceFile:81)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(SourceFile:118)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(SourceFile:72)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson.getAdapter(SourceFile:353)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson.toJson(SourceFile:578)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson.toJsonTree(SourceFile:479)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson.toJsonTree(SourceFile:458)
03-21 10:06:53.632: E/AndroidRuntime(12441): at com.google.gson.Gson$3.serialize(SourceFile:137)
</code></pre>
<p>My Gson specific proguard configuration is:</p>
<pre><code>##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
#This is extra - added by me to exclude gson obfuscation
-keep class com.google.gson.** { *; }
##---------------End: proguard configuration for Gson ----------
</code></pre>
<p>The <strong>TypeAdapter</strong> I'm using is:</p>
<pre><code>public final class GsonWorkshiftAdapter implements JsonSerializer<IWorkshift>, JsonDeserializer<IWorkshift> {
private static final String CLASSNAME = "CLASSNAME";
private static final String INSTANCE = "INSTANCE";
@Override
public JsonElement serialize(IWorkshift src, Type typeOfSrc, JsonSerializationContext context) {
String className = src.getClass().getCanonicalName();
JsonElement elem = context.serialize(src);
JsonObject retValue = new JsonObject();
retValue.addProperty(CLASSNAME, className);
retValue.add(INSTANCE, elem);
return retValue;
}
@Override
public IWorkshift deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME);
String className = prim.getAsString();
Class<?> klass = null;
try { klass = Class.forName(className); }
catch (ClassNotFoundException e) { throw new JsonParseException(e.getMessage()); }
return context.deserialize(jsonObject.get(INSTANCE), klass);
}
}
</code></pre>
<p>I did a lot of search on this error specific to Gson, but couldn't find any helpful answer. However I found <a href="https://stackoverflow.com/questions/15483686/using-proguard-with-gson-and-roboguice-fails-when-using-a-enumtypeadapter">another question</a> with the similar issue.</p>
<p>Any help from developer's community would be appreciated.</p> | 30,167,048 | 7 | 1 | null | 2013-03-21 09:26:00.43 UTC | 14 | 2022-01-05 11:56:31.477 UTC | 2017-05-23 12:10:30.22 UTC | null | -1 | null | 966,550 | null | 1 | 80 | android|gson|proguard | 21,178 | <p>It seems like we must request that enumerations' members are kept.
Adding this to the proguard config file worked for me: </p>
<pre><code>-keepclassmembers enum * { *; }
</code></pre>
<p>Or, if you want to be more specific,</p>
<pre><code>-keepclassmembers enum com.your.package.** { *; }
</code></pre> |
10,586,962 | How to create popup boxes next to the links when mouse over them? | <p>Here is what I want to implement:</p>
<p>I have two hyperlinks that are displayed on the webpage:</p>
<pre><code><a href="http://foo.com"> foo </a>
<a href="http://bar.com"> bar </a>
</code></pre>
<p>and I also have two descriptions to the links as divs:</p>
<pre><code><div id="foo">foo means foo</div>
<div id="bar">bar means bar</div>
</code></pre>
<p>Now, when I mouse over the link of foo, the corresponding description div should pop up, and it should pop up right next to where my cursor is.</p>
<p>So if I mouse over "foo", a pop-up box containing "foo means foo" should appear right next to the mouse cursor. Same thing applies to "bar".</p>
<p>Please show a quick and simple way to implement this, with javascript/jquery, CSS, or combination of these.</p>
<p>P.S. I apologize for didn't explain clearly earlier, I actually want to add further links or images into the description div instead of pure text so a regular tool-tip perhaps would not do.</p>
<p>Thanks.</p> | 10,587,181 | 2 | 3 | null | 2012-05-14 16:03:43.997 UTC | 1 | 2019-07-05 03:17:00.06 UTC | 2012-05-14 16:19:33.607 UTC | null | 612,569 | null | 612,569 | null | 1 | 8 | javascript|jquery|css | 51,357 | <p>Here is the simpliest solution.</p>
<p><em>HTML:</em></p>
<pre><code><a href="http://foo.com" data-tooltip="#foo">foo</a>
<a href="http://bar.com" data-tooltip="#bar">bar</a>
<div id="foo">foo means foo</div>
<div id="bar">bar means bar</div>
</code></pre>
<p><em>CSS:</em></p>
<pre><code>div {
position: absolute;
display: none;
...
}
</code></pre>
<p><em>JavaScript:</em></p>
<pre><code>$("a").hover(function(e) {
$($(this).data("tooltip")).css({
left: e.pageX + 1,
top: e.pageY + 1
}).stop().show(100);
}, function() {
$($(this).data("tooltip")).hide();
});
</code></pre>
<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-js lang-js prettyprint-override"><code>$("a").hover(function(e) {
$($(this).data("tooltip")).css({
left: e.pageX + 1,
top: e.pageY + 1
}).stop().show(100);
}, function() {
$($(this).data("tooltip")).hide();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
position: absolute;
display: none;
border: 1px solid green;
padding:5px 15px;
border-radius: 15px;
background-color: lavender;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<a href="http://foo.com" data-tooltip="#foo">foo</a>
<a href="http://bar.com" data-tooltip="#bar">bar</a>
<div id="foo">foo means foo</div>
<div id="bar">bar means bar</div></code></pre>
</div>
</div>
</p>
<p><strong>DEMO:</strong> <a href="http://jsfiddle.net/8UkHn/" rel="nofollow noreferrer">http://jsfiddle.net/8UkHn/</a></p> |
25,413,301 | gmail login failure using python and imaplib | <p>I'm seeking some help logging into a gmail account and downloading some emails using a python script. I'm trying to adapt an approach found <a href="https://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">here</a>, but I'm running into a problem with step 1, accessing the account via imap. </p>
<p>here is the code I'm starting with: </p>
<pre><code>import email
import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com",993)
rc, resp = m.login('myemailaddress','mypassword')
</code></pre>
<p>I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "email.py", line 1, in <module>
import email, imaplib
File "/home/will/wd/email.py", line 14, in <module>
m.login('myemailaddress','mypassword')
File "/usr/lib/python3.4/imaplib.py", line 538, in login
raise self.error(dat[-1])
imaplib.error: b'[ALERT] Please log in via your web browser: http://support.google.com/mail/accounts/bin/answer.py?answer=78754 (Failure)'
</code></pre>
<p>Imap is indeed enabled in gmail settings. I have looked at the instruction on the google support link and questions regarding this error in similar situations, such as <a href="https://stackoverflow.com/questions/5479240/python-imaplib-error">here</a> and <a href="https://stackoverflow.com/questions/10013736/how-can-i-avoid-google-mail-server-asking-me-to-log-in-via-browser">here</a>, but my situation is different from the first because <br>1) it never worked to start with, and<br> 2) I'm not running it so frequently to get blocked. Its also different from the second example because this is a normal gmail account, not a custom domain with a google apps account. <br>Using the <a href="https://accounts.google.com/DisplayUnlockCaptcha" rel="noreferrer">https://accounts.google.com/DisplayUnlockCaptcha</a> to try and allow access doesn't work for me either.</p>
<p>The only thing that allows login to work is to change my google accounts security settings to "allow access for less secure apps". </p>
<p>My question is: how can I fix my code (or my setup more generally) to allow me to login, without relaxing my accounts security settings? Is there some way to meet security requirements using libimap?</p> | 26,131,731 | 5 | 5 | null | 2014-08-20 19:52:58.817 UTC | 5 | 2020-10-01 21:21:47.4 UTC | 2017-05-23 10:31:34.66 UTC | null | -1 | null | 3,757,989 | null | 1 | 26 | python|email|gmail-imap | 43,663 | <p>If you want to avoid this error without compromising your account's security, use OAuth to authenticate. The protocol is documented <a href="https://developers.google.com/gmail/xoauth2_protocol" rel="noreferrer">here</a>, and there is <a href="https://code.google.com/p/google-mail-oauth2-tools/wiki/OAuth2DotPyRunThrough" rel="noreferrer">Python sample code</a> that shows the use of XOAUTH2 with imaplib.</p>
<p>Independent of this, you should consider enabling <a href="https://www.google.com/landing/2step/" rel="noreferrer">two-step verification</a> on your account to make it more secure. If you do, you can use an <a href="https://support.google.com/accounts/answer/185833" rel="noreferrer">App Password</a> to connect to IMAP, which might also avoid the above warning.</p> |
25,182,011 | Why async / await allows for implicit conversion from a List to IEnumerable? | <p>I've just been playing around with async/await and found out something interesting. Take a look at the examples below:</p>
<pre><code>// 1) ok - obvious
public Task<IEnumerable<DoctorDto>> GetAll()
{
IEnumerable<DoctorDto> doctors = new List<DoctorDto>
{
new DoctorDto()
};
return Task.FromResult(doctors);
}
// 2) ok - obvious
public async Task<IEnumerable<DoctorDto>> GetAll()
{
IEnumerable<DoctorDto> doctors = new List<DoctorDto>
{
new DoctorDto()
};
return await Task.FromResult(doctors);
}
// 3) ok - not so obvious
public async Task<IEnumerable<DoctorDto>> GetAll()
{
List<DoctorDto> doctors = new List<DoctorDto>
{
new DoctorDto()
};
return await Task.FromResult(doctors);
}
// 4) !! failed to build !!
public Task<IEnumerable<DoctorDto>> GetAll()
{
List<DoctorDto> doctors = new List<DoctorDto>
{
new DoctorDto()
};
return Task.FromResult(doctors);
}
</code></pre>
<p>Consider cases 3 and 4. The only difference is that 3 uses async/await keywords. 3 builds fine, however 4 gives an error about implicit conversion of a List to IEnumerable:</p>
<pre><code>Cannot implicitly convert type
'System.Threading.Tasks.Task<System.Collections.Generic.List<EstomedRegistration.Business.ApiCommunication.DoctorDto>>' to
'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<EstomedRegistration.Business.ApiCommunication.DoctorDto>>'
</code></pre>
<p>What is it that async/await keywords change here?</p> | 25,182,311 | 3 | 8 | null | 2014-08-07 12:02:46.787 UTC | 7 | 2020-04-24 08:52:17.623 UTC | 2014-08-07 12:09:11.53 UTC | null | 672,018 | null | 672,018 | null | 1 | 32 | c#|.net|asynchronous | 33,254 | <p><code>Task<T></code> is simply not a covariant type.</p>
<p>Although <code>List<T></code> can be converted to <code>IEnumerable<T></code>, <code>Task<List<T>></code> cannot be converted to <code>Task<IEnumerable<T>></code>. And In #4, <code>Task.FromResult(doctors)</code> returns <code>Task<List<DoctorDto>></code>.</p>
<p>In #3, we have:</p>
<pre><code>return await Task.FromResult(doctors)
</code></pre>
<p>Which is the same as:</p>
<pre><code>return await Task.FromResult<List<DoctorDto>>(doctors)
</code></pre>
<p>Which is the same as:</p>
<pre><code>List<DoctorDto> result = await Task.FromResult<List<DoctorDto>>(doctors);
return result;
</code></pre>
<p>This works because <code>List<DoctorDto></code> can be converted <code>IEnumerable<DoctorDto></code>.</p> |
22,717,428 | Vagrant error : Failed to mount folders in Linux guest | <p>I have some issues with Vagrant shared folders, my base system is Ubuntu 13.10 desktop.</p>
<p>I do not understand why I have this error is something that is not right configured ? Is a NFS issue or Virtualbox Guest Additions ? I have tried with different many boxes but the same issue.</p>
<pre><code>Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:
mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` /vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` /vagrant /vagrant
</code></pre>
<p>Here is the complete process after <code>vagrant up</code> :</p>
<pre><code>$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'u131032'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1396020504136_46442
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
default: Adapter 2: hostonly
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Error: Connection timeout. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
default: Error: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
GuestAdditions versions on your host (4.3.10) and guest (4.2.16) do not match.
* Stopping VirtualBox Additions
...done.
Reading package lists...
Building dependency tree...
Reading state information...
The following packages were automatically installed and are no longer required:
dkms libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libfontenc1
libgl1-mesa-dri libglapi-mesa libice6 libllvm3.3 libpciaccess0 libpixman-1-0
libsm6 libtxc-dxtn-s2tc0 libxaw7 libxcomposite1 libxdamage1 libxfixes3
libxfont1 libxkbfile1 libxmu6 libxpm4 libxrandr2 libxrender1 libxt6
x11-common x11-xkb-utils xfonts-base xfonts-encodings xfonts-utils
xserver-common xserver-xorg-core
Use 'apt-get autoremove' to remove them.
The following packages will be REMOVED:
virtualbox-guest-dkms* virtualbox-guest-utils* virtualbox-guest-x11*
0 upgraded, 0 newly installed, 3 to remove and 0 not upgraded.
After this operation, 11.1 MB disk space will be freed.
(Reading database ... 65615 files and directories currently installed.)
Removing virtualbox-guest-dkms ...
-------- Uninstall Beginning --------
Module: virtualbox-guest
Version: 4.2.16
Kernel: 3.11.0-18-generic (i686)
-------------------------------------
Status: Before uninstall, this module version was ACTIVE on this kernel.
vboxguest.ko:
- Uninstallation
- Deleting from: /lib/modules/3.11.0-18-generic/updates/dkms/
- Original module
- No original module was found for this module on this kernel.
- Use the dkms install command to reinstall any previous module version.
vboxsf.ko:
- Uninstallation
- Deleting from: /lib/modules/3.11.0-18-generic/updates/dkms/
- Original module
- No original module was found for this module on this kernel.
- Use the dkms install command to reinstall any previous module version.
vboxvideo.ko:
- Uninstallation
- Deleting from: /lib/modules/3.11.0-18-generic/updates/dkms/
- Original module
- No original module was found for this module on this kernel.
- Use the dkms install command to reinstall any previous module version.
depmod....
DKMS: uninstall completed.
------------------------------
Deleting module version: 4.2.16
completely from the DKMS tree.
------------------------------
Done.
Removing virtualbox-guest-x11 ...
Purging configuration files for virtualbox-guest-x11 ...
Removing virtualbox-guest-utils ...
Purging configuration files for virtualbox-guest-utils ...
Processing triggers for ureadahead ...
Processing triggers for man-db ...
Reading package lists...
Building dependency tree...
Reading state information...
dkms is already the newest version.
dkms set to manually installed.
linux-headers-3.11.0-18-generic is already the newest version.
linux-headers-3.11.0-18-generic set to manually installed.
The following packages were automatically installed and are no longer required:
libdrm-intel1 libdrm-nouveau2 libdrm-radeon1 libfontenc1 libgl1-mesa-dri
libglapi-mesa libice6 libllvm3.3 libpciaccess0 libpixman-1-0 libsm6
libtxc-dxtn-s2tc0 libxaw7 libxcomposite1 libxdamage1 libxfixes3 libxfont1
libxkbfile1 libxmu6 libxpm4 libxrandr2 libxrender1 libxt6 x11-common
x11-xkb-utils xfonts-base xfonts-encodings xfonts-utils xserver-common
xserver-xorg-core
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Copy iso file /usr/share/virtualbox/VBoxGuestAdditions.iso into the box /tmp/VBoxGuestAdditions.iso
mount: block device /tmp/VBoxGuestAdditions.iso is write-protected, mounting read-only
Installing Virtualbox Guest Additions 4.3.10 - guest version is 4.2.16
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.10 Guest Additions for Linux............
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox DKMS kernel modules ...done.
Removing existing VirtualBox non-DKMS kernel modules ...done.
Building the VirtualBox Guest Additions kernel modules ...done.
Doing non-kernel setup of the Guest Additions ...done.
Starting the VirtualBox Guest Additions ...done.
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.
An error occurred during installation of VirtualBox Guest Additions 4.3.10. Some functionality may not work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
nfsd running
sudo: /usr/bin/exportfs: command not found
==> default: Mounting NFS shared folders...
==> default: Mounting shared folders...
default: /vagrant => /home/me/Documents/Work/project/vagrant
Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:
mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` /vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` /vagrant /vagrant
</code></pre>
<p>My Vagrantfile configuration is :</p>
<pre><code># -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
personalization = File.expand_path("../Personalization", __FILE__)
load personalization
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = $base_box
config.vm.box_url = $base_box_url
config.vm.hostname = $vhost + ".dev"
config.hostsupdater.aliases = ["api." + $vhost + ".dev", "mysql." + $vhost + ".dev"]
config.hostsupdater.remove_on_suspend = true
# set auto_update to ture to check the correct
# additions version when booting the machine
config.vbguest.auto_update = true
config.vbguest.auto_reboot = true
config.vm.network :private_network, ip: $ip
config.vm.synced_folder "../", "/srv/www/vhosts/" + $vhost + ".dev", type: "nfs"
config.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 2048]
v.customize ["modifyvm", :id, "--cpus", "1"]
v.customize ["modifyvm", :id, "--cpuexecutioncap", "100"]
v.customize ["modifyvm", :id, "--ioapic", "off"]
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
config.vm.provision "shell" do |s|
s.path = "vagrant-bootstrap.sh"
s.args = $vhost + " " + $mysql_password + " " + $application_database
end
end
</code></pre>
<p>The Personalization file is :</p>
<pre><code># Name of the vhost to create
$vhost = "project"
# Use the Ubunut 32bit or 64bit
$base_box_url = "http://cloud-images.ubuntu.com/vagrant/saucy/current/saucy-server-cloudimg-i386-vagrant-disk1.box"
# VM IP
$ip = "192.168.7.7"
# Base box name
$base_box = "u131032"
# MySQL
$mysql_password = "admin"
$application_database = "project"
</code></pre>
<p>The following plugins are enabled in Vagrant:</p>
<pre><code>$ vagrant plugin list
vagrant-hostsupdater (0.0.11)
vagrant-login (1.0.1, system)
vagrant-share (1.0.1, system)
vagrant-vbguest (0.10.0)
</code></pre> | 23,752,848 | 22 | 2 | null | 2014-03-28 15:46:04.39 UTC | 120 | 2021-01-29 16:42:11.357 UTC | null | null | null | null | 574,371 | null | 1 | 283 | ubuntu|virtualbox|vagrant|nfs | 141,969 | <p>The plugin vagrant-vbguest <a href="https://github.com/dotless-de/vagrant-vbguest"><img src="https://i.stack.imgur.com/hD37w.png" width="16" height="16" alt="GitHub"></a> <a href="https://rubygems.org/gems/vagrant-vbguest"><img src="https://i.stack.imgur.com/MEQSm.png" alt="RubyGems"></a> solved my problem: </p>
<pre><code>$ vagrant plugin install vagrant-vbguest
</code></pre>
<p>Output:</p>
<pre><code>$ vagrant reload
==> default: Attempting graceful shutdown of VM...
...
==> default: Machine booted and ready!
GuestAdditions 4.3.12 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
==> default: Mounting NFS shared folders...
==> default: VM already provisioned. Run `vagrant provision` or use `--provision` to force it
</code></pre>
<p>Just make sure you are running the latest version of VirtualBox</p> |
13,655,048 | Display underscore rather than subscript in gnuplot titles | <p><strong>Short question</strong>:
How do I display the <code>_</code> (underscore) character in a title in gnuplot that is assigned from a variable name in gnuplot?</p>
<p><strong>Details</strong>:
I have something like the following code:</p>
<pre><code>items = "foo_abc foo_bcd bar_def"
do for [item in items] {
set title item
set output item.eps
plot item."-input.txt" using 1:2 title item with linespoints
}
</code></pre>
<p>This works fine with gnuplot except that the title get changed from foo_abc to foo<sub>a</sub>bc. I don't know if I want to use an escape character because I don't want that to be in the file name. I've tried a couple of different options with single vs. double quotes but I haven't found what I need yet.</p> | 13,655,372 | 5 | 4 | null | 2012-12-01 00:17:55.04 UTC | 7 | 2017-05-02 14:46:01.65 UTC | 2012-12-01 00:31:26.97 UTC | null | 1,030,675 | null | 937,324 | null | 1 | 31 | gnuplot | 23,992 | <p>If you are using the enhanced eps terminal, that is the reason you need to escape the underscore in the first place. There was <a href="https://stackoverflow.com/questions/13631006/how-is-produced-in-gnuplot/13633472#13633472">another related question</a> today which explains the issue a bit. When you set the terminal, try:</p>
<pre><code>set terminal postscript noenhanced <whatever else here...>
</code></pre>
<p>That works for me (Arch linux, gnuplot 4.7.0). If the enhanced terminal is essential, below is a partial solution I found. The assumption is that the underscore always appears in the same place in the string.</p>
<pre><code>set terminal postscript enhanced
items = 'foo\_abc foo\_bcd bar\_def'
do for [item in items] {
set output item[1:3].item[5:*].'.eps'
set title item
plot sin(x)
}
</code></pre>
<p>This way you can escape the underscore and not have the \ appear in the filename. Note the use of single quotes for the 'items' string; see the previously linked question for details.</p> |
13,546,778 | How to communicate between popup.js and background.js in chrome extension? | <p>The message from popup.js is being posted twice to background.js, but I get absolutely nothing from background.js. </p>
<p>background.js</p>
<pre><code>function login(username,password){
console.log(username);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/login/", true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
data = {"username":username,"password":password};
console.log(JSON.stringify(data));
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
console.log(resp);
var lStorage = localStorage;
localStorage.setItem("username",resp["username"]);
localStorage.setItem("apiKey",resp["apiKey"]);
localStorage.setItem("password",resp["password"]);
console.log(localStorage.getItem("username"));
}
};
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse){
console.log("hello");
if(request.msg == "login") {
//alert(request.password);
login(request.username,request.password);}
}
);
chrome.extension.onConnect.addListener(function(port) {
console.log("Connected .....");
port.onMessage.addListener(function(msg) {
console.log("message recieved "+ msg);
port.postMessage("Hi Popup.js");
});
});
</code></pre>
<p>popup.js:</p>
<pre><code>function login(){
alert(document.login.username.value);
chrome.extension.sendRequest({ msg: "login",username:document.login.username.value,password:document.login.password.value});
document.getElementById('openBackgroundWindow').visbility = "hidden";
}
$(document).ready(function (){
checkUserAuth();
console.log("Inside");
$("#openBackgroundWindow").click(login);
});
function checkUserAuth(){
console.log(localStorage.getItem("apiKey"));
if(localStorage.getItem("apiKey") != null)
{
$("#openBackgroundWindow").visbility ="hidden";
}
}
var port = chrome.extension.connect({name: "Sample Communication"});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved"+ msg);
});
</code></pre> | 13,549,245 | 4 | 0 | null | 2012-11-24 23:37:22.05 UTC | 47 | 2022-07-14 07:31:12.71 UTC | 2017-01-08 16:52:19.18 UTC | null | 176,877 | null | 105,167 | null | 1 | 73 | javascript|google-chrome-extension | 61,928 | <p><strong><em>Method - A :</em></strong> <br/><em>Using Long Lived Connections</em> you can communicate from background.js to popup.js of extension page for any activities( Here i have included popup.html and <code>only initiated</code> sample communication from popup.js as a sample)</p>
<p><strong><em>background.js</em></strong></p>
<pre><code> chrome.extension.onConnect.addListener(function(port) {
console.log("Connected .....");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
port.postMessage("Hi Popup.js");
});
})
</code></pre>
<p><strong><em>popup.js</em></strong></p>
<pre><code> var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});
</code></pre>
<p><strong><em>Method - B :</em></strong> <br/>Direct Manipulation of DOM* if your end result is modification of DOM, you can achieve with this</p>
<p><strong><em>popup.html</em></strong></p>
<pre><code><html>
<head>
<script src="popup.js"></script>
</head>
<body>
<div id="x" value="m">Some thing</div>
</body>
</html>
</code></pre>
<p><strong><em>background.js</em></strong></p>
<pre><code>var views = chrome.extension.getViews({
type: "popup"
});
for (var i = 0; i < views.length; i++) {
views[i].document.getElementById('x').innerHTML = "My Custom Value";
}
</code></pre>
<p><strong><em>Method - C :</em></strong> </p>
<p><em>Using Long Lived Connections</em> you can communicate from background.js to popup.js of extension page for any activities( Here i have not included popup.html and initiated sample communication from background.js; </p>
<p><strong><em>background.js</em></strong></p>
<pre><code>chrome.browserAction.onClicked.addListener(function(tab) {
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});
});
</code></pre>
<p>I have changed your code and made it running after eliminating some stuff and making it a simple version. <strong>Add your code for AJAX requests and HTML DOM on this skeleton</strong>( Make sure you add <code><script></code> tag in head section and put <code>chrome.extension.onConnect.addListener</code> out of <code>(xhr.readyState == 4)</code> code;)</p>
<p><strong><em>popup.html</em></strong></p>
<pre><code><html >
<head>
<script src="popup.js"></script>
</head>
<body></body>
</html>
</code></pre>
<p><strong><em>manifest.json</em></strong></p>
<pre><code>{
"name": "Demo",
"version": "1.0",
"manifest_version": 2,
"description": "This is a demo",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": ["<all_urls>",
"storage",
"tabs"
]
}
</code></pre>
<p><strong><em>background.js</em></strong></p>
<pre><code>chrome.extension.onConnect.addListener(function(port) {
console.log("Connected .....");
port.onMessage.addListener(function(msg) {
console.log("message recieved " + msg);
port.postMessage("Hi Popup.js");
});
});
</code></pre>
<p><strong><em>popup.js</em></strong></p>
<pre><code>var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});
</code></pre> |
20,461,030 | CURRENT_DATE/CURDATE() not working as default DATE value | <p>Pretty straight forward question here, I think this should work but it doesn't. Why doesn't it?</p>
<pre><code>CREATE TABLE INVOICE(
INVOICEDATE DATE NOT NULL DEFAULT CURRENT_DATE
)
</code></pre> | 20,461,045 | 10 | 2 | null | 2013-12-09 00:18:10.167 UTC | 9 | 2022-04-24 18:11:34.903 UTC | null | null | null | null | 977,541 | null | 1 | 73 | mysql|date|default-value | 152,231 | <p>It doesn't work because it's not supported</p>
<blockquote>
<p>The <code>DEFAULT</code> clause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as <code>NOW()</code> or <code>CURRENT_DATE</code>. The exception is that you can specify <code>CURRENT_TIMESTAMP</code> as the default for a <code>TIMESTAMP</code> column</p>
</blockquote>
<p><a href="http://dev.mysql.com/doc/refman/5.5/en/create-table.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.5/en/create-table.html</a></p> |
20,451,719 | Cannot Set date.timezone In php.ini file | <p>I'm using php5.5 and getting this error whenever I used the date function in PHP:</p>
<pre><code> Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /var/www/info.php on line 1
</code></pre>
<p>the loaded configuration file is here:</p>
<pre><code>/etc/php5/apache2/php.ini
</code></pre>
<p>so I changed the date.timezone setting into this:</p>
<pre><code>[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Asia/Jakarta
; http://php.net/date.default-latitude
;date.default_latitude = 31.7667
; http://php.net/date.default-longitude
;date.default_longitude = 35.2333
; http://php.net/date.sunrise-zenith
;date.sunrise_zenith = 90.583333
; http://php.net/date.sunset-zenith
;date.sunset_zenith = 90.583333
</code></pre>
<p>Then I restart the server:</p>
<pre><code>sudo /etc/init.d/apache2 restart
</code></pre>
<p>but still getting this error, I tried to check the .ini file in the Additional ini file location but none of it is overriding the date.timezone setting</p>
<p>I've checked the php.ini file permission, but still not working
please guide me to solve this problem, thanks..</p> | 20,731,466 | 12 | 3 | null | 2013-12-08 09:16:19.737 UTC | 4 | 2019-07-17 08:41:33.603 UTC | 2017-01-25 11:31:41.777 UTC | null | 6,887,672 | null | 2,424,235 | null | 1 | 22 | php|datetime|timezone | 89,172 | <p>finally solved my problem,
this is my Loaded Configuration File:</p>
<pre><code>/etc/php5/apache2/php.ini
</code></pre>
<p>modified the date.timezone here but it's not working.</p>
<p>So, I check the "Scan this dir for additional .ini files " values in phpinfo() which point to:</p>
<pre><code>/etc/php5/apache2/conf.d
</code></pre>
<p>then I search date.timezone from all files in that folder but found none.</p>
<p>this is my Additional .ini file parsed value in phpinfo():</p>
<pre><code>/etc/php5/apache2/conf.d/05-opcache.ini, /etc/php5/apache2/conf.d/10-pdo.ini, /etc/php5/apache2/conf.d/20-json.ini, /etc/php5/apache2/conf.d/20-mysql.ini, /etc/php5/apache2/conf.d/20-mysqli.ini, /etc/php5/apache2/conf.d/20-pdo_mysql.ini, /etc/php5/apache2/conf.d/20-xdebug.ini, /etc/php5/apache2/conf.d/30-mcrypt.ini
</code></pre>
<p>I modified /etc/php5/apache2/conf.d/20-xdebug.ini, and appended this line: </p>
<pre><code>date.timezone = Asia/Jakarta
</code></pre>
<p>very weird but this solved my problem !!!</p> |
3,814,322 | List to integer or double in R | <p>I have a list of about 1000 single integers. I need to be able to do some mathematical computations, but they're stuck in list or character form. How can I switch them so they're usable?</p>
<p>sample data:</p>
<pre><code>> y [[1]]
[1] "7" "3" "1" "6" "7" "1" "7" "6" "5" "3" "1" "3" "3" "0" "6" "2" "4" "9"
[19] "1" "9" "2" "2" "5" "1" "1" "9" "6" "7" "4" "4" "2" "6" "5" "7" "4" "7"
[37] "4" "2" "3" "5" "5" "3" "4" "9" "1" "9" "4" "9" "3" "4" "9" "6" "9" "8"
[55] "3" "5" "2" "0" "3" "1" "2" "7" "7" "4" "5" "0" "6" "3" "2" "6" "2" "3"
[73] "9" "5" "7" "8" "3" "1" "8" "0" "1" "6" "9" "8" "4" "8" "0" "1" "8" "6" ...
</code></pre>
<p>Just the first couple of lines.</p> | 3,814,359 | 2 | 1 | null | 2010-09-28 15:24:04.937 UTC | 5 | 2016-08-12 12:21:48.25 UTC | 2016-08-12 12:21:48.25 UTC | null | 322,912 | null | 446,667 | null | 1 | 19 | list|r|vector | 68,792 | <p>See ?unlist :</p>
<pre><code>> x
[[1]]
[1] "1"
[[2]]
[1] "2"
[[3]]
[1] "3"
> y <- as.numeric(unlist(x))
> y
[1] 1 2 3
</code></pre>
<p>If this doesn't solve your problem, please specify what exactly you want to do.</p>
<hr>
<p>edit :
It's even simpler apparently :</p>
<pre><code>> x <- list(as.character(1:3))
> x
[[1]]
[1] "1" "2" "3"
> y <-as.numeric(x[[1]])
> y
[1] 1 2 3
</code></pre> |
3,371,208 | How do I set up a Sinatra app under Apache with Passenger? | <p>Let's say I have the simplest single-file Sinatra app. The <a href="http://www.sinatrarb.com/" rel="nofollow noreferrer">hello world</a> on their homepage will do. I want to run it under Apache with Phusion Passenger, AKA mod_rails.</p>
<ul>
<li>What directory structure do I need?</li>
<li>What do I have to put in the vhost conf file?</li>
<li>I understand I need a rackup file. What goes in it and why?</li>
</ul> | 3,371,343 | 2 | 0 | null | 2010-07-30 12:02:32.23 UTC | 27 | 2019-07-28 18:23:37.69 UTC | 2019-07-28 18:23:37.69 UTC | null | 964,243 | null | 13,989 | null | 1 | 26 | ruby|apache|sinatra|passenger|rack | 14,631 | <h3>Basic directory structure:</h3>
<pre><code>app
|-- config.ru # <- rackup file
|-- hello-app.rb # <- your application
|-- public/ # <- static public files (passenger needs this)
`-- tmp/
`-- restart.txt # <- touch this file to restart app
</code></pre>
<h3>Virtual host file:</h3>
<pre><code><VirtualHost *:80>
ServerName app.example.com
DocumentRoot /path/to/app/public
<Directory /path/to/app/public>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<h3>config.ru</h3>
<pre><code># encoding: UTF-8
require './hello-app'
run Sinatra::Application
</code></pre>
<h3>hello-app.rb (sample application):</h3>
<pre><code>#!/usr/bin/env ruby
# encoding: UTF-8
require 'rubygems' # for ruby 1.8
require 'sinatra'
get '/hi' do
"Hello World!"
end
</code></pre>
<p><code>restart.txt</code> is empty.</p>
<hr>
<h3>Mildly useful links:</h3>
<ul>
<li><a href="http://docs.heroku.com/rack#sinatra" rel="noreferrer">Heroku rack documentation</a></li>
<li><a href="http://www.modrails.com/documentation/Users%20guide.html#_rackup_specifications_for_various_web_frameworks" rel="noreferrer">Phusion Passenger documentation</a></li>
</ul> |
3,699,725 | How to split string into equal-length substrings? | <p>Im looking for an <em>elegant</em> way in <a href="http://www.scala-lang.org/" rel="noreferrer">Scala</a> to split a given string into substrings of fixed size (the last string in the sequence might be shorter).</p>
<p>So</p>
<pre><code>split("Thequickbrownfoxjumps", 4)
</code></pre>
<p>should yield</p>
<pre><code>["Theq","uick","brow","nfox","jump","s"]
</code></pre>
<p>Of course I could simply use a loop but there has to be a more elegant (functional style) solution.</p> | 3,699,749 | 2 | 0 | null | 2010-09-13 10:52:34.553 UTC | 2 | 2017-07-07 14:59:39.353 UTC | 2015-01-10 12:47:15.01 UTC | null | 1,305,344 | null | 81,424 | null | 1 | 28 | scala|functional-programming|split | 12,303 | <pre><code>scala> val grouped = "Thequickbrownfoxjumps".grouped(4).toList
grouped: List[String] = List(Theq, uick, brow, nfox, jump, s)
</code></pre> |
3,707,797 | Where does Android store SQLite's database version? | <p>I am unable to find where Android stores the database version within the SQLite database file. Where exactly is the database version stored?</p> | 3,711,985 | 2 | 0 | null | 2010-09-14 09:53:19.157 UTC | 21 | 2016-10-18 03:36:47.383 UTC | 2016-10-18 03:36:47.383 UTC | null | 5,662,596 | null | 195,802 | null | 1 | 92 | android|database|android-sqlite | 28,711 | <p>You can read the version using <code>android.database.sqlite.SQLiteDatabase.getVersion()</code>.</p>
<p>Internally, this method executes the SQL statement "<a href="http://www.sqlite.org/pragma.html#pragma_schema_version" rel="noreferrer"><code>PRAGMA user_version</code></a>". I got that from the <a href="https://github.com/android/platform_frameworks_base/blob/master/core/java/android/database/sqlite/SQLiteDatabase.java#L861" rel="noreferrer">Android source code</a>.</p>
<p>In the database file, the version is stored at byte offset 60 in the <a href="http://www.sqlite.org/fileformat.html#database_header" rel="noreferrer">database header</a> of the database file, in the field 'user cookie'.</p> |
29,404,784 | How Nodejs's internal threadpool works exactly? | <p>I have read a lot of article about how NodeJs works. But I still can not figure out exactly how the internal threads of Nodejs proceed IO operations.</p>
<p>In this answer <a href="https://stackoverflow.com/a/20346545/1813428">https://stackoverflow.com/a/20346545/1813428</a> , he said there are 4 internal threads in the thread pool of NodeJs to process I/O operations . So what if I have 1000 request coming at the same time , every request want to do I/O operations like retrieve an enormous data from the database . NodeJs will deliver these request to those 4 worker threads respectively without blocking the main thread . So the maximum number of I/O operations that NodeJs can handle at the same time is 4 operations. Am I wrong?.</p>
<p>If I am right , where will the remaining requests will handle?. The main single thread is non blocking and keep driving the request to corresponding operators , so where will these requests go while all the workers thread is full of task? . </p>
<p>In the image below , all of the internal worker threads are full of task , assume all of them need to <strong>retrieve a lot of data from the database</strong> and the main single thread keep driving new requests to these workers, where will these requests go? Does it have a internal task queuse to store these requests? </p>
<p><img src="https://i.stack.imgur.com/VAEW0.png" alt="enter image description here"></p> | 29,472,222 | 3 | 3 | null | 2015-04-02 04:03:36.057 UTC | 8 | 2021-07-25 13:47:20.783 UTC | 2017-05-23 12:02:11.563 UTC | null | -1 | null | 1,813,428 | null | 1 | 15 | javascript|node.js|multithreading|event-loop | 8,753 | <p>The single, per-process thread pool provided by libuv creates 4 threads by default. The <code>UV_THREADPOOL_SIZE</code> environment variable can be used to alter the number of threads created when the <code>node</code> process starts, up to a maximum value of 1024 (as of libuv version 1.30.0).</p>
<p>When all of these threads are blocked, further requests to use them are queued. The API method to request a thread is called <code>uv_queue_work</code>.</p>
<p>This thread pool is used for any system calls that will result in <em>blocking</em> IO, which includes local file system operations. It can also be used to reduce the effect of CPU intensive operations, as @Andrey mentions.</p>
<p><em>Non-blocking</em> IO, as supported by most networking operations, don't need to use the thread pool.</p>
<p>If the source code for the database driver you're using is available and you're able to find reference to <code>uv_queue_work</code> then it is probably using the thread pool.</p>
<p>The libuv <a href="http://docs.libuv.org/en/latest/threadpool.html" rel="nofollow noreferrer">thread pool</a> documentation provides more technical details, if required.</p> |
16,567,129 | How to get table comments via SQL in Oracle? | <p>I've tried :</p>
<pre><code>select * from user_tab_comments;
</code></pre>
<p>and it returns me 3 columns "TABLE_NAME", "TABLE_TYPE", and "COMMENTS", but the "TABLE_NAME" column is like "encrypted", I need clear table names :</p>
<pre><code>TABLE_NAME TABLE_TYPE COMMENTS
BIN$IN1vjtqhTEKcWfn9PshHYg==$0 TABLE Résultat d'intégration d'une photo numérisée
BIN$PUwG3lb3QoazOc4QaC1sjw==$0 TABLE Motif de fin d'agrément de maître de stage
</code></pre>
<p>When I use <code>select * from user_tables;</code> TABLE_NAME is not "encrypted".</p> | 20,816,570 | 2 | 2 | null | 2013-05-15 13:59:48.517 UTC | 3 | 2020-03-27 08:47:33.03 UTC | 2020-03-27 08:47:33.03 UTC | null | 146,325 | null | 668,455 | null | 1 | 27 | sql|oracle | 83,594 | <p>Since 10g Oracle doesn't immediately drop tables when we issue a DROP TABLE statement. Instead it renames them like this <code>BIN$IN1vjtqhTEKcWfn9PshHYg==$0</code> and puts them in the recycle bin. This allows us to recover tables we didn't mean to drop. <a href="http://www.orafaq.com/node/968" rel="noreferrer">Find out more</a>.</p>
<p>Tables in the recycle bin are still tables, so they show up in ALL_TABLES and similar views. So if you only want to see comments relating only to live (non-dropped) tables you need to filter by table name:</p>
<pre><code>select * from all_tab_comments
where substr(table_name,1,4) != 'BIN$'
/
</code></pre>
<hr>
<blockquote>
<p>"I can't believe there isn't a flag column so you could do and is_recycled = 0 or something. "</p>
</blockquote>
<p>You're right, it would be incredible. So I checked the documentation it turns out Oracle 10g added a column called DROPPED to the USER_/ALL_/DBA_TABLES views.</p>
<pre><code>select tc.*
from all_tab_comments tc
join all_tables t
on tc.owner = t.owner
and tc.table_name = t.table_name
where t.dropped = 'NO'
/
</code></pre>
<p>Check out <a href="https://docs.oracle.com/database/121/REFRN/GUID-6823CD28-0681-468E-950B-966C6F71325D.htm#REFRN20286" rel="noreferrer">the documentation</a>. Obviously the need to join to the ALL_TABLES view requires more typing than filtering on the name, so depending on our need it might just be easier to keep the original WHERE clause.</p> |
16,107,471 | SQL Server Management Studio Skin / Appearance / Layout | <p>Can you apply a custom skin / appearance to SSMS? I am thinking something along the lines of a dark theme (black background, yellow font) you'd find in most IDEs</p> | 19,416,131 | 5 | 1 | null | 2013-04-19 14:53:36.527 UTC | 4 | 2020-11-20 07:16:16.16 UTC | 2016-11-14 14:45:04.607 UTC | null | 1,423,787 | null | 1,423,787 | null | 1 | 42 | ssms | 73,161 | <p>SSMS 2012 is build on the VS 2010 shell. Thus, it can use compatible ".vssettings" files to apply custom color schemes. </p>
<p>See also <a href="http://studiostyl.es/" rel="noreferrer">http://studiostyl.es/</a> for a gallery.</p> |
16,136,943 | How to get the second column from command output? | <p>My command's output is something like:</p>
<pre><code>1540 "A B"
6 "C"
119 "D"
</code></pre>
<p>The first column is always a number, followed by a space, then a double-quoted string.</p>
<p>My purpose is to get the second column only, like:</p>
<pre><code>"A B"
"C"
"D"
</code></pre>
<p>I intended to use <code><some_command> | awk '{print $2}'</code> to accomplish this. But the question is, some values in the second column contain space(s), which happens to be the default delimiter for <code>awk</code> to separate the fields. Therefore, the output is messed up:</p>
<pre><code>"A
"C"
"D"
</code></pre>
<p>How do I get the second column's value (with paired quotes) cleanly?</p> | 16,137,100 | 8 | 2 | null | 2013-04-21 22:36:40.99 UTC | 45 | 2019-05-09 09:35:51.253 UTC | 2016-04-10 02:30:23.007 UTC | null | 55,075 | null | 1,060,209 | null | 1 | 212 | shell|awk|ksh | 466,574 | <p>Or use sed & regex.</p>
<pre><code><some_command> | sed 's/^.* \(".*"$\)/\1/'
</code></pre> |
17,375,708 | How to create an HTML button that acts like a link to an item on the same page? | <p>I would like to create an HTML button that acts like a link to an item on the same page. So, when you click the button, it redirects to item on the same page. </p>
<p>How can I do this? (I would limit the solution to HTML, CSS, and JavaScript, because currently I am not using any other language)</p>
<p>Current Button (Bootstrap):</p>
<pre><code><a class="btn btn-large btn-primary" href="">Democracy</a>
</code></pre> | 17,375,863 | 7 | 1 | null | 2013-06-29 01:05:43.453 UTC | 3 | 2021-03-08 18:26:59.387 UTC | null | null | null | null | 1,873,905 | null | 1 | 10 | html|button|hyperlink | 40,722 | <p>This is assuming that you are not talking about scrolling down to a regular anchor, and instead you want to scroll to actual HTML elements on the page.</p>
<p>I'm not sure if jQuery counts for you, but if you're using Bootstrap, I imagine it does. If so, you can bind to the "click" event for your button and put some javascript code there to handle the scrolling. Typically you might associate the link/button with the element you want to scroll to using a "data" attribute (e.g. data-scroll="my-element-id").</p>
<p>Without jQuery, you'll have to make a function that contains the code as described, and put in an onclick attribute that references your function, and passes "this" as a parameter to your function, so you can get the reference to the link/button element that called it.</p>
<p>For the code to use to actually scroll to the corresponding element, check out this article: </p>
<p><a href="https://stackoverflow.com/questions/4801655/how-to-go-to-a-specific-element-on-page">How to go to a specific element on page?</a></p>
<p>Quick example without jQuery:</p>
<pre><code><a class="scrollbutton" data-scroll="#somethingonpage"
onchange="scrollto(this);">something on page</a>
<div id="somethingonpage">scrolls to here when you click on the link above</a>
<script type="text/javascript">
function scrollto(element) {
// get the element on the page related to the button
var scrollToId = element.getAttribute("data-scroll");
var scrollToElement = document.getElementById(scrollToId);
// make the page scroll down to where you want
// ...
}
</script>
</code></pre>
<p>With jQuery:</p>
<pre><code><a class="scrollbutton" data-scroll="#somethingonpage">something on page</a>
<div id="somethingonpage">scrolls to here when you click on the link above</a>
<script type="text/javascript">
$(".scrollbutton").click(function () {
// get the element on the page related to the button
var scrollToId = $(this).data("scroll");
var scrollToElement = document.getElementById(scrollToId);
// make the page scroll down to where you want
// ...
});
</script>
</code></pre>
<p>Note: If you literally want a "button" rather than a "link", you can really use any element and make that clickable, e.g.:</p>
<pre><code><button class="scrollbutton" data-scroll="#somethingonpage">something on page</button>
</code></pre> |
27,353,619 | How to use Google Play Services 6.5 granular dependency management | <p>This question is no longer valid. But answers may still be useful for others, so I will leave it here.</p>
<hr>
<p>Original question:</p>
<p>In a <a href="http://android-developers.blogspot.com/2014/11/google-play-services-65.html">blogpost</a> from 17 november, Google guys introduced long awaited granular dependency management (to cope with dex method limit). We have december 8th and I still cannot download the sdk (6.1 is the latest available), nor get the documentation on how to introduce granular dependency. Any news on this one? Or an idea how to get it before it's officialy released?</p> | 27,366,164 | 3 | 4 | null | 2014-12-08 07:52:57.013 UTC | 18 | 2017-10-07 16:54:18.717 UTC | 2015-01-28 11:58:54.59 UTC | null | 1,118,475 | null | 1,118,475 | null | 1 | 29 | android|google-play-services | 17,357 | <h1>Note!</h1>
<p>I will <strong>no longer be maintaining this answer</strong>, because Google is doing a very good job at doing the releases now. With a post on their <a href="http://android-developers.blogspot.co.at" rel="nofollow noreferrer">Android Developers Blog</a>, <a href="https://developers.google.com/android/guides/releases" rel="nofollow noreferrer">official release notes</a> and often also a video on their <a href="https://www.youtube.com/user/GoogleDevelopers" rel="nofollow noreferrer">YouTube channel</a> with a short overview of what's new.</p>
<p>I'll leave the last two (as of writing) updates and the original answer. Please find the previous updates <a href="https://stackoverflow.com/posts/27366164/revisions">here</a></p>
<h3>Update October 2016, Play Services 9.8.0</h3>
<p><a href="https://developers.google.com/android/guides/releases#october_2016_-_version_98" rel="nofollow noreferrer">Google Play Services Release Notes</a>,
<a href="https://developers.google.com/maps/documentation/android-api/releases" rel="nofollow noreferrer">Google Maps APIs Release Notes</a></p>
<p><strong>support-v4 dependency</strong></p>
<pre><code>com.google.android.gms:play-services-base:9.8.0
-> com.google.android.gms:play-services-basement:9.8.0
-> com.android.support:support-v4:24.0.0 -> 24.2.1
</code></pre>
<ul>
<li><a href="https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev24-2-1" rel="nofollow noreferrer">latest support-v4 version: 24.2.1</a></li>
</ul>
<h3>Update May 2016, Play Services 9.0.1</h3>
<p><a href="http://android-developers.blogspot.co.at/2016/05/google-play-services-90-updates.html" rel="nofollow noreferrer">Blog Post</a>,
<a href="https://developers.google.com/android/guides/releases#may_2016_-_v90" rel="nofollow noreferrer">Google Play Services Release Notes</a>,
<a href="https://developers.google.com/maps/documentation/android-api/releases" rel="nofollow noreferrer">Google Maps APIs Release Notes</a></p>
<pre><code># Google+
compile com.google.android.gms:play-services-plus:9.0.1
# Google Account Login
compile com.google.android.gms:play-services-auth:9.0.1
# Google Actions, Base Client Library
compile com.google.android.gms:play-services-base:9.0.1
# Google Address API
compile com.google.android.gms:play-services-identity:9.0.1
# Google App Indexing
compile com.google.android.gms:play-services-appindexing:9.0.1
# Google App Invites
compile com.google.android.gms:play-services-appinvite:9.0.1
# Google Analytics
compile com.google.android.gms:play-services-analytics:9.0.1
# Google Cast
compile com.google.android.gms:play-services-cast:9.0.1
# Google Cloud Messaging
compile com.google.android.gms:play-services-gcm:9.0.1
# Google Drive
compile com.google.android.gms:play-services-drive:9.0.1
# Google Fit
compile com.google.android.gms:play-services-fitness:9.0.1
# Google Location, Activity Recognition, and Places
compile com.google.android.gms:play-services-location:9.0.1
# Google Maps
compile com.google.android.gms:play-services-maps:9.0.1
# Google Mobile Ads
compile com.google.android.gms:play-services-ads:9.0.1
# Mobile Vision
compile com.google.android.gms:play-services-vision:9.0.1
# Google Nearby
compile com.google.android.gms:play-services-nearby:9.0.1
# Google Panorama Viewer
compile com.google.android.gms:play-services-panorama:9.0.1
# Google Play Game services
compile com.google.android.gms:play-services-games:9.0.1
# SafetyNet
compile com.google.android.gms:play-services-safetynet:9.0.1
# Android Pay
compile com.google.android.gms:play-services-wallet:9.0.1
# Android Wear
compile com.google.android.gms:play-services-wearable:9.0.1
</code></pre>
<h3>Update December 2015, Play Services 8.4.0</h3>
<p><a href="http://android-developers.blogspot.de/2015/12/google-play-services-84-sdk-is-available_18.html" rel="nofollow noreferrer">Blog Post</a>,
<a href="https://www.youtube.com/watch?v=-xwKQa9Tm5k" rel="nofollow noreferrer">Video</a>,
<a href="https://developers.google.com/android/guides/releases" rel="nofollow noreferrer">Google Play Services Release Notes</a>,
<a href="https://developers.google.com/maps/documentation/android-api/releases" rel="nofollow noreferrer">Google Maps APIs Release Notes</a></p>
<pre><code>dependencies {
# Google+
compile com.google.android.gms:play-services-plus:8.4.0
# Google Account Login
compile com.google.android.gms:play-services-auth:8.4.0
# Google Actions, Base Client Library
compile com.google.android.gms:play-services-base:8.4.0
# Google Address API
compile com.google.android.gms:play-services-identity:8.4.0
# Google App Indexing
compile com.google.android.gms:play-services-appindexing:8.4.0
# Google App Invites
compile com.google.android.gms:play-services-appinvite:8.4.0
# Google Analytics
compile com.google.android.gms:play-services-analytics:8.4.0
# Google Cast
compile com.google.android.gms:play-services-cast:8.4.0
# Google Cloud Messaging
compile com.google.android.gms:play-services-gcm:8.4.0
# Google Drive
compile com.google.android.gms:play-services-drive:8.4.0
# Google Fit
compile com.google.android.gms:play-services-fitness:8.4.0
# Google Location, Activity Recognition, and Places
compile com.google.android.gms:play-services-location:8.4.0
# Google Maps
compile com.google.android.gms:play-services-maps:8.4.0
# Google Mobile Ads
compile com.google.android.gms:play-services-ads:8.4.0
# Mobile Vision
compile com.google.android.gms:play-services-vision:8.4.0
# Google Nearby
compile com.google.android.gms:play-services-nearby:8.4.0
# Google Panorama Viewer
compile com.google.android.gms:play-services-panorama:8.4.0
# Google Play # Game services
compile com.google.android.gms:play-services-games:8.4.0
# SafetyNet
compile com.google.android.gms:play-services-safetynet:8.4.0
# Google Wallet
compile com.google.android.gms:play-services-wallet:8.4.0
# Android Wear
compile com.google.android.gms:play-services-wearable:8.4.0
}
</code></pre>
<p><strong>support-v4 dependency</strong></p>
<pre><code>com.google.android.gms:play-services-base:8.4.0
-> com.google.android.gms:play-services-basement:8.4.0
-> com.android.support:support-v4:23.0.0 -> 23.4.0
</code></pre>
<ul>
<li><a href="https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev23-4-0" rel="nofollow noreferrer">latest support-v4 version: 23.4.0</a></li>
</ul>
<h3>Update August 2015, Play Services 7.8.0</h3>
<p><a href="https://developers.google.com/android/guides/releases#august_2015_-_version_78" rel="nofollow noreferrer">Google Play Services Release Notes</a>,
<a href="https://developers.google.com/maps/documentation/android-api/releases" rel="nofollow noreferrer">Google Maps APIs Release Notes</a></p>
<p><strong>support-v4 dependency</strong></p>
<pre><code>com.google.android.gms:play-services-base:7.8.0
-> com.android.support:support-v4:22.2.0 -> 22.2.1
</code></pre>
<ul>
<li><a href="https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev22-2-1" rel="nofollow noreferrer">latest support-v4 version: 22.2.1</a></li>
</ul>
<h3>Original answer</h3>
<p>They have just been released (see the <a href="https://developer.android.com/google/play-services/index.html#newfeatures" rel="nofollow noreferrer">highlights</a>). You can find more information on how to use the granular dependencies <a href="https://developer.android.com/google/play-services/setup.html#split" rel="nofollow noreferrer">here</a>.</p>
<p>You will need to update your local Google Play Services repository using the SDK Manager provided by the SDK or use a plugin like Jake Whartons <a href="https://github.com/JakeWharton/sdk-manager-plugin" rel="nofollow noreferrer">sdk-manager-plugin</a> for Gradle which will automatically update it for you. It would look like this when building with Gradle:</p>
<p><code>Google Play Services repository outdated. Downloading update...</code></p>
<h3>Edit 1</h3>
<p>As of writing, the second link seem to be corrupt, as in, even though <em>Using Android Studio</em> is selected in the drop down menu, it doesn't show the information, at least for me. In order to see the information for Android Studio, select <em>Using something else</em>, then select <em>Using Android Studio</em> again.</p>
<h3>Edit 2</h3>
<p><a href="https://developers.google.com/maps/documentation/android-api/releases" rel="nofollow noreferrer">Google Maps APIs Release Notes</a></p>
<pre><code>dependencies {
# Google+'
compile 'com.google.android.gms:play-services-plus:6.5.+'
# Google Account Login
compile 'com.google.android.gms:play-services-identity:6.5.+'
# Google Activity Recognition
compile 'com.google.android.gms:play-services-location:6.5.+'
# Google App Indexing
compile 'com.google.android.gms:play-services-appindexing:6.5.+'
# Google Cast
compile 'com.google.android.gms:play-services-cast:6.5.+'
# Google Drive
compile 'com.google.android.gms:play-services-drive:6.5.+'
# Google Fit
compile 'com.google.android.gms:play-services-fitness:6.5.+'
# Google Maps
compile 'com.google.android.gms:play-services-maps:6.5.+'
# Google Mobile Ads
compile 'com.google.android.gms:play-services-ads:6.5.+'
# Google Panorama Viewer
compile 'com.google.android.gms:play-services-panorama:6.5.+'
# Google Play Game services
compile 'com.google.android.gms:play-services-games:6.5.+'
# Google Wallet
compile 'com.google.android.gms:play-services-wallet:6.5.+'
# Android Wear
compile 'com.google.android.gms:play-services-wearable:6.5.+'
# Google Actions
# Google Analytics
# Google Cloud Messaging
compile 'com.google.android.gms:play-services-base:6.5.+'
}
</code></pre>
<p><strong>support-v4 dependency</strong></p>
<pre><code>com.google.android.gms:play-services-base:6.5.87
-> com.android.support:support-v4:21.0.0 -> 21.0.3
</code></pre>
<ul>
<li><a href="https://developer.android.com/topic/libraries/support-library/rev-archive.html#rev21-0-3" rel="nofollow noreferrer">latest support-v4 version: 21.0.3</a></li>
</ul>
<h3>Edit 3</h3>
<p>Google just made a blog post about <a href="http://android-developers.blogspot.co.at/2014/12/google-play-services-and-dex-method.html" rel="nofollow noreferrer">Google Play Services 6.5 and the 65k method limit</a>. It contains the information of my post and more. I'll just quote one paragraph for anyone who comes across this information via SO instead of the blog post:</p>
<blockquote>
<p><em>Note: At the time of writing, the correct version to use is 6.5.87. As this is a very granular number, it will get updated quite quickly, so be sure the check the latest version when you are coding. Often people will use a ‘+’ to denote versions, such as 6.5.+ to use the latest 6.5 build. However, it’s typically discouraged to use a ‘+’ as it can lead to inconsistencies.</em></p>
</blockquote> |
26,694,108 | What is the difference between compileSdkVersion and targetSdkVersion? | <p>I have looked at the <a href="http://developer.android.com/sdk/installing/studio-build.html#buildFileBasics" rel="noreferrer" title="documentation">documentation</a> for building with Gradle, but I'm still not sure what the difference between <code>compileSdkVersion</code> and <code>targetSdkVersion</code> is.</p>
<p>All it says is:</p>
<blockquote>
<p>The <code>compileSdkVersion</code> property specifies the compilation target.</p>
</blockquote>
<p>Well, what is the "compilation target"?</p>
<p>I see two possible ways to interpret this:</p>
<ol>
<li><code>compileSdkVersion</code> is the version of the compiler used in building the app, while <code>targetSdkVersion</code> is the <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html" rel="noreferrer">"API level that the application targets"</a>. (If this were the case, I'd assume <code>compileSdkVersion</code> must be greater than or equal to the <code>targetSdkVersion</code>?</li>
<li>They mean the same thing. "compilation target" == "the API level that the application targets"</li>
<li>Something else?</li>
</ol>
<p>I see that <a href="https://stackoverflow.com/questions/24510219/android-studio-min-skd-version-target-sdk-version-vs-compile-sdk-version" title="this question">this question</a> has been asked before, but the one answer just quotes the doc, which is what is unclear to me.</p> | 26,694,276 | 11 | 2 | null | 2014-11-01 22:54:26.653 UTC | 188 | 2021-03-31 19:19:43.747 UTC | 2017-05-23 11:47:35.397 UTC | null | -1 | null | 3,761,530 | null | 1 | 660 | android|sdk|android-gradle-plugin|android-build | 272,599 | <h3>compileSdkVersion</h3>
<p>The <code>compileSdkVersion</code> is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set <code>compileSdkVersion</code> to 15, you will get a compilation error. If you set <code>compileSdkVersion</code> to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.</p>
<h3>targetSdkVersion</h3>
<p>The <code>targetSdkVersion</code> has nothing to do with how your app is compiled or what APIs you can utilize. The <code>targetSdkVersion</code> is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.</p>
<p>For example, as <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html">the documentation</a> states:</p>
<blockquote>
<p>For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...</p>
</blockquote>
<p>The Android OS, <strong>at runtime</strong>, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.</p>
<p>For all practical purposes, most apps are going to want to set <code>targetSdkVersion</code> to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the <code>targetSdkVersion</code>, it defaults to the <code>minSdkVersion</code>.</p> |
19,535,147 | Await and SynchronizationContext in a managed component hosted by an unmanaged app | <p><strong>[EDITED]</strong> <em><a href="https://stackoverflow.com/a/19555959/1768303">This appears to be a bug</a> in the Framework's implementation of <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx" rel="noreferrer">Application.DoEvents</a>, which I've reported <a href="https://connect.microsoft.com/VisualStudio/feedback/details/806432/application-doevents-resets-the-threads-current-synchronization-context" rel="noreferrer">here</a>. Restoring a wrong synchronization context on a UI thread may seriously affect component developers like me. The goal of the bounty is to draw more attention to this problem and to reward @MattSmith whose answer helped tracking it down.</em></p>
<p>I'm responsible for a .NET WinForms <code>UserControl</code>-based component exposed as ActiveX to <strong>a legacy unmanaged app</strong>, via COM interop. The runtime requirement is .NET 4.0 + Microsoft.Bcl.Async.</p>
<p>The component gets instantiated and used on the app's main STA UI thread. Its implementation utilizes <code>async/await</code>, so it expects that an instance of a serializing synchronization context has been installed on the current thread (i. e.,<code>WindowsFormsSynchronizationContext</code>). </p>
<p>Usually, <code>WindowsFormsSynchronizationContext</code> gets set up by <code>Application.Run</code>, which is where the message loop of a managed app runs. Naturally, <strong>this is not the case for the unmanaged host app</strong>, and I have no control over this. Of course, the host app still has its own classic Windows message loop, so it should not be a problem to serialize <code>await</code> continuation callbacks.</p>
<p>However, none of the solutions I've come up with so far is perfect, or even works properly. Here's an artificial example, where <code>Test</code> method is invoked by the host app:</p>
<pre><code>Task testTask;
public void Test()
{
this.testTask = TestAsync();
}
async Task TestAsync()
{
Debug.Print("thread before await: {0}", Thread.CurrentThread.ManagedThreadId);
var ctx1 = SynchronizationContext.Current;
Debug.Print("ctx1: {0}", ctx1 != null? ctx1.GetType().Name: null);
if (!(ctx1 is WindowsFormsSynchronizationContext))
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
var ctx2 = SynchronizationContext.Current;
Debug.Print("ctx2: {0}", ctx2.GetType().Name);
await TaskEx.Delay(1000);
Debug.WriteLine("thread after await: {0}", Thread.CurrentThread.ManagedThreadId);
var ctx3 = SynchronizationContext.Current;
Debug.Print("ctx3: {0}", ctx3 != null? ctx3.GetType().Name: null);
Debug.Print("ctx3 == ctx1: {0}, ctx3 == ctx2: {1}", ctx3 == ctx1, ctx3 == ctx2);
}
</code></pre>
<p>Debug output:</p>
<pre>
thread before await: 1
ctx1: SynchronizationContext
ctx2: WindowsFormsSynchronizationContext
thread after await: 1
ctx3: SynchronizationContext
ctx3 == ctx1: True, ctx3 == ctx2: False
</pre>
<p>Although it continues on the same thread, the <code>WindowsFormsSynchronizationContext</code> context I'm installing on the current thread before <code>await</code> <strong>gets reset to the default <code>SynchronizationContext</code></strong> after it, for some reason.</p>
<p><strong>Why does it get reset?</strong> I've verified my component is the only .NET component being used by that app. The app itself does call <code>CoInitialize/OleInitialize</code> properly.</p>
<p>I've also tried <strong>setting up <code>WindowsFormsSynchronizationContext</code> in the constructor of a static singleton object</strong>, so it gets installed on the thread when my managed assembly gets loaded. That didn't help: when <code>Test</code> is later invoked on the same thread, the context has been already reset to the default one.</p>
<p>I'm considering using a <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx" rel="noreferrer">custom awaiter</a> to schedule <code>await</code> callbacks via <code>control.BeginInvoke</code> of my control, so the above would look like <code>await TaskEx.Delay().WithContext(control)</code>. That should work for my own <code>awaits</code>, as long as the host app keeps pumping messages, but not for <code>awaits</code> inside any of the 3rd party assemblies my assembly may be referencing. </p>
<p>I'm still researching this. <strong>Any ideas on how to keep the correct thread affinity for <code>await</code> in this scenario would be appreciated.</strong> </p> | 19,555,959 | 2 | 5 | null | 2013-10-23 07:12:18.947 UTC | 9 | 2014-01-20 21:27:25.627 UTC | 2017-05-23 10:29:24.52 UTC | null | -1 | null | 1,768,303 | null | 1 | 19 | c#|.net|asynchronous|async-await|com-interop | 2,975 | <p>This is going to be a bit long. First of all, thanks <strong>Matt Smith</strong> and <strong>Hans Passant</strong> for your ideas, they have been very helpful.</p>
<p>The problem was caused by a good old friend, <code>Application.DoEvents</code>, although in a novelty way. Hans has <a href="https://stackoverflow.com/a/5183623/1768303">an excellent post</a> about why <code>DoEvents</code> is an evil. Unfortunately, I'm unable to avoid using <code>DoEvents</code> in this control, because of the synchronous API restrictions posed by the legacy unmanaged host app (more about it at the end). <strong>I'm well aware of the existing implications of <code>DoEvents</code>, but here I believe we have a new one:</strong> </p>
<p><em>On a thread without explicit WinForms message loop (i.e., any thread which hasn't entered <code>Application.Run</code> or <code>Form.ShowDialog</code>), calling <code>Application.DoEvents</code> will replace the current synchronization context with the default <code>SynchronizationContext</code>, provided <code>WindowsFormsSynchronizationContext.AutoInstall</code> is <code>true</code> (which is so by default).</em></p>
<p>If it is not a bug, then it's a very unpleasant undocumented behavior which may seriously affect some component developers.</p>
<p>Here is a simple console STA app reproducing the problem. <strong>Note how <code>WindowsFormsSynchronizationContext</code> gets (incorrectly) replaced with <code>SynchronizationContext</code> in the first pass of <code>Test</code> and does not in the second pass.</strong></p>
<pre><code>using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication
{
class Program
{
[STAThreadAttribute]
static void Main(string[] args)
{
Debug.Print("ApartmentState: {0}", Thread.CurrentThread.ApartmentState.ToString());
Debug.Print("*** Test 1 ***");
Test();
SynchronizationContext.SetSynchronizationContext(null);
WindowsFormsSynchronizationContext.AutoInstall = false;
Debug.Print("*** Test 2 ***");
Test();
}
static void DumpSyncContext(string id, string message, object ctx)
{
Debug.Print("{0}: {1} ({2})", id, ctx != null ? ctx.GetType().Name : "null", message);
}
static void Test()
{
Debug.Print("WindowsFormsSynchronizationContext.AutoInstall: {0}", WindowsFormsSynchronizationContext.AutoInstall);
var ctx1 = SynchronizationContext.Current;
DumpSyncContext("ctx1", "before setting up the context", ctx1);
if (!(ctx1 is WindowsFormsSynchronizationContext))
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
var ctx2 = SynchronizationContext.Current;
DumpSyncContext("ctx2", "before Application.DoEvents", ctx2);
Application.DoEvents();
var ctx3 = SynchronizationContext.Current;
DumpSyncContext("ctx3", "after Application.DoEvents", ctx3);
Debug.Print("ctx3 == ctx1: {0}, ctx3 == ctx2: {1}", ctx3 == ctx1, ctx3 == ctx2);
}
}
}
</code></pre>
<p><strong>Debug output:</strong></p>
<pre>
ApartmentState: STA
*** Test 1 ***
WindowsFormsSynchronizationContext.AutoInstall: True
ctx1: null (before setting up the context)
ctx2: WindowsFormsSynchronizationContext (before Application.DoEvents)
ctx3: SynchronizationContext (after Application.DoEvents)
ctx3 == ctx1: False, ctx3 == ctx2: False
*** Test 2 ***
WindowsFormsSynchronizationContext.AutoInstall: False
ctx1: null (before setting up the context)
ctx2: WindowsFormsSynchronizationContext (before Application.DoEvents)
ctx3: WindowsFormsSynchronizationContext (after Application.DoEvents)
ctx3 == ctx1: False, ctx3 == ctx2: True
</pre>
<p>It took some investigation of the Framework's implementation of <code>Application.ThreadContext.RunMessageLoopInner</code> and <code>WindowsFormsSynchronizationContext.InstalIifNeeded</code>/<code>Uninstall</code> to understand why exactly it happens. The condition is that the thread doesn't currently execute an <code>Application</code> message loop, as mentioned above. The relevant piece from <code>RunMessageLoopInner</code>:</p>
<pre><code>if (this.messageLoopCount == 1)
{
WindowsFormsSynchronizationContext.InstallIfNeeded();
}
</code></pre>
<p>Then the code inside <code>WindowsFormsSynchronizationContext.InstallIfNeeded</code>/<code>Uninstall</code> pair of methods <strong>doesn't save/restore the thread's existing synchronization context</strong> correctly. At this point, I'm not sure if it's a bug or a design feature.</p>
<p><strong>The solution is to disable <code>WindowsFormsSynchronizationContext.AutoInstall</code></strong>, as simple as this:</p>
<pre><code>struct SyncContextSetup
{
public SyncContextSetup(bool autoInstall)
{
WindowsFormsSynchronizationContext.AutoInstall = autoInstall;
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
}
}
static readonly SyncContextSetup _syncContextSetup =
new SyncContextSetup(autoInstall: false);
</code></pre>
<p><strong>A few words about why I use <code>Application.DoEvents</code> in the first place here.</strong> It's a typical asynchronous-to-synchronous bridge code running on the UI thread, using a nested message loop. This is a bad practice, but the legacy host app expects all APIs to complete synchronously. The original problem is described <a href="https://stackoverflow.com/q/18050438/1768303">here</a>. At some later point, I replaced <code>CoWaitForMultipleHandles</code> with a combination of <code>Application.DoEvents</code>/<code>MsgWaitForMultipleObjects</code>, which now looks like this:</p>
<p><strong>[EDITED]</strong> The most recent version of <code>WaitWithDoEvents</code> is <a href="https://stackoverflow.com/q/20876645/1768303">here</a>. <strong>[/EDITED]</strong></p>
<p>The idea was to dispatch messages using .NET standard mechanism, rather than relying upon <code>CoWaitForMultipleHandles</code> to do so. That's when I implicitly introduced the problem with the synchronization context, due to the described behavior of <code>DoEvents</code>.</p>
<p>The legacy app is currently being rewritten using modern technologies, and so is the control. The current implementation is aimed for existing customers with Windows XP who cannot upgrade for reasons beyond our control.</p>
<p><strong>Finally, here's the implementation of the custom awaiter</strong> which I mentioned in my question as an option to mitigate the problem. It was an interesting experience and it works, but <strong>it cannot be considered a proper solution</strong>.</p>
<pre><code>/// <summary>
/// AwaitHelpers - custom awaiters
/// WithContext continues on the control's thread after await
/// E.g.: await TaskEx.Delay(1000).WithContext(this)
/// </summary>
public static class AwaitHelpers
{
public static ContextAwaiter<T> WithContext<T>(this Task<T> task, Control control, bool alwaysAsync = false)
{
return new ContextAwaiter<T>(task, control, alwaysAsync);
}
// ContextAwaiter<T>
public class ContextAwaiter<T> : INotifyCompletion
{
readonly Control _control;
readonly TaskAwaiter<T> _awaiter;
readonly bool _alwaysAsync;
public ContextAwaiter(Task<T> task, Control control, bool alwaysAsync)
{
_awaiter = task.GetAwaiter();
_control = control;
_alwaysAsync = alwaysAsync;
}
public ContextAwaiter<T> GetAwaiter() { return this; }
public bool IsCompleted { get { return !_alwaysAsync && _awaiter.IsCompleted; } }
public void OnCompleted(Action continuation)
{
if (_alwaysAsync || _control.InvokeRequired)
{
Action<Action> callback = (c) => _awaiter.OnCompleted(c);
_control.BeginInvoke(callback, continuation);
}
else
_awaiter.OnCompleted(continuation);
}
public T GetResult()
{
return _awaiter.GetResult();
}
}
}
</code></pre> |
21,813,723 | Change and transition dataset in chord diagram with D3 | <p>I'm working on a chord diagram using D3.</p>
<p>I am trying to make it so that when a user clicks on a link the dataset will change to another predefined dataset. I've looked at both <a href="http://exposedata.com/tutorial/chord/latest.html">http://exposedata.com/tutorial/chord/latest.html</a> and <a href="http://fleetinbeing.net/d3e/chord.html">http://fleetinbeing.net/d3e/chord.html</a>, and have tried to use some elements in there to get it to work.</p>
<p>Here is the JavaScript to create the "default" diagram:</p>
<pre><code>var dataset = "data/all_trips.json";
var width = 650,
height = 600,
outerRadius = Math.min(width, height) / 2 - 25,
innerRadius = outerRadius - 18;
var formatPercent = d3.format("%");
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var layout = d3.layout.chord()
.padding(.03)
.sortSubgroups(d3.descending)
.sortChords(d3.ascending);
var path = d3.svg.chord()
.radius(innerRadius);
var svg = d3.select("#chart_placeholder").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 1.5 + "," + height / 1.75 + ")");
svg.append("circle")
.attr("r", outerRadius);
d3.csv("data/neighborhoods.csv", function(neighborhoods) {
d3.json(dataset, function(matrix) {
// Compute chord layout.
layout.matrix(matrix);
// Add a group per neighborhood.
var group = svg.selectAll(".group")
.data(layout.groups)
.enter().append("g")
.attr("class", "group")
.on("mouseover", mouseover);
// Add a mouseover title.
group.append("title").text(function(d, i) {
return numberWithCommas(d.value) + " trips started in " + neighborhoods[i].name;
});
// Add the group arc.
var groupPath = group.append("path")
.attr("id", function(d, i) { return "group" + i; })
.attr("d", arc)
.style("fill", function(d, i) { return neighborhoods[i].color; });
var rootGroup = d3.layout.chord().groups()[0];
// Text label radiating outward from the group.
var groupText = group.append("text");
group.append("svg:text")
.each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })
.attr("xlink:href", function(d, i) { return "#group" + i; })
.attr("dy", ".35em")
.attr("color", "#fff")
.attr("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" +
" translate(" + (innerRadius + 26) + ")" +
(d.angle > Math.PI ? "rotate(180)" : "");
})
.text(function(d, i) { return neighborhoods[i].name; });
// Add the chords.
var chord = svg.selectAll(".chord")
.data(layout.chords)
.enter().append("path")
.attr("class", "chord")
.style("fill", function(d) { return neighborhoods[d.source.index].color; })
.attr("d", path);
// Add mouseover for each chord.
chord.append("title").text(function(d) {
if (!(neighborhoods[d.target.index].name === neighborhoods[d.source.index].name)) {
return numberWithCommas(d.source.value) + " trips from " + neighborhoods[d.source.index].name + " to " + neighborhoods[d.target.index].name + "\n" +
numberWithCommas(d.target.value) + " trips from " + neighborhoods[d.target.index].name + " to " + neighborhoods[d.source.index].name;
} else {
return numberWithCommas(d.source.value) + " trips started and ended in " + neighborhoods[d.source.index].name;
}
});
function mouseover(d, i) {
chord.classed("fade", function(p) {
return p.source.index != i
&& p.target.index != i;
});
var selectedOrigin = d.value;
var selectedOriginName = neighborhoods[i].name;
}
});
});
</code></pre>
<p>And here's what I'm trying to do to make it re-render the chart with the new data (there is an image element with the <code>id</code> "female".</p>
<pre><code>d3.select("#female").on("click", function () {
var new_data = "data/women_trips.json";
reRender(new_data);
});
function reRender(data) {
var layout = d3.layout.chord()
.padding(.03)
.sortSubgroups(d3.descending)
.matrix(data);
// Update arcs
svg.selectAll(".group")
.data(layout.groups)
.transition()
.duration(1500)
.attrTween("d", arcTween(last_chord));
// Update chords
svg.select(".chord")
.selectAll("path")
.data(layout.chords)
.transition()
.duration(1500)
.attrTween("d", chordTween(last_chord))
};
var arc = d3.svg.arc()
.startAngle(function(d) { return d.startAngle })
.endAngle(function(d) { return d.endAngle })
.innerRadius(r0)
.outerRadius(r1);
var chordl = d3.svg.chord().radius(r0);
function arcTween(layout) {
return function(d,i) {
var i = d3.interpolate(layout.groups()[i], d);
return function(t) {
return arc(i(t));
}
}
}
function chordTween(layout) {
return function(d,i) {
var i = d3.interpolate(layout.chords()[i], d);
return function(t) {
return chordl(i(t));
}
}
}
</code></pre> | 21,923,560 | 1 | 10 | null | 2014-02-16 16:08:21.633 UTC | 12 | 2014-04-12 15:14:08.987 UTC | 2014-04-12 15:14:08.987 UTC | null | 3,052,751 | null | 2,497,825 | null | 1 | 19 | javascript|d3.js|transition|chord-diagram | 10,523 | <h1>Creating a chord diagram</h1>
<p>There are a number of layers to creating a <a href="http://bl.ocks.org/mbostock/4062006" rel="noreferrer">chord diagram</a> with d3, corresponding to d3's careful separation of <em>data manipulation</em> from <em>data visualization</em>. If you're going to not only create a chord diagram, but also update it smoothly, you'll need to clearly understand what each piece of the program does and how they interact.</p>
<p><img src="https://d3js.org/ex/chord.png" alt="Sample Chord Diagram, from the example linked above" title="Sample Chord Diagram, from the example linked above"></p>
<p><strong>First, the data-manipulation aspect.</strong> The d3 <a href="https://github.com/mbostock/d3/wiki/Chord-Layout" rel="noreferrer">Chord Layout tool</a> takes your data about the interactions between different groups and creates a set of data objects which contain the original data but are also assigned angle measurements . In this way, it is similar to the <a href="https://github.com/mbostock/d3/wiki/Pie-Layout" rel="noreferrer">pie layout tool</a>, but there are some important differences related to the increased complexity of the chord layout.</p>
<p>Like the other d3 layout tools, you create a chord layout object by calling a function (<code>d3.layout.chord()</code>), and then you call additional methods on the layout object to change the default settings. Unlike the pie layout tool and most of the other layouts, however, the chord layout object isn't a function that takes your data as input and outputs the calculated array of data objects with layout attributes (angles) set. </p>
<p>Instead, your data is another setting for the layout, which you define with the <a href="https://github.com/mbostock/d3/wiki/Chord-Layout#wiki-matrix" rel="noreferrer"><code>.matrix()</code></a> method, and which is stored within the layout object. The data has to be stored within the object because there are <em>two different</em> arrays of data objects with layout attributes, one for the chords (connections between different groups), and one for the groups themselves. The fact that the layout object stores the data is important when dealing with updates, as you have to be careful not to over-write old data with new if you still need the old data for transitions.</p>
<pre><code>var chordLayout = d3.layout.chord() //create layout object
.sortChords( d3.ascending ) //set a property
.padding( 0.01 ); //property-setting methods can be chained
chordLayout.matrix( data ); //set the data matrix
</code></pre>
<p>The group data objects are accessed by calling <code>.groups()</code> on the chord layout after the data matrix has been set. Each group is equivalent to a row in your data matrix (i.e., each subarray in an array of arrays). The group data objects have been assigned start angle and end angle values representing a section of the circle. This much is just like a pie graph, with the difference being that the values for each group (and for the circle as a whole) are calculated by summing up values for the entire row (subarray). The group data objects <a href="https://github.com/mbostock/d3/wiki/Chord-Layout#wiki-groups" rel="noreferrer">also have properties</a> representing their index in the original matrix (important because they might be sorted into a different order) and their total value.</p>
<p>The chord data objects are accessed by calling <code>.chords()</code> on the chord layout after the data matrix has been set. Each chord represents <em>two</em> values in the data matrix, equivalent to the two possible relationships between two groups. For example, in @latortue09's example, the relationships are bicycle trips between neighbourhoods, so the chord that represents trips between Neighbourhood A and Neighbourhood B represents the number of trips from A to B as well as the number from B to A. If Neighbourhood A is in row <code>a</code> of your data matrix and Neighbourhood B is in row <code>b</code>, then these values should be at <code>data[a][b]</code> and <code>data[b][a]</code>, respectively. (Of course, sometimes the relationships you're drawing won't have this type of direction to them, in which case your data matrix should be <em>symmetric</em>, meaning that those two values should be equal.) </p>
<p>Each chord data object has two properties, <code>source</code> and <code>target</code>, each of which is its own data object. Both the source and target data object <a href="https://github.com/mbostock/d3/wiki/Chord-Layout#wiki-chords" rel="noreferrer">have the same structure</a> with information about the <em>one-way</em> relationship from one group to the other, including the original indexes of the groups and the value of that relationship, and start and end angles representing a section of one group's segment of the circle.</p>
<p>The source/target naming is kind of confusing, since as I mentioned above, the chord object represents <em>both</em> directions of the relationship between two groups. The direction that has the larger value determines which group is called <code>source</code> and which is called <code>target</code>. So if there are 200 trips from Neighbourhood A to Neighbourhood B, but 500 trips from B to A, then the <code>source</code> for that chord object will represent a section of Neighbourhood B's segment of the circle, and the <code>target</code> will represent part of Neighbourhood A's segment of the circle. For the relationship between a group and itself (in this example, trips that start and end in the same neighbourhood), the source and target objects are the same. </p>
<p>One final important aspect of the chord data object array is that it only contains objects where relationships between two groups exist. If there are no trips between Neighbourhood A and Neighbourhood B in either direction, then there will be no chord data object for those groups. This becomes important when updating from one dataset to another. </p>
<p><strong>Second, the data-visualization aspect.</strong> The Chord Layout tool creates arrays of data objects, converting information from the data matrix into angles of a circle. But it doesn't draw anything. To create the standard SVG representation of a chord diagram, you use <a href="http://bost.ocks.org/mike/selection/" rel="noreferrer">d3 selections</a> to create elements joined to an array of layout data objects. Because there are two different arrays of layout data objects in the chord diagram, one for the chords and one for the groups, there are two different d3 selections.</p>
<p>In the simplest case, both selections would contain <code><path></code> elements (and the two types of paths would be distinguished by class). The <code><path></code>s that are joined to the data array for the chord diagram groups become the arcs around the outside of the circle, while the <code><path></code>s that are joined to the data for the chords themselves become the bands across the circle.</p>
<p>The shape of a <code><path></code> is determined by its <a href="http://codepen.io/AmeliaBR/full/pIder" rel="noreferrer"><code>"d"</code> (path data or directions)</a> attribute. D3 has a variety of <a href="https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-path-data-generators" rel="noreferrer">path data generators</a>, which are functions that take a data object and create a string that can be used for a path's <code>"d"</code> attribute. Each path generator is created by calling a d3 method, and each can be modified by calling it's own methods. </p>
<p>The groups in a standard chord diagram are drawn using the <a href="https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-arc" rel="noreferrer"><code>d3.svg.arc()</code> path data generator</a>. This arc generator is the same one used by pie and donut graphs. After all, if you remove the chords from a chord diagram, you essentially just have a donut diagram made up of the group arcs. The default arc generator expects to be passed data objects with <code>startAngle</code> and <code>endAngle</code> properties; the group data objects created by the chord layout works with this default. The arc generator also needs to know the inside and outside radius for the arc. These can be specified as functions of the data or as constants; for the chord diagram they will be constants, the same for every arc.</p>
<pre><code>var arcFunction = d3.svg.arc() //create the arc path generator
//with default angle accessors
.innerRadius( radius )
.outerRadius( radius + bandWidth);
//set constant radius values
var groupPaths = d3.selectAll("path.group")
.data( chordLayout.groups() );
//join the selection to the appropriate data object array
//from the chord layout
groupPaths.enter().append("path") //create paths if this isn't an update
.attr("class", "group"); //set the class
/* also set any other attributes that are independent of the data */
groupPaths.attr("fill", groupColourFunction )
//set attributes that are functions of the data
.attr("d", arcFunction ); //create the shape
//d3 will pass the data object for each path to the arcFunction
//which will create the string for the path "d" attribute
</code></pre>
<p>The chords in a chord diagram have a shape unique to this type of diagram. Their shapes are defined using the <a href="https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-chord" rel="noreferrer"><code>d3.svg.chord()</code> path data generator</a>. The default chord generator expects data of the form created by the chord layout object, the only thing that needs to be specified is the radius of the circle (which will usually be the same as the inner radius of the arc groups).</p>
<pre><code>var chordFunction = d3.svg.chord() //create the chord path generator
//with default accessors
.radius( radius ); //set constant radius
var chordPaths = d3.selectAll("path.chord")
.data( chordLayout.chords() );
//join the selection to the appropriate data object array
//from the chord layout
chordPaths.enter().append("path") //create paths if this isn't an update
.attr("class", "chord"); //set the class
/* also set any other attributes that are independent of the data */
chordPaths.attr("fill", chordColourFunction )
//set attributes that are functions of the data
.attr("d", chordFunction ); //create the shape
//d3 will pass the data object for each path to the chordFunction
//which will create the string for the path "d" attribute
</code></pre>
<p>That's the simple case, with <code><path></code> elements only. If you want to also have text labels associated with your groups or chords, then your data is joined to <code><g></code> elements, and the <code><path></code> elements and the <code><text></code> elements for the labels (and any other elements, like the tick mark lines in the hair-colour example) are children of the that inherit it's data object. When you update the graph, you'll need to update all the sub-components that are affected by the data. </p>
<h1>Updating a chord diagram</h1>
<p>With all that information in mind, how should you approach creating a chord diagram that can be updated with new data?</p>
<p>First, to minimize the total amount of code, I usually recommend making your <em>update</em> method double as your <em>initialization</em> method. Yes, you'll still need some initialization steps for things that never change in the update, but for actually drawing the shapes that are based on the data you should only need one function regardless of whether this is an update or a new visualization.</p>
<p>For this example, the initialization steps will include creating the <code><svg></code> and the centered <code><g></code> element, as well as reading in the array of information about the different neighbourhoods. Then the initialization method will call the update method with a default data matrix. The buttons that switch to a different data matrix will call the same method.</p>
<pre><code>/*** Initialize the visualization ***/
var g = d3.select("#chart_placeholder").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform",
"translate(" + width / 2 + "," + height / 2 + ")");
//the entire graphic will be drawn within this <g> element,
//so all coordinates will be relative to the center of the circle
g.append("circle")
.attr("r", outerRadius);
d3.csv("data/neighborhoods.csv", function(error, neighborhoodData) {
if (error) {alert("Error reading file: ", error.statusText); return; }
neighborhoods = neighborhoodData;
//store in variable accessible by other functions
updateChords(dataset);
//call the update method with the default dataset url
} ); //end of d3.csv function
/* example of an update trigger */
d3.select("#MenOnlyButton").on("click", function() {
updateChords( "/data/men_trips.json" );
disableButton(this);
});
</code></pre>
<p>I'm just passing a data url to the update function, which means that the first line of that function will be a data-parsing function call. The resulting data matrix is used as the matrix for a <em>new</em> data layout object. We need a new layout object in order to keep a copy of the old layout for the transition functions. (If you weren't going to transition the changes, you could just call the <code>matrix</code> method on the same layout to create the new one.) To minimize code duplication, I use a function to create the new layout object and to set all its options:</p>
<pre><code>/* Create OR update a chord layout from a data matrix */
function updateChords( datasetURL ) {
d3.json(datasetURL, function(error, matrix) {
if (error) {alert("Error reading file: ", error.statusText); return; }
/* Compute chord layout. */
layout = getDefaultLayout(); //create a new layout object
layout.matrix(matrix);
/* main part of update method goes here */
}); //end of d3.json
}
</code></pre>
<p>Then on to the main part of the update-or-create drawing funcion: you're going to need to break down all your <a href="https://stackoverflow.com/a/20754006/3128209">method chains into four parts</a> for data join, enter, exit and update. This way, you can handle the creation new elements during an update (e.g., new chords for groups that didn't have a relationship in the previous data set) with the same code that you use to handle the original creation of the visualization. </p>
<p><strong>First, the data join chain.</strong> One for the groups and one for the chords.<br>
To maintain <a href="http://bost.ocks.org/mike/constancy/" rel="noreferrer">object constancy</a> through transitions -- and to reduce the number of graphical properties you have to set on update -- you'll want to set a key function within your data join. By default, d3 matches data to elements within a selection based only on their order in the page/array. Because our chord layout's <code>.chords()</code> array doesn't include chords were there is zero relationship in this data set, the order of the chords can be inconsistent between update rounds. The <code>.groups()</code> array could also be re-sorted into orders that don't match the original data matrix, so we also add a key function for that to be safe. In both cases, the key functions are based on the <code>.index</code> properties that the chord layout stored in the data objects.</p>
<pre><code>/* Create/update "group" elements */
var groupG = g.selectAll("g.group")
.data(layout.groups(), function (d) {
return d.index;
//use a key function in case the
//groups are sorted differently between updates
});
/* Create/update the chord paths */
var chordPaths = g.selectAll("path.chord")
.data(layout.chords(), chordKey );
//specify a key function to match chords
//between updates
/* Elsewhere, chordKey is defined as: */
function chordKey(data) {
return (data.source.index < data.target.index) ?
data.source.index + "-" + data.target.index:
data.target.index + "-" + data.source.index;
//create a key that will represent the relationship
//between these two groups *regardless*
//of which group is called 'source' and which 'target'
}
</code></pre>
<p>Note that the chords are <code><path></code> elements, but the groups are <code><g></code> elements, which will contain both a <code><path></code> and a <code><text></code>.</p>
<p>The variables created in this step are data-join selections; they will contain all the existing elements (if any) that matched the selector <em>and</em> matched a data value, and they will contain null pointers for any data values which did not match an existing element. They also have the <code>.enter()</code> and <code>.exit()</code> methods to access those chains.</p>
<p><strong>Second, the enter chain.</strong> For all the data objects which didn't match an element (which is all of them if this is the first time the visualization is drawn), we need to create the element and its child components. At this time, you want to also set any attributes that are constant for all elements (regardless of the data), or which are based on the data values that you use in the key function, and therefore won't change on update.</p>
<pre><code>var newGroups = groupG.enter().append("g")
.attr("class", "group");
//the enter selection is stored in a variable so we can
//enter the <path>, <text>, and <title> elements as well
//Create the title tooltip for the new groups
newGroups.append("title");
//create the arc paths and set the constant attributes
//(those based on the group index, not on the value)
newGroups.append("path")
.attr("id", function (d) {
return "group" + d.index;
//using d.index and not i to maintain consistency
//even if groups are sorted
})
.style("fill", function (d) {
return neighborhoods[d.index].color;
});
//create the group labels
newGroups.append("svg:text")
.attr("dy", ".35em")
.attr("color", "#fff")
.text(function (d) {
return neighborhoods[d.index].name;
});
//create the new chord paths
var newChords = chordPaths.enter()
.append("path")
.attr("class", "chord");
// Add title tooltip for each new chord.
newChords.append("title");
</code></pre>
<p>Note that the fill colours for the group arcs is set on enter, but not the fill colours for the chords. That's because the chord colour is going to change depending on which group (of the two the chord connects) is called 'source' and which is 'target', i.e., depending on which direction of the relationship is stronger (has more trips).</p>
<p><strong>Third, the update chain.</strong> When you append an element to an <code>.enter()</code> selection, that new element replaces the null place holder in the original data-join selection. After that, if you manipulate the original selection, the settings get applied to both the new and the updating elements. So this is where you set any properties that depend on the data.</p>
<pre><code>//Update the (tooltip) title text based on the data
groupG.select("title")
.text(function(d, i) {
return numberWithCommas(d.value)
+ " trips started in "
+ neighborhoods[i].name;
});
//update the paths to match the layout
groupG.select("path")
.transition()
.duration(1500)
.attr("opacity", 0.5) //optional, just to observe the transition
.attrTween("d", arcTween( last_layout ) )
.transition().duration(10).attr("opacity", 1) //reset opacity
;
//position group labels to match layout
groupG.select("text")
.transition()
.duration(1500)
.attr("transform", function(d) {
d.angle = (d.startAngle + d.endAngle) / 2;
//store the midpoint angle in the data object
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" +
" translate(" + (innerRadius + 26) + ")" +
(d.angle > Math.PI ? " rotate(180)" : " rotate(0)");
//include the rotate zero so that transforms can be interpolated
})
.attr("text-anchor", function (d) {
return d.angle > Math.PI ? "end" : "begin";
});
// Update all chord title texts
chordPaths.select("title")
.text(function(d) {
if (neighborhoods[d.target.index].name !==
neighborhoods[d.source.index].name) {
return [numberWithCommas(d.source.value),
" trips from ",
neighborhoods[d.source.index].name,
" to ",
neighborhoods[d.target.index].name,
"\n",
numberWithCommas(d.target.value),
" trips from ",
neighborhoods[d.target.index].name,
" to ",
neighborhoods[d.source.index].name
].join("");
//joining an array of many strings is faster than
//repeated calls to the '+' operator,
//and makes for neater code!
}
else { //source and target are the same
return numberWithCommas(d.source.value)
+ " trips started and ended in "
+ neighborhoods[d.source.index].name;
}
});
//update the path shape
chordPaths.transition()
.duration(1500)
.attr("opacity", 0.5) //optional, just to observe the transition
.style("fill", function (d) {
return neighborhoods[d.source.index].color;
})
.attrTween("d", chordTween(last_layout))
.transition().duration(10).attr("opacity", 1) //reset opacity
;
//add the mouseover/fade out behaviour to the groups
//this is reset on every update, so it will use the latest
//chordPaths selection
groupG.on("mouseover", function(d) {
chordPaths.classed("fade", function (p) {
//returns true if *neither* the source or target of the chord
//matches the group that has been moused-over
return ((p.source.index != d.index) && (p.target.index != d.index));
});
});
//the "unfade" is handled with CSS :hover class on g#circle
//you could also do it using a mouseout event on the g#circle
</code></pre>
<p>The changes are done using <a href="http://bost.ocks.org/mike/transition/" rel="noreferrer">d3 transitions</a> to create a smooth shift from one diagram to another. For the changes to the path shapes, custom functions are used to do the transition while maintaining the overall shape. More about those below.</p>
<p><strong>Fourth, the exit() chain.</strong> If any elements from the previous diagram no longer have a match in the new data -- for example, if a chord doesn't exist because there are no relationships between those two groups (e.g., no trips between those two neighbourhoods) in this data set -- then you have to remove that element from the visualization. You can either remove them immediately, so they disappear to make room for transitioning data, or you can use a transition them out and then remove. (Calling <code>.remove()</code> on a transition-selection will remove the element when that transition completes.)</p>
<p>You could create a custom transition to make shapes shrink into nothing, but I just use a fade-out to zero opacity:</p>
<pre><code>//handle exiting groups, if any, and all their sub-components:
groupG.exit()
.transition()
.duration(1500)
.attr("opacity", 0)
.remove(); //remove after transitions are complete
//handle exiting paths:
chordPaths.exit().transition()
.duration(1500)
.attr("opacity", 0)
.remove();
</code></pre>
<p><strong>About the custom tween functions:</strong></p>
<p>If you just used a default tween to switch from one path shape to another, <a href="http://jsfiddle.net/KjrGF/11/" rel="noreferrer">the results can look kind of strange</a>. Try switching from "Men Only" to "Women Only" and you'll see that the chords get disconnected from the edge of the circle. If the arc positions had changed more significantly, you would see them crossing the circle to reach their new position instead of sliding around the ring.</p>
<p>That's because the default transition from one path shape to another just matches up points on the path and transitions each point in a straight line from one to the other. It works for any type of shape without any extra code, but it doesn't necessarily maintain that shape throughout the transition.</p>
<p>The custom tween function lets you define how the path should be shaped at every step of the transition. I've written up comments about tween functions <a href="https://stackoverflow.com/a/21569459/3128209">here</a> and <a href="https://stackoverflow.com/a/21228701/3128209">here</a>, so I'm not going to rehash it. But the short description is that the tween function you pass to <code>.attrTween(attribute, tween)</code> has to be a function that gets called once per element, and must itself return a function that will be called at every "tick" of the transition to return the attribute value at that point in the transition. </p>
<p>To get smooth transitions of path shapes, we use the two path data generator functions -- the arc generator and the chord generator -- to create the path data at each step of the transition. That way, the arcs will always look like arcs and the chords will always look like chords. The part that is <em>transitioning</em> is the start and end angle values. Given two different data objects that describe the same type of shape, but with different angle values, you can use <a href="https://github.com/mbostock/d3/wiki/Transitions#wiki-d3_interpolateObject" rel="noreferrer"><code>d3.interpolateObject(a,b)</code></a> to create a function that will give you an object at each stage of the transition that with appropriately transitioned angle properties. So if you have the data object from the old layout and the matching data object from the new layout, you can smoothly shift the arcs or chords from one position to the other.</p>
<p>However, what should you do if you don't have an old data object? Either because this chord didn't have a match in the old layout, or because this is the first time the visualization is drawn and there <em>is</em> no old layout. If you pass an empty object as the first parameter to <code>d3.interpolateObject</code>, the transitioned object will always be exactly the final value. In combination with other transitions, such as opacity, this could be acceptable. However, I decided to make the transition such that it starts with a zero-width shape -- that is, a shape where the start angles match the end angles -- and then expands to the final shape:</p>
<pre><code>function chordTween(oldLayout) {
//this function will be called once per update cycle
//Create a key:value version of the old layout's chords array
//so we can easily find the matching chord
//(which may not have a matching index)
var oldChords = {};
if (oldLayout) {
oldLayout.chords().forEach( function(chordData) {
oldChords[ chordKey(chordData) ] = chordData;
});
}
return function (d, i) {
//this function will be called for each active chord
var tween;
var old = oldChords[ chordKey(d) ];
if (old) {
//old is not undefined, i.e.
//there is a matching old chord value
//check whether source and target have been switched:
if (d.source.index != old.source.index ){
//swap source and target to match the new data
old = {
source: old.target,
target: old.source
};
}
tween = d3.interpolate(old, d);
}
else {
//create a zero-width chord object
var emptyChord = {
source: { startAngle: d.source.startAngle,
endAngle: d.source.startAngle},
target: { startAngle: d.target.startAngle,
endAngle: d.target.startAngle}
};
tween = d3.interpolate( emptyChord, d );
}
return function (t) {
//this function calculates the intermediary shapes
return path(tween(t));
};
};
}
</code></pre>
<p><em>(Check the fiddle for the arc tween code, which is slightly simpler)</em></p>
<p><strong>Live version altogether:</strong> <a href="http://jsfiddle.net/KjrGF/12/" rel="noreferrer">http://jsfiddle.net/KjrGF/12/</a></p> |
17,504,169 | How to get installed applications in Android and no system apps? | <p>I want to get all application which appears in the menu screen. But, now I only get the user installed apps or all the application (included the system application). </p>
<p>My current code is: </p>
<pre><code> final PackageManager pm = getActivity().getPackageManager();
List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_META_DATA);
ArrayList<PackageInfo> aux = new ArrayList<PackageInfo>();
for (int i = 0; i < apps.size(); i++) {
if (apps.get(i).versionName != null && ((apps.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 1)) {
aux.add(apps.get(i));
}
</code></pre>
<p>With this code, I can get the user installed apps, and if I comment the 'if' instruction, I will get the system apps. </p>
<p>So, I want to get the user installed apps and apps like contacts, gallery and so on.</p>
<p>UPDATE:</p>
<pre><code> final PackageManager pm = getActivity().getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
</code></pre> | 18,097,499 | 4 | 7 | null | 2013-07-06 15:07:37.933 UTC | 16 | 2017-11-22 06:42:18.177 UTC | 2013-07-06 15:34:45.433 UTC | null | 916,366 | null | 916,366 | null | 1 | 20 | android | 30,257 | <pre><code>final PackageManager pm = getActivity().getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
</code></pre> |
17,148,948 | "com.jcraft.jsch.JSchException: Auth fail" with working passwords | <p>While trying to upload the file to our server, i am getting the following exception</p>
<pre><code> com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:464)
at com.jcraft.jsch.Session.connect(Session.java:158)
at FtpService.transferFileToReciever(FtpService.java:80)
at FtpService.transferFileToReciever(FtpService.java:54)
at FtpService.transferFileToRecievers(FtpService.java:44)
at FtpService.transferSingeFile(FtpService.java:241)
at FtpService.main(FtpService.java:26)
Auth fail
</code></pre>
<p>The part of function transferFileToReciever from source file is </p>
<pre><code> JSch jsch = new JSch();
jsch.addIdentity("/root/.ssh/id_dsa");
Session session = jsch.getSession(username, host, 22);
session.setUserInfo(serverinfo);
session.connect(); //geting exception here
boolean ptimestamp = true;
</code></pre>
<p>The passwords are working, since i can do login using ssh, but using JSCh it doesnt work even provided with key, username and password.
Using id_dsa key with java version "1.6.0_25".
What could be the error?</p>
<p>Found other similar question, but not the answer.
Thanks in advance.</p> | 17,162,377 | 8 | 3 | null | 2013-06-17 13:39:07.07 UTC | 8 | 2022-04-14 12:40:29.427 UTC | null | null | null | null | 2,319,984 | null | 1 | 32 | java|jsch | 180,920 | <p>Tracing the root cause, i finally found that the public key of type dsa is not added to the authorized keys on remote server. Appending the same worked for me.</p>
<p>The ssh was working with rsa key, causing me to look back in my code.</p>
<p>thanks everyone.</p> |
17,481,672 | Fitting a Weibull distribution using Scipy | <p>I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate the Weibull distribution parameters for my data set.</p>
<p>I have tried this:</p>
<pre><code>import scipy.stats as s
import numpy as np
import matplotlib.pyplot as plt
def weib(x,n,a):
return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
data = np.loadtxt("stack_data.csv")
(loc, scale) = s.exponweib.fit_loc_scale(data, 1, 1)
print loc, scale
x = np.linspace(data.min(), data.max(), 1000)
plt.plot(x, weib(x, loc, scale))
plt.hist(data, data.max(), density=True)
plt.show()
</code></pre>
<p>And get this:</p>
<pre><code>(2.5827280639441961, 3.4955032285727947)
</code></pre>
<p>And a distribution that looks like this:</p>
<p><img src="https://i.stack.imgur.com/kkMR2m.jpg" alt="Weibull distribution using Scipy" /></p>
<p>I have been using the <code>exponweib</code> after reading this <a href="http://www.johndcook.com/distributions_scipy.html" rel="noreferrer">http://www.johndcook.com/distributions_scipy.html</a>. I have also tried the other Weibull functions in scipy (just in case!).</p>
<p>In Matlab (using the Distribution Fitting Tool - see screenshot) and in R (using both the MASS library function <code>fitdistr</code> and the GAMLSS package) I get a (loc) and b (scale) parameters more like 1.58463497 5.93030013. I believe all three methods use the maximum likelihood method for distribution fitting.</p>
<p><img src="https://i.stack.imgur.com/WtNWt.jpg" alt="Weibull distribution using Matlab" /></p>
<p>I have posted my data <a href="https://i.stack.imgur.com/kkMR2m.jpg" rel="noreferrer">here</a> if you would like to have a go! And for completeness I am using Python 2.7.5, Scipy 0.12.0, R 2.15.2 and Matlab 2012b.</p>
<p>Why am I getting a different result!?</p> | 17,498,673 | 8 | 5 | null | 2013-07-05 05:29:10.003 UTC | 26 | 2021-01-31 18:42:55.733 UTC | 2020-12-21 14:02:29.17 UTC | null | 1,650,778 | null | 1,414,831 | null | 1 | 50 | python|numpy|scipy|distribution|weibull | 80,876 | <p>My guess is that you want to estimate the shape parameter and the scale of the Weibull distribution while keeping the location fixed. Fixing <code>loc</code> assumes that the values of your data and of the distribution are positive with lower bound at zero. </p>
<p><code>floc=0</code> keeps the location fixed at zero, <code>f0=1</code> keeps the first shape parameter of the exponential weibull fixed at one.</p>
<pre><code>>>> stats.exponweib.fit(data, floc=0, f0=1)
[1, 1.8553346917584836, 0, 6.8820748596850905]
>>> stats.weibull_min.fit(data, floc=0)
[1.8553346917584836, 0, 6.8820748596850549]
</code></pre>
<p>The fit compared to the histogram looks ok, but not very good. The parameter estimates are a bit higher than the ones you mention are from R and matlab.</p>
<p><strong>Update</strong></p>
<p>The closest I can get to the plot that is now available is with unrestricted fit, but using starting values. The plot is still less peaked. Note values in fit that don't have an f in front are used as starting values.</p>
<pre><code>>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> plt.plot(data, stats.exponweib.pdf(data, *stats.exponweib.fit(data, 1, 1, scale=02, loc=0)))
>>> _ = plt.hist(data, bins=np.linspace(0, 16, 33), normed=True, alpha=0.5);
>>> plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/CSEsK.png" alt="exponweib fit"></p> |
17,311,917 | ggplot2 - The unit of size | <p>A quick question that I can't find answer on the web (or Wickham's book):</p>
<p>What is the unit of the size argument in <code>ggplot2</code>? For example, <code>geom_text(size = 10)</code> -- <code>10</code> in what units?</p>
<p>The same question applies to default unit in <code>ggsave(height = 10, width = 10)</code>.</p> | 17,312,440 | 3 | 2 | null | 2013-06-26 05:06:30.643 UTC | 17 | 2020-08-04 14:19:39.86 UTC | 2020-08-04 14:19:39.86 UTC | null | 1,851,712 | null | 1,793,442 | null | 1 | 52 | r|ggplot2 | 21,720 | <p>The answer is : The unit is the points. It is the unit of fontsize in the <code>grid</code> package. In <code>?unit</code>, we find the following definition</p>
<pre><code>"points" Points. There are 72.27 points per inch.
</code></pre>
<p>(but note the closely related "bigpts" <code>Big Points. 72 bp = 1 in.</code>)</p>
<p>Internally <code>ggplot2</code> will multiply the font size by a magic number <code>ggplot2:::.pt</code>, defined as <strong>1/0.352777778</strong>.</p>
<p>Here a demonstration, I create a letter using grid and ggplot2 with same size:</p>
<pre><code>library(grid)
library(ggplot2)
ggplot(data=data.frame(x=1,y=1,label=c('A'))) +
geom_text(aes(x,y,label=label),size=100)
## I divide by the magic number to get the same size.
grid.text('A',gp=gpar(fontsize=100/0.352777778,col='red'))
</code></pre>
<p><img src="https://i.stack.imgur.com/9x0SQ.png" alt="enter image description here"></p>
<p><em>Addendum</em> Thanks to @baptiste</p>
<p>The "magic number"(<em>defined in aaa-constants.r as .pt <- 1 / 0.352777778</em>) is really just the conversion factor between "points" and "mm", that is <code>1/72 * 25.4 = 0.352777778</code>. Unfortunately, <code>grid</code> makes the subtle distinction between "pts" and "bigpts", which explains why <code>convertUnit(unit(1, "pt"), "mm", valueOnly=TRUE)</code> gives the slightly different value of <code>0.3514598</code>.</p> |
17,589,420 | When to choose mouseover() and hover() function? | <p>What are the differences between jQuery <code>.mouseover()</code> and <code>.hover()</code> functions? If they are totally same why jQuery uses both?</p> | 17,589,540 | 5 | 5 | null | 2013-07-11 09:09:47.197 UTC | 26 | 2019-10-18 15:42:25.373 UTC | 2019-10-18 15:35:52.617 UTC | null | 814,702 | null | 2,138,752 | null | 1 | 125 | jquery|mouseevent | 126,553 | <h1>From the official jQuery documentation</h1>
<ul>
<li><a href="http://api.jquery.com/mouseover/" rel="noreferrer"><code>.mouseover()</code></a><br>
Bind an event handler to the "mouseover" JavaScript event, or trigger
that event on an element.</li>
</ul>
<hr>
<ul>
<li><p><a href="http://api.jquery.com/hover/" rel="noreferrer"><code>.hover()</code></a> Bind one or two handlers
to the matched elements, to be executed when the mouse pointer
<em>enters</em> and <em>leaves</em> the elements. </p>
<p>Calling <code>$(selector).hover(handlerIn, handlerOut)</code> is shorthand for:
<code>$(selector).mouseenter(handlerIn).mouseleave(handlerOut);</code></p></li>
</ul>
<hr>
<ul>
<li><p><a href="http://api.jquery.com/mouseenter/" rel="noreferrer"><code>.mouseenter()</code></a></p>
<p>Bind an event handler to be fired when the mouse enters an element,
or trigger that handler on an element.</p>
<p><code>mouseover</code> fires when the pointer moves into the child element as
well, while <code>mouseenter</code> fires only when the pointer moves into the
bound element.</p></li>
</ul>
<hr>
<h1>What this means</h1>
<p>Because of this, <code>.mouseover()</code> is <em>not</em> the same as <code>.hover()</code>, for the same reason <code>.mouseover()</code> is <em>not</em> the same as <code>.mouseenter()</code>.</p>
<pre><code>$('selector').mouseover(over_function) // may fire multiple times
// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function)
</code></pre> |
17,493,080 | advantage of tap method in ruby | <p>I was just reading a blog article and noticed that the author used <code>tap</code> in a snippet something like:</p>
<pre class="lang-ruby prettyprint-override"><code>user = User.new.tap do |u|
u.username = "foobar"
u.save!
end
</code></pre>
<p>My question is what exactly is the benefit or advantage of using <code>tap</code>? Couldn't I just do:</p>
<pre class="lang-ruby prettyprint-override"><code>user = User.new
user.username = "foobar"
user.save!
</code></pre>
<p>or better yet:</p>
<pre class="lang-ruby prettyprint-override"><code>user = User.create! username: "foobar"
</code></pre> | 17,493,604 | 19 | 0 | null | 2013-07-05 16:12:34.187 UTC | 37 | 2022-07-08 13:09:42.067 UTC | 2022-07-08 13:09:42.067 UTC | null | 74,089 | null | 435,471 | null | 1 | 133 | ruby | 55,724 | <p>When readers encounter:</p>
<pre><code>user = User.new
user.username = "foobar"
user.save!
</code></pre>
<p>they would have to follow all the three lines and then recognize that it is just creating an instance named <code>user</code>.</p>
<p>If it were:</p>
<pre><code>user = User.new.tap do |u|
u.username = "foobar"
u.save!
end
</code></pre>
<p>then that would be immediately clear. A reader would not have to read what is inside the block to know that an instance <code>user</code> is created.</p> |
30,726,663 | Switch-case won't compile after commenting out an unused line | <p>Here is my code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main (void) {
struct addrinfo hints;
memset (&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_CANONNAME;
struct addrinfo *res;
getaddrinfo ("example.com", "http", &hints, &res);
printf ("Host: %s\n", "example.com");
void *ptr;
while (res != NULL) {
printf("AI Family for current addrinfo: %i\n", res->ai_family);
switch (res->ai_family) {
case AF_INET:
ptr = (struct sockaddr_in *) res->ai_addr;
struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
break;
}
res = res->ai_next;
}
return 0;
}
</code></pre>
<p>which compiles fine.</p>
<p>However when I comment out this line:</p>
<pre><code>//ptr = (struct sockaddr_in *) res->ai_addr;
</code></pre>
<p>I will get:</p>
<pre><code>$ gcc ex4.c
ex4.c:30:9: error: expected expression
struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
^
1 error generated.
</code></pre>
<p>What am I missing? </p> | 30,726,783 | 2 | 4 | null | 2015-06-09 08:23:40.65 UTC | 6 | 2015-06-10 05:26:13.77 UTC | 2015-06-09 21:08:14.187 UTC | null | 371,228 | null | 1,173,112 | null | 1 | 82 | c | 4,707 | <p>Each case in a switch statement is, technically speaking, a label. For some <a href="https://stackoverflow.com/a/8384505/2908724">obscure and old reasons</a>, you are not allowed to have a variable declaration as the first line after a label. By commenting out the assignment </p>
<pre><code>ptr = (struct sockaddr_in *) res->ai_addr;
</code></pre>
<p>the line</p>
<pre><code>struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
</code></pre>
<p>becomes the first line after the label <code>AF_INET:</code> which, like I said, is illegal in C.</p>
<p>The solution is to wrap all of your case statements in curly brackets like so:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main (void) {
struct addrinfo hints;
memset (&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_CANONNAME;
struct addrinfo *res;
getaddrinfo ("example.com", "http", &hints, &res);
printf ("Host: %s\n", "example.com");
void *ptr;
while (res != NULL) {
printf("AI Family for current addrinfo: %i\n", res->ai_family);
switch (res->ai_family) {
case AF_INET:
{
ptr = (struct sockaddr_in *) res->ai_addr;
struct sockaddr_in *sockAddrIn = (struct sockaddr_in *) res->ai_addr;
break;
}
}
res = res->ai_next;
}
return 0;
}
</code></pre>
<p>Anyway, I think this is better coding practice.</p> |
18,245,858 | Galaxy S3 google play not working | <p>My girlfriends Galaxy S3 is not letting her access Google Play Store on the device. She Has tried all of the conventional means of getting things fixed clearing data / cache / force stopping all to no avail. </p>
<p>Any other options that do not involve resting the phone?</p> | 18,245,988 | 3 | 0 | null | 2013-08-15 03:23:53.23 UTC | null | 2013-10-12 05:31:13.923 UTC | 2013-09-14 07:38:45.663 UTC | null | 1,400,768 | null | 1,580,784 | null | 1 | 3 | google-play|galaxy | 63,812 | <p>This answer is from <a href="http://forums.androidcentral.com/t-inspire-4g/246409-cant-access-google-play-market.html" rel="nofollow noreferrer">this link</a>:</p>
<blockquote>
<p>4 Simple steps. Set Date, Clear Play Store, Clear Google Framework, Reboot.</p>
</blockquote>
<hr />
<p><a href="http://forums.androidcentral.com/google-nexus-7-tablet-2012/268695-google-play-store-isnt-working.html" rel="nofollow noreferrer">Another link</a></p>
<blockquote>
<p>If nothing works, try removing your Google account, then signing in again.</p>
<p>Settings ---> Google ---> Tap on your email address ---> Tap on the three dots at the top-right corner ---> Tap on "Remove account".</p>
</blockquote>
<hr />
<p>Check out this <a href="http://www.gottabemobile.com/2012/03/07/3-ways-to-get-google-play-store-now-on-your-android-device/" rel="nofollow noreferrer">too</a>.</p>
<blockquote>
<p>From the home screen, hit the menu button, and go to settings. Next go to applications, and then manage applications and click on the all tab at the top. Scroll down to Market and clear your data and cache. Once you open Android Market, you’ll be prompted to accept the new terms and conditions of Google Play and then the app will update itself.</p>
<p>Download the APK from the Google Play Store, which was provided on Android-centric blog Droid-life. You can download the APK from MediaFire. Installing the APK would replace the Android Market app.</p>
</blockquote>
<hr />
<p>Again another <a href="http://androidforums.com/samsung-galaxy-s3/698001-google-play-app-wont-open.html" rel="nofollow noreferrer">link</a></p>
<blockquote>
<ol>
<li>Turn off the device.</li>
<li>Press and hold the <strong>Volume Up</strong> key, <strong>Home</strong> key, and <strong>Power</strong> key at the same time.</li>
<li>When the phone vibrates, let go of the <strong>buttons</strong>.</li>
<li>When the Android System Recovery screen appears, let go of the Volume Up and Home keys.</li>
<li>Press the <strong>Volume Down</strong> key to move to and highlight <strong>wipe cache partition</strong>.</li>
<li>Press the <strong>Power</strong> key to select and wipe the cache partition.</li>
<li>After the wipe is finished, go back up till <strong>reboot system now</strong> is highlighted and press the <strong>Power</strong> key to restart the phone.</li>
</ol>
</blockquote>
<hr />
<p>Some video tutorials:</p>
<ul>
<li><a href="http://www.youtube.com/watch?v=VDc-JwbauAM" rel="nofollow noreferrer">http://www.youtube.com/watch?v=VDc-JwbauAM</a></li>
<li><a href="http://www.youtube.com/watch?v=tRO3VAITias" rel="nofollow noreferrer">http://www.youtube.com/watch?v=tRO3VAITias</a></li>
<li><a href="http://www.tech-recipes.com/rx/29473/ok-android-jelly-bean-reset-app-preferences/" rel="nofollow noreferrer">http://www.tech-recipes.com/rx/29473/ok-android-jelly-bean-reset-app-preferences/</a></li>
</ul>
<p>Hope it helps you.</p>
<p>As said by <a href="https://stackoverflow.com/users/1580784/codemonkeyalx">@CodeMonkeyAlx</a></p>
<p>You can Factory reset it but if you have important data on your device then be sure to have a Backup . Here i have listed out some Backup apps. Some needs rooted device whereas some works for unrooted device too.</p>
<ol>
<li><a href="https://play.google.com/store/apps/details?id=mobi.infolife.appbackup&hl=en" rel="nofollow noreferrer">App Backup & Restore</a></li>
<li><a href="https://play.google.com/store/apps/details?id=com.keramidas.TitaniumBackup" rel="nofollow noreferrer">Titanium Backup ★ root</a></li>
<li><a href="https://play.google.com/store/apps/details?id=com.idea.backup.smscontacts" rel="nofollow noreferrer">Super Backup : SMS & Contacts</a></li>
<li><a href="https://play.google.com/store/apps/details?id=com.koushikdutta.backup" rel="nofollow noreferrer">Helium - App Sync and Backup</a></li>
<li><a href="https://play.google.com/store/apps/details?id=de.goddchen.android.easyapptoolbox" rel="nofollow noreferrer">Easy App Toolbox (Backup)</a></li>
<li><a href="https://play.google.com/store/apps/details?id=com.genie9.gcloudbackup&hl=en" rel="nofollow noreferrer">G Cloud Backup</a></li>
</ol> |
18,452,701 | Ruby on Rails , No Rakefile found error | <p>I installed ruby on rails, postgres.
I installed all required gem files,
I created a project as <a href="http://guides.rubyonrails.org/getting_started.html" rel="noreferrer">http://guides.rubyonrails.org/getting_started.html</a> wants</p>
<p>I added below code in config/routes.rb</p>
<pre><code>Blog::Application.routes.draw do
resources :posts
root to: "welcome#index"
end
</code></pre>
<p>I am trying to run <code>rake routes</code> command.</p>
<p>But i get </p>
<pre><code>rake aborted!
No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb)
</code></pre>
<p>I checked internet.. Everybody says "i need to run it under exact project folder".
But i need to say, I tried almost 20 different folders on my Windows 7. (I am getting crazy)</p>
<p>I don't exactly know what is necessary for you experts, but :</p>
<p>I use : </p>
<p>Windows 7 Ultimate (64bit)
Ruby200-x64
rake-10.1.0</p>
<p>Thanks in advance..</p> | 18,453,089 | 3 | 6 | null | 2013-08-26 20:43:29.843 UTC | 2 | 2018-09-10 21:05:35.333 UTC | null | null | null | null | 403,298 | null | 1 | 11 | ruby-on-rails|ruby|rake | 53,631 | <p>Sounds like your <code>Rakefile</code> might be missing, or you might not be in the app's "root directory".</p>
<p><code>cd</code> to your blog directory, and you should see,</p>
<pre><code>$ ls
app/
bin/
config/
db/
...
</code></pre>
<p>If it doesn't exist already, create a new file named <code>Rakefile</code> and put this text in there.</p>
<pre><code>#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Blog::Application.load_tasks
</code></pre> |
5,452,422 | OpenSSL encryption using .NET classes | <p>I'm looking to create a class that uses the .NET libraries that is compatible with OpenSSL. I'm aware there is an OpenSSL.Net wrapper, but I would prefer to avoid referencing 3rd party\unmanaged code. I'm not looking for a discussion of whether this is the right choice, but there are reasons for it.</p>
<p>Currently I have the following, which I believe should be compatible with OpenSSL - it effectively does what I believe OpenSSL does from the OpenSSL documentation. However even when just using this class to do both the encryption and decryption, I'm getting the following error:</p>
<pre><code>[CryptographicException] Padding is invalid and cannot be removed.
</code></pre>
<p>I have stepped through the code and verified that the salt\key\iv are all the same during the encryption and decryption process. </p>
<p>See below for sample class and call to do encrypt decrypt. Any ideas or pointers would be welcome. </p>
<pre><code>public class Protection
{
public string OpenSSLEncrypt(string plainText, string passphrase)
{
// generate salt
byte[] key, iv;
byte[] salt = new byte[8];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
DeriveKeyAndIV(passphrase, salt, out key, out iv);
// encrypt bytes
byte[] encryptedBytes = EncryptStringToBytesAes(plainText, key, iv);
// add salt as first 8 bytes
byte[] encryptedBytesWithSalt = new byte[salt.Length + encryptedBytes.Length];
Buffer.BlockCopy(salt, 0, encryptedBytesWithSalt, 0, salt.Length);
Buffer.BlockCopy(encryptedBytes, 0, encryptedBytesWithSalt, salt.Length, encryptedBytes.Length);
// base64 encode
return Convert.ToBase64String(encryptedBytesWithSalt);
}
public string OpenSSLDecrypt(string encrypted, string passphrase)
{
// base 64 decode
byte[] encryptedBytesWithSalt = Convert.FromBase64String(encrypted);
// extract salt (first 8 bytes of encrypted)
byte[] salt = new byte[8];
byte[] encryptedBytes = new byte[encryptedBytesWithSalt.Length - salt.Length];
Buffer.BlockCopy(encryptedBytesWithSalt, 0, salt, 0, salt.Length);
Buffer.BlockCopy(encryptedBytesWithSalt, salt.Length, encryptedBytes, 0, encryptedBytes.Length);
// get key and iv
byte[] key, iv;
DeriveKeyAndIV(passphrase, salt, out key, out iv);
return DecryptStringFromBytesAes(encryptedBytes, key, iv);
}
private static void DeriveKeyAndIV(string passphrase, byte[] salt, out byte[] key, out byte[] iv)
{
// generate key and iv
List<byte> concatenatedHashes = new List<byte>(48);
byte[] password = Encoding.UTF8.GetBytes(passphrase);
byte[] currentHash = new byte[0];
MD5 md5 = MD5.Create();
bool enoughBytesForKey = false;
// See http://www.openssl.org/docs/crypto/EVP_BytesToKey.html#KEY_DERIVATION_ALGORITHM
while (!enoughBytesForKey)
{
int preHashLength = currentHash.Length + password.Length + salt.Length;
byte[] preHash = new byte[preHashLength];
Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
Buffer.BlockCopy(password, 0, preHash, currentHash.Length, password.Length);
Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + password.Length, salt.Length);
currentHash = md5.ComputeHash(preHash);
concatenatedHashes.AddRange(currentHash);
if (concatenatedHashes.Count >= 48)
enoughBytesForKey = true;
}
key = new byte[32];
iv = new byte[16];
concatenatedHashes.CopyTo(0, key, 0, 32);
concatenatedHashes.CopyTo(32, iv, 0, 16);
md5.Clear();
md5 = null;
}
static byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged { Key = key, IV = iv, Mode = CipherMode.CBC, KeySize = 256, BlockSize = 256 };
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
swEncrypt.Flush();
swEncrypt.Close();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return msEncrypt.ToArray();
}
static string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged { Key = key, IV = iv, Mode = CipherMode.CBC, KeySize = 256, BlockSize = 256};
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
srDecrypt.Close();
}
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
}
</code></pre>
<p>I then call this to test it:</p>
<pre><code>Protection protection = new Protection();
const string passphrase = "<passphrase>";
string encrypted = protection.OpenSSLEncrypt(jobid, passphrase);
string decrypted = protection.OpenSSLDecrypt(encrypted, passphrase);
</code></pre> | 5,454,692 | 3 | 2 | null | 2011-03-27 21:00:34.18 UTC | 14 | 2021-10-07 15:23:39.84 UTC | 2017-06-02 07:36:50.533 UTC | null | 608,639 | null | 385,024 | null | 1 | 20 | c#|.net|encryption|openssl|aes | 36,499 | <p>Finally figured this one out. In the event someone needs to integrate openssl and .NET without using the openssl wrappers, I'll share the results here. </p>
<p>1) The main issue with my original code (as in the question) is that you must initialize the BlockSize and KeySize on your RijndaelManaged instance BEFORE setting the key or IV. </p>
<p>2) I also had BlockSize set to 256 when it should only be 128</p>
<p>3) The remainder of my issue came to the fact that openssl puts and expects "Salted__" onto the front of the salt before appending the encrypted string and then base64 encoding it. (I saw this initially in the openssl documentation with respect to file encryption but didn't think it did it when doing it directly through commandline - Apparently I was wrong!! Note also the capitalization of the S in Salted!)</p>
<p>With that all in mind, here is my "fixed" code:</p>
<pre><code>public class Protection
{
public string OpenSSLEncrypt(string plainText, string passphrase)
{
// generate salt
byte[] key, iv;
byte[] salt = new byte[8];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
DeriveKeyAndIV(passphrase, salt, out key, out iv);
// encrypt bytes
byte[] encryptedBytes = EncryptStringToBytesAes(plainText, key, iv);
// add salt as first 8 bytes
byte[] encryptedBytesWithSalt = new byte[salt.Length + encryptedBytes.Length + 8];
Buffer.BlockCopy(Encoding.ASCII.GetBytes("Salted__"), 0, encryptedBytesWithSalt, 0, 8);
Buffer.BlockCopy(salt, 0, encryptedBytesWithSalt, 8, salt.Length);
Buffer.BlockCopy(encryptedBytes, 0, encryptedBytesWithSalt, salt.Length + 8, encryptedBytes.Length);
// base64 encode
return Convert.ToBase64String(encryptedBytesWithSalt);
}
public string OpenSSLDecrypt(string encrypted, string passphrase)
{
// base 64 decode
byte[] encryptedBytesWithSalt = Convert.FromBase64String(encrypted);
// extract salt (first 8 bytes of encrypted)
byte[] salt = new byte[8];
byte[] encryptedBytes = new byte[encryptedBytesWithSalt.Length - salt.Length - 8];
Buffer.BlockCopy(encryptedBytesWithSalt, 8, salt, 0, salt.Length);
Buffer.BlockCopy(encryptedBytesWithSalt, salt.Length + 8, encryptedBytes, 0, encryptedBytes.Length);
// get key and iv
byte[] key, iv;
DeriveKeyAndIV(passphrase, salt, out key, out iv);
return DecryptStringFromBytesAes(encryptedBytes, key, iv);
}
private static void DeriveKeyAndIV(string passphrase, byte[] salt, out byte[] key, out byte[] iv)
{
// generate key and iv
List<byte> concatenatedHashes = new List<byte>(48);
byte[] password = Encoding.UTF8.GetBytes(passphrase);
byte[] currentHash = new byte[0];
MD5 md5 = MD5.Create();
bool enoughBytesForKey = false;
// See http://www.openssl.org/docs/crypto/EVP_BytesToKey.html#KEY_DERIVATION_ALGORITHM
while (!enoughBytesForKey)
{
int preHashLength = currentHash.Length + password.Length + salt.Length;
byte[] preHash = new byte[preHashLength];
Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
Buffer.BlockCopy(password, 0, preHash, currentHash.Length, password.Length);
Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + password.Length, salt.Length);
currentHash = md5.ComputeHash(preHash);
concatenatedHashes.AddRange(currentHash);
if (concatenatedHashes.Count >= 48)
enoughBytesForKey = true;
}
key = new byte[32];
iv = new byte[16];
concatenatedHashes.CopyTo(0, key, 0, 32);
concatenatedHashes.CopyTo(32, iv, 0, 16);
md5.Clear();
md5 = null;
}
static byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt;
// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged { Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = key, IV = iv };
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
swEncrypt.Flush();
swEncrypt.Close();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return msEncrypt.ToArray();
}
static string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext;
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged {Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = key, IV = iv};
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
srDecrypt.Close();
}
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
}
</code></pre> |
5,147,438 | Match two fields with jQuery validate plugin | <p>I have an e-mail field, and a confirm e-mail field. I need to validate both of them to make sure their values match.</p>
<p>Is there a way to add a rule to match those two fields?</p> | 5,147,456 | 3 | 1 | null | 2011-02-28 20:52:16.697 UTC | 3 | 2014-12-17 12:29:18.78 UTC | null | null | null | null | 295,302 | null | 1 | 33 | javascript|jquery|asp.net|jquery-validate | 30,300 | <p>You could use the <a href="http://docs.jquery.com/Plugins/Validation/Methods/equalTo" rel="noreferrer">equalTo</a> method:</p>
<pre><code>$('#myform').validate({
rules: {
email: 'required',
emailConfirm: {
equalTo: '#email'
}
}
});
</code></pre> |
9,317,922 | What does the MOVZBL instruction do in IA-32 AT&T syntax? | <p>What exactly does this instruction do?</p>
<pre><code>movzbl 0x01(%eax,%ecx), %eax
</code></pre> | 9,318,005 | 2 | 3 | null | 2012-02-16 19:38:55.3 UTC | 5 | 2020-07-22 13:36:07.907 UTC | 2020-07-22 13:36:07.907 UTC | null | 224,132 | user663896 | null | null | 1 | 46 | assembly|x86|att|zero-extension | 82,955 | <p>AT&T syntax splits the <a href="http://www.felixcloutier.com/x86/MOVZX.html" rel="noreferrer"><code>movzx</code> Intel instruction mnemonic</a> into different mnemonics for different source sizes (<code>movzb</code> vs. <code>movzw</code>). In Intel syntax, it's:</p>
<pre><code>movzx eax, byte ptr [eax+ecx+1]
</code></pre>
<p>i.e. load a byte from memory at eax+ecx+1 and zero-extend to full register.</p>
<p>BTW, most GNU tools now have a switch or a config option to prefer Intel syntax. (Such as <code>objdump -Mintel</code> or <code>gcc -S -masm=intel</code>, although the latter affects the syntax used when compiling inline-asm). I would certainly recommend to look into it, if you don't do AT&T assembly for living. See also the <a href="/questions/tagged/x86" class="post-tag" title="show questions tagged 'x86'" rel="tag">x86</a> tag wiki for more docs and guides.</p> |
18,329,001 | Parse to Boolean or check String Value | <p>If I have a variable that pulls a string of <code>true</code> or <code>false</code> from the DB,<br>
which would be the preferred way of checking its value?</p>
<pre><code>string value = "false";
if(Boolean.Parse(value)){
DoStuff();
}
</code></pre>
<p><em>I know there are different ways of parsing to bool - this is an example</em><br>
or</p>
<pre><code>string value = "false";
if(value == "true"){
DoStuff();
}
</code></pre>
<p>I am pulling a lot of true/false values from the DB in <code>string</code> format, and want to know if these methods make any performance difference at all?</p> | 18,329,085 | 8 | 1 | null | 2013-08-20 07:12:31.077 UTC | 1 | 2021-06-18 21:57:34.013 UTC | null | null | null | null | 1,514,813 | null | 1 | 16 | c#|boolean | 51,416 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/system.boolean.tryparse.aspx"><code>Boolean.TryParse</code></a>:</p>
<pre><code>string value = "false";
Boolean parsedValue;
if (Boolean.TryParse(value, out parsedValue))
{
if (parsedValue)
{
// do stuff
}
else
{
// do other stuff
}
}
else
{
// unable to parse
}
</code></pre> |
19,925,075 | Fit website background image to screen size | <p>I'm just starting on a website and I already encounter a small problem where I can't find a specific solution to.</p>
<p>I wanted to make my website background fit any screen size in width, height does not matter.</p>
<p>This is the link to my image:</p>
<pre><code> ../IMAGES/background.jpg
</code></pre>
<p>EDIT</p>
<p>I have no idea what's wrong, but for some reason the body doesn't even want to get the background image. It just displays a plain white background.</p>
<pre><code>body
{background-image:url(../IMAGES/background.jpg);}
</code></pre> | 19,925,343 | 14 | 2 | null | 2013-11-12 09:12:49.553 UTC | 11 | 2021-03-24 08:58:59.32 UTC | 2017-08-11 14:00:26.053 UTC | null | 1,000,551 | null | 2,982,476 | null | 1 | 31 | html|css|background|size|responsive | 405,084 | <p>you can do this with this plugin <a href="http://dev.andreaseberhard.de/jquery/superbgimage/">http://dev.andreaseberhard.de/jquery/superbgimage/</a></p>
<p>or </p>
<pre><code> background-image:url(../IMAGES/background.jpg);
background-repeat:no-repeat;
background-size:cover;
</code></pre>
<p>with no need the prefixes of browsers. it's all ready suporterd in both of browers</p> |
15,273,551 | Using MSBuild, how do I build an MVC4 solution from the command line (applying Web.config transformations in the process) and output to a folder? | <p>I think the question title pretty much said it all, but for clarity, I am trying to: </p>
<ol>
<li>Build a VS2010 ASP.NET MVC4 solution from the command line (MSBuild), specifying a solution configuration (e.g. Release)</li>
<li>Apply any Web.config transformations for that configuration during the process</li>
<li>Output the results into a folder on the local machine (no IIS, agents, zip files, FTP, packages etc, just <em>a folder</em> containing all the files required to run that web site) </li>
</ol>
<p>I've been trying to figure this out for almost a week now, through the Microsoft docs (which are spectacularly unhelpful), other answers on SO and general Googling. I don't know if I'm just not getting it (which is entirely possible), or if MSBuild/MSDeploy really is the cryptic mess it currently appears to be. </p>
<p>Is there a reasonably simple way to achieve this? Help, please!</p> | 15,317,119 | 1 | 1 | null | 2013-03-07 14:19:13.253 UTC | 8 | 2015-07-29 22:09:40.65 UTC | 2013-03-08 07:53:20.433 UTC | null | 43,140 | null | 43,140 | null | 1 | 10 | .net|deployment|msbuild|msdeploy | 7,296 | <p>If you are running VS2010: ensure you have the Azure 1.7+ SDK installed (even if you're not publishing to Azure, it adds the VS2012 publishing features to VS2010)</p>
<p>VS2012+ have these featured built in</p>
<pre><code>msbuild ProjectFile.csproj /p:Configuration=Release ^
/p:Platform=AnyCPU ^
/t:WebPublish ^
/p:WebPublishMethod=FileSystem ^
/p:DeleteExistingFiles=True ^
/p:publishUrl=c:\output
</code></pre>
<p>Or if you are building the solution file:</p>
<pre><code>msbuild Solution.sln /p:Configuration=Release ^
/p:DeployOnBuild=True ^
/p:DeployDefaultTarget=WebPublish ^
/p:WebPublishMethod=FileSystem ^
/p:DeleteExistingFiles=True ^
/p:publishUrl=c:\output
</code></pre>
<p>Either way, you can also set <code>/p:PrecompileBeforePublish=true</code> and the output will be a precompiled version of the site.</p>
<p>Once you have the Azure SDK installed you would usually create a publish profile and simply use <code>/p:PublishProfile=DeployToFolder</code> but I've given you the manual command line in case you're not interested in going all-in with the new publishing stuff.</p> |
15,302,713 | Zend Framework 2 Redirect | <p>How can I redirect to another module?</p>
<pre><code>return $this->redirect()->toRoute(null, array(
'module' => 'othermodule',
'controller' => 'somecontroller',
'action' => 'someaction'
));
</code></pre>
<p>This doesn't seem to work, any ideas?</p> | 15,303,267 | 4 | 1 | null | 2013-03-08 20:27:28.51 UTC | 2 | 2015-04-30 13:04:23.72 UTC | 2013-03-08 21:02:41.067 UTC | null | 1,742,415 | null | 2,029,042 | null | 1 | 10 | zend-framework2 | 44,737 | <p>This is how I redirect from my Controller to another Route:</p>
<pre><code>return $this->redirect()->toRoute('dns-search', array(
'companyid' => $this->params()->fromRoute('companyid')
));
</code></pre>
<p>Where dns-search is the route I want to redirect to and companyid are the url params.</p>
<p>In the end the URL becomes /dns/search/1 (for example)</p> |
15,433,377 | How parse 2013-03-13T20:59:31+0000 date string to Date | <p>How to parse this format date string <strong>2013-03-13T20:59:31+0000</strong> to Date object?</p>
<p>I'm trying on this way but it doesn't work.</p>
<pre><code>DateFormat df = new SimpleDateFormat("YYYY-MM-DDThh:mm:ssTZD");
Date result = df.parse(time);
</code></pre>
<p>I get this exception from the first line:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Illegal pattern character 'T'</p>
</blockquote> | 15,433,475 | 7 | 1 | null | 2013-03-15 13:10:38.427 UTC | 11 | 2021-10-26 06:50:28.177 UTC | 2021-10-26 06:42:05.193 UTC | null | 5,772,882 | null | 1,073,748 | null | 1 | 29 | java|android|parsing|datetime-format | 117,641 | <p><code>DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");</code></p>
<p>Year is lower case y.
Any characters that are in the input which are not related to the date (like the 'T' in <code>2013-03-13T20:59:31+0000</code> should be quoted in <code>''</code>.</p>
<p>For a list of the defined pattern letters see the <a href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">documentation</a> </p>
<p>Parse checks that the given date is in the format you specified.
To print the date in a specific format after checking see below:</p>
<pre><code>DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
Date result;
try {
result = df.parse("2013-03-13T20:59:31+0000");
System.out.println("date:"+result); //prints date in current locale
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(result)); //prints date in the format sdf
}
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.