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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,040,681 | XCode 4.3 Unable to load persistent store UserDictionary.sqlite | <p>I have been working on an iOS app for some time, all of a sudden I am getting the following crash every time I run the app in the iOS 5.1 Simulator. </p>
<p>The App does not use Core Data and I am not sure what brought this about. </p>
<p>I have deleted the app from the simulator, done Clean, and a rebuild but nothing seems to help.</p>
<pre><code>Unable to load persistent store at URL 'file://localhost/Users/jcottrell/Library/Application%20Support/iPhone%20Simulator/5.1/Library/Keyboard/UserDictionary.sqlite' ({
metadata = {
NSPersistenceFrameworkVersion = 407;
NSStoreModelVersionHashes = {
UserDictionaryEntry = <f0c9025b 602122f9 37a4e274 bdaacec1 b9a66f83 fca5c43b bed5e80a 6baee338>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "43DABF34-7F7E-4FE9-B78D-8AF64292A967";
"_NSAutoVacuumLevel" = 2;
};
reason = "The model used to open the store is incompatible with the one used to create the store";
})
</code></pre> | 11,042,584 | 2 | 3 | null | 2012-06-14 20:13:21.603 UTC | 10 | 2013-03-16 23:46:11.477 UTC | 2013-03-16 23:46:11.477 UTC | null | 1,457,196 | null | 1,457,196 | null | 1 | 42 | iphone|ios|xcode|store|persistent | 5,141 | <p>I have fixed the problem. I clicked 'iOS Simulator' -> Reset Content and Settings</p> |
11,078,016 | Change event on select with knockout binding, how can I know if it is a real change? | <p>I am building a permissions UI, I have a list of permissions with a select list next to each permission. The permissions are represented by an observable array of objects which are bound to a select list:</p>
<pre><code><div data-bind="foreach: permissions">
<div class="permission_row">
<span data-bind="text: name"></span>
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
<option value="0"></option>
<option value="1">R</option>
<option value="2">RW</option>
</select>
</div>
</div>
</code></pre>
<p>Now the problem is this: the change event gets raised when the UI is just populating for the first time. I call my ajax function, get the permissions list and then the event get raised for each of the permission items. This is really not the behavior I want. I want it to be raised <strong>only when a user really picks out a new value for the permission in the select list</strong>, how can I do that?</p> | 20,397,649 | 11 | 0 | null | 2012-06-18 06:42:56.477 UTC | 18 | 2021-01-20 12:49:15.117 UTC | 2020-12-15 11:08:06.577 UTC | null | 1,783,163 | null | 333,466 | null | 1 | 95 | knockout.js | 173,241 | <p>Actually <strong>you want to find whether the event is triggered by user or program</strong> , and its obvious that event will trigger while initialization.</p>
<p>The knockout approach of adding <code>subscription</code> won't help in all cases, why because in most of the model will be implemented like this</p>
<ol>
<li>init the model with undefined data , just structure <em><code>(actual KO initilization)</code></em></li>
<li>update the model with initial data <em><code>(logical init like load JSON , get data etc)</code></em></li>
<li>User interaction and updates</li>
</ol>
<p>The actual step that we want to capture is changes in 3, but in second step <code>subscription</code> will get call ,
So a better way is to add to event change like </p>
<pre><code> <select data-bind="value: level, event:{ change: $parent.permissionChanged}">
</code></pre>
<p>and detected the event in <code>permissionChanged</code> function </p>
<pre><code>this.permissionChanged = function (obj, event) {
if (event.originalEvent) { //user changed
} else { // program changed
}
}
</code></pre> |
11,223,403 | What are the differences between Clojure, Scheme/Racket and Common Lisp? | <p>I know they are dialects of the same family of language called lisp, but what exactly are the differences? Could you give an overview, if possible, covering topics such as syntax, characteristics, features and resources.</p> | 11,223,779 | 4 | 6 | null | 2012-06-27 09:44:28.293 UTC | 41 | 2017-03-05 14:25:12.173 UTC | 2012-06-27 16:35:30.897 UTC | null | 898,073 | null | 1,031,791 | null | 1 | 143 | clojure|lisp|scheme|common-lisp|racket | 39,717 | <p>They all have a lot in common:</p>
<ul>
<li>Dynamic languages</li>
<li><a href="http://en.wikipedia.org/wiki/Strong_typing" rel="noreferrer">Strongly typed</a></li>
<li>Compiled</li>
<li>Lisp-style syntax, i.e. code is written as a Lisp data structures (forms) with the most common pattern being function calls like: <code>(function-name arg1 arg2)</code></li>
<li>Powerful macro systems that allow you to treat code as data and generate arbitrary code at runtime (often used to either "extend the language" with new syntax or create DSLs)</li>
<li>Often used in functional programming style, although have the ability to accommodate other paradigms</li>
<li>Emphasis in interactive development with a REPL (i.e. you interactively develop in a running instance of the code)</li>
</ul>
<p>Common Lisp distinctive features:</p>
<ul>
<li>A powerful OOP subsystem (<a href="http://en.wikipedia.org/wiki/Common_Lisp_Object_System" rel="noreferrer">Common Lisp Object System</a>)</li>
<li>Probably the best compiler (Common Lisp is the fastest Lisp according to <a href="http://benchmarksgame.alioth.debian.org/u64q/which-programs-are-fastest.html" rel="noreferrer">http://benchmarksgame.alioth.debian.org/u64q/which-programs-are-fastest.html</a> although there isn't much in it.....)</li>
</ul>
<p>Clojure distinctive features:</p>
<ul>
<li>Largest library ecosystem, since you can directly use any Java libraries</li>
<li>Vectors <code>[]</code> and maps <code>{}</code> used as standard in addition to the standard lists <code>()</code> - in addition to the general usefullness of vectors and maps some believe this is a innovation which makes generally more readable</li>
<li>Greater emphasis on immutability and lazy functional programming, somewhat inspired by Haskell</li>
<li>Strong concurrency capabilities supported by software transactional memory at the language level (worth watching: <a href="http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey" rel="noreferrer">http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey</a>)</li>
</ul>
<p>Scheme distinctive features:</p>
<ul>
<li>Arguably the simplest and easiest to learn Lisp</li>
<li>Hygienic macros (see <a href="http://en.wikipedia.org/wiki/Hygienic_macro" rel="noreferrer">http://en.wikipedia.org/wiki/Hygienic_macro</a>) - elegantly avoids the problems with accidental symbol capture in macro expansions</li>
</ul> |
10,995,165 | What is the opposite of :hover (on mouse leave)? | <p>Is there any way to do the opposite of <code>:hover</code> <strong>using only</strong> CSS? As in: if <code>:hover</code> is <code>on Mouse Enter</code>, is there a CSS equivalent to <code>on Mouse Leave</code>?</p>
<p>Example:</p>
<p>I have a HTML menu using list items. When I hover one of the items, there is a CSS color animation from <code>#999</code> to <code>black</code>. How can I create the opposite effect when the mouse leaves the item area, with an animation from <code>black</code> to <code>#999</code>?</p>
<p><a href="http://jsfiddle.net/Cthulhu/SZqkb/">jsFiddle</a></p>
<p>(Have in mind that I do not wish to answer only this example, but the entire "opposite of <code>:hover</code>" issue.)</p> | 10,995,287 | 12 | 8 | null | 2012-06-12 10:51:01.953 UTC | 26 | 2022-09-09 22:26:13.153 UTC | 2017-11-20 16:30:38.063 UTC | null | 2,756,409 | null | 1,041,673 | null | 1 | 152 | css|hover | 299,452 | <p>If I understand correctly you could do the same thing by moving your transitions to the link rather than the hover state:</p>
<pre><code>ul li a {
color:#999;
transition: color 0.5s linear; /* vendorless fallback */
-o-transition: color 0.5s linear; /* opera */
-ms-transition: color 0.5s linear; /* IE 10 */
-moz-transition: color 0.5s linear; /* Firefox */
-webkit-transition: color 0.5s linear; /*safari and chrome */
}
ul li a:hover {
color:black;
cursor: pointer;
}
</code></pre>
<p><a href="http://jsfiddle.net/spacebeers/sELKu/3/" rel="noreferrer">http://jsfiddle.net/spacebeers/sELKu/3/</a></p>
<p>The definition of hover is:</p>
<blockquote>
<p>The :hover selector is used to select elements when you mouse over
them.</p>
</blockquote>
<p>By that definition the opposite of hover is any point at which the mouse is <strong>not</strong> over it. Someone far smarter than me has done this article, setting different transitions on both states - <a href="http://css-tricks.com/different-transitions-for-hover-on-hover-off/" rel="noreferrer">http://css-tricks.com/different-transitions-for-hover-on-hover-off/</a></p>
<pre><code>#thing {
padding: 10px;
border-radius: 5px;
/* HOVER OFF */
-webkit-transition: padding 2s;
}
#thing:hover {
padding: 20px;
border-radius: 15px;
/* HOVER ON */
-webkit-transition: border-radius 2s;
}
</code></pre> |
13,151,196 | How to cast from Object to Integer in VB.NET? | <p>How should I cast from an <code>Object</code> to an <code>Integer</code> in VB.NET?</p>
<p>When I do:</p>
<pre><code>Dim intMyInteger as Integer = TryCast(MyObject, Integer)
</code></pre>
<p>it says:</p>
<blockquote>
<p>TryCast operand must be reference type, but Integer is a value type.</p>
</blockquote> | 13,151,219 | 4 | 4 | null | 2012-10-31 04:15:39.133 UTC | 4 | 2017-04-03 16:39:26.703 UTC | null | null | null | null | 327,528 | null | 1 | 18 | vb.net|string|casting|integer | 44,014 | <p><code>TryCast</code> is the equivalent of C#'s <code>as</code> operator. It is a "safe cast" operator that doesn't throw an exception if the cast fails. Instead, it returns <code>Nothing</code> (<code>null</code> in C#). The problem is, you can't assign <code>Nothing</code> (<code>null</code>) (a reference type) to an <code>Integer</code> (a value type). There is no such thing as an <code>Integer</code> <code>null</code>/<code>Nothing</code>.</p>
<p>Instead, you can use <code>TypeOf</code> and <code>Is</code>:</p>
<pre><code>If TypeOf MyObject Is Integer Then
intMyInteger = DirectCast(MyObject, Integer)
Else
intMyInteger = 0
End If
</code></pre>
<p>This tests to see if the <em>runtime type</em> of <code>MyObject</code> is <code>Integer</code>. See the <a href="http://msdn.microsoft.com/en-us/library/0ec5kw18.aspx" rel="noreferrer">MSDN documentation on the <code>TypeOf</code> operator</a> for more details.</p>
<p>You could also write it like this:</p>
<pre><code>Dim myInt As Integer = If(TypeOf myObj Is Integer, DirectCast(myObj,Integer), 0)
</code></pre>
<p>Furthermore, if an integer with a default value (like 0) is not suitable, you could consider a <code>Nullable(Of Integer)</code> type.</p> |
12,981,150 | iOS app with Django | <p>So we currently have a website that was created using Django. Now, we would like to create a native iOS app that uses the same backend, so we don't have to re-code the whole thing. From my understanding, there are two alternative routes:</p>
<p>1) Call directly Django URLs, which then calls a function. Within that function, create a HTTPResponse, with encoded JSON data and send that back.</p>
<p>2) Create a REST Service from the Django server with something like Tastypie. However, aside from doing straight-forward GET calls to an object, I don't see how we can call custom functions in our Django Models from TastyPie. Can we even do that?</p>
<p>I find it surprising that there is not a lot of information about consuming a web service from iOS with existing backends like Django or RoR. For example, I know that instagram uses Django, but how do they communicate from iOS to their servers?!</p>
<p>Thanks a lot!</p> | 12,981,293 | 3 | 0 | null | 2012-10-19 19:28:53.747 UTC | 15 | 2016-01-17 23:40:59.987 UTC | null | null | null | null | 1,248,709 | null | 1 | 19 | ios|django|restkit|tastypie | 18,105 | <p>I am currently working on an iOS app for iPhone, with Django / Tastypie in the backend. We do both 1 and 2. The resources are offered REST-style (after auth) via Tastypie, and any custom function calls (for example, creating a new user) are handled by views.py at various REST endpoints, which returns JSON.</p> |
12,693,423 | Clean way to throw php exception through jquery/ajax and json | <p>Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.</p> | 12,693,543 | 5 | 2 | null | 2012-10-02 15:29:45.34 UTC | 16 | 2019-05-05 10:17:01.507 UTC | null | null | null | null | 443,793 | null | 1 | 32 | php|jquery | 48,129 | <p>You could do something like this in PHP (assuming this gets called via AJAX):</p>
<pre><code><?php
try {
if (some_bad_condition) {
throw new Exception('Test error', 123);
}
echo json_encode(array(
'result' => 'vanilla!',
));
} catch (Exception $e) {
echo json_encode(array(
'error' => array(
'msg' => $e->getMessage(),
'code' => $e->getCode(),
),
));
}
</code></pre>
<p>In JavaScript:</p>
<pre><code>$.ajax({
// ...
success: function(data) {
if (data.error) {
// handle the error
throw data.error.msg;
}
alert(data.result);
}
});
</code></pre>
<p>You can also trigger the <code>error:</code> handler of $.ajax() by returning a 400 (for example) header:</p>
<pre><code>header('HTTP/1.0 400 Bad error');
</code></pre>
<p>Or use <code>Status:</code> if you're on FastCGI. Note that the <code>error:</code> handler doesn't receive the error details; to accomplish that you have to override how <code>$.ajax()</code> works :)</p> |
13,058,521 | Is this a bug in MonoTouch GC? | <blockquote>
<p>Note: <a href="http://dl.dropbox.com/u/76095045/MTMemoryTest.zip" rel="nofollow noreferrer">I've created a simple project</a>—you can see how switching types between <code>UIButton</code> and <code>CustomButton</code> in storyboard changes GC behavior.</p>
</blockquote>
<p>I'm trying to get my head wrapped around MonoTouch garbage collector.<br>
The issue is similar to <a href="https://stackoverflow.com/q/4902967/458193">the one fixed in MT 4.0</a>, however with inherited types.</p>
<p>To illustrate it, consider two view controllers, parent and child. </p>
<p>Child's view contains a single <code>UIButton</code> that writes to console on tap.<br>
Controller's <code>Dispose</code> method throws an exception so it's hard to miss.</p>
<p>Here goes child view controller:</p>
<pre><code>public override void ViewDidLoad ()
{
base.ViewDidLoad ();
sayHiButton.TouchUpInside += (sender, e) =>
SayHi();
}
}
void SayHi()
{
Console.WriteLine("Hi");
}
protected override void Dispose (bool disposing)
{
throw new Exception("Hey! I've just been collected.");
base.Dispose (disposing);
}
</code></pre>
<p>Parent view controller just presents child controller and sets a timer to dismiss it and run GC:</p>
<pre><code>public override void ViewDidLoad ()
{
base.ViewDidLoad ();
var child = (ChildViewController)Storyboard.InstantiateViewController("ChildViewController");
NSTimer.CreateScheduledTimer(2, () => {
DismissViewController(false, null);
GC.Collect();
});
PresentViewController(child, false, null);
}
</code></pre>
<p>If you run this code, it predictably crashes inside <code>ChildViewController.Dispose()</code> called from its finalizer because child controller has been garbage collected. Cool.</p>
<p>Now open the storyboard and change button type to <code>CustomButton</code>. MonoDevelop will generate a simple <code>UIButton</code> subclass:</p>
<pre><code>[Register ("CustomButton")]
public partial class CustomButton : UIButton
{
public CoolButton (IntPtr handle) : base (handle)
{
}
void ReleaseDesignerOutlets()
{
}
}
</code></pre>
<p>Somehow changing the button type to <code>CustomButton</code> is enough to trick garbage collector into thinking child controller is not yet eligible for collection.</p>
<p>How is that so?</p> | 13,059,140 | 1 | 1 | null | 2012-10-24 22:03:03.433 UTC | 25 | 2012-11-15 14:30:32.07 UTC | 2017-05-23 12:25:48.557 UTC | null | -1 | null | 458,193 | null | 1 | 33 | xamarin.ios|garbage-collection|xamarin | 9,591 | <p>This is an unfortunate side-effect of MonoTouch (who is garbage collected) having to live in a reference counted world (ObjectiveC).</p>
<p>There are a few pieces of information required to be able to understand what's going on:</p>
<ul>
<li>For every managed object (derived from NSObject), there is a corresponding native object.</li>
<li>For custom managed classes (derived from framework classes such as UIButton or UIView), the managed object must stay alive until the native object is freed [1]. The way it works is that when a native object has a reference count of 1, we do not prevent the managed instance from getting garbage collected. <strong>As soon as the reference count increases above 1, we prevent the managed instance from getting garbage collected.</strong></li>
</ul>
<p>What happens in your case is a cycle, which crosses the MonoTouch/ObjectiveC bridge and due to the above rules, the GC can't determine that the cycle can be collected.</p>
<p>This is what happens:</p>
<ul>
<li>Your ChildViewController has a sayHiButton. The native ChildViewController will retain this button, so its reference count will be 2 (one reference held by the managed CustomButton instance + one reference held by the native ChildViewController).</li>
<li>The TouchUpInside event handler has a reference to the ChildViewController instance.</li>
</ul>
<p>Now you see that the CustomButton instance will not be freed, because its reference count is 2. And the ChildViewController instance will not be freed because the CustomButton's event handler has a reference to it.</p>
<p>There are a couple of ways to break the cycle to fix this:</p>
<ul>
<li>Detach the event handler when you no longer need it.</li>
<li>Dispose the ChildViewController when you no longer need it.</li>
</ul>
<p>[1] This is because a managed object may contain user state. For managed objects which are mirroring a corresponding native object (such as the managed UIView instance) MonoTouch knows that the instance can not contain any state, so as soon as no managed code has a reference to the managed instance, the GC can collect it. If a managed instance is required at a later stage, we just create a new one.</p> |
13,118,738 | Can you make newline characters \n display as breaks <br />? | <p>I'm trying to display emails with IMAP. When the email is text though, the newlines \n don't display properly. I'd rather not convert them to breaks < br /> because if the user wanted to reply to that email, it would now be in HTML instead of plain text. Is there perhaps a javascript function that could display it as a line break without changing the code?</p> | 13,118,763 | 3 | 0 | null | 2012-10-29 09:18:47.16 UTC | 4 | 2019-12-03 12:22:51.327 UTC | null | null | null | null | 778,352 | null | 1 | 36 | javascript|html|css|formatting | 30,005 | <p>How about HTML/CSS? If you put your text inside a <code><pre></code> tag, it will show all newlines exactly as they were. Alternatively, you can achieve the same effect by applying the CSS style <code>white-space:pre</code> to any element.</p>
<p>Don't forget to HTMLencode it still (<code><</code> to <code>&lt;</code> etc.), otherwise it will all break apart at the first angle bracket.</p> |
16,808,471 | Ruby On Rails: way to create different seeds file for environments | <p>How can one make the task <code>rake db:seed</code> to use different seeds.rb file on production and development? </p>
<p>edit: any better strategy will be welcome</p> | 16,808,734 | 2 | 1 | null | 2013-05-29 08:02:27.92 UTC | 12 | 2015-12-02 19:14:27.71 UTC | null | null | null | null | 1,942,204 | null | 1 | 25 | ruby-on-rails | 10,024 | <p>You can have a rake task behave differently based on the current environment, and you can change the environment a task runs in by passing <code>RAILS_ENV=production</code> to the command. Using these two together you could produce something like so:</p>
<p>Create the following files with your environment specific seeds:</p>
<pre><code>db/seeds/development.rb
db/seeds/test.rb
db/seeds/production.rb
</code></pre>
<p>Place this line in your base seeds file to run the desired file</p>
<pre><code>load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))
</code></pre>
<p>Call the seeds task:</p>
<pre><code>rake db:seed RAILS_ENV=production
</code></pre> |
17,039,119 | How to get separate price and currency information for an in-app purchase? | <p>I am implementing in-app purchases for an app with support for several countries.</p>
<p>The In-App Billing Version 3 API <a href="http://android-developers.blogspot.jp/2012/12/in-app-billing-version-3.html" rel="noreferrer">claims that</a>:</p>
<blockquote>
<p>No currency conversion or formatting is necessary: prices are reported
in the user's currency and formatted according to their locale.</p>
</blockquote>
<p>This is <a href="https://developer.android.com/google/play/billing/billing_reference.html" rel="noreferrer">actually true</a>, since <code>skuGetDetails()</code> takes care of all necessary formatting. The response includes a field called <code>price</code>, which contains the</p>
<blockquote>
<p>Formatted price of the item, including its currency sign. The price does not include tax.</p>
</blockquote>
<p>However, I need the ISO 4217 currency code (retrievable if I know the store locale) and the actual non-formatted price (optimally in a float or decimal variable) so I can do further processing and analysis myself.</p>
<p>Parsing the return of <code>skuGetDetails()</code> is not a reliable idea, because many countries share the same currency symbols.</p>
<p><img src="https://i.stack.imgur.com/N9Az4.png" alt="Currencies"></p>
<p>How can I get the ISO 4217 currency code and non-formatted price of an in-app purchase with the In-App Billing Version 3 API?</p> | 29,510,024 | 8 | 4 | null | 2013-06-11 07:57:26.097 UTC | 11 | 2018-12-11 12:47:30.727 UTC | null | null | null | null | 1,802,240 | null | 1 | 27 | android|in-app-purchase|in-app-billing | 24,486 | <p>Full information can be found <a href="http://developer.android.com/google/play/billing/billing_reference.html#getSkuDetails">here</a>, but essentially in August 2014 this was resolved with:</p>
<p><strong>The getSkuDetails() method</strong></p>
<p><em>This method returns product details for a list of product IDs. In the response Bundle sent by Google Play, the query results are stored in a String ArrayList mapped to the DETAILS_LIST key. Each String in the details list contains product details for a single product in JSON format. The fields in the JSON string with the product details are summarized below</em></p>
<p><strong>price_currency_code</strong> ISO 4217 currency code for price. For example, if price is specified in British pounds sterling, price_currency_code is "GBP".</p>
<p><strong>price_amount_micros</strong> Price in micro-units, where 1,000,000 micro-units equal one unit of the currency. For example, if price is "€7.99", price_amount_micros is "7990000".</p> |
17,023,376 | Get view of Fragment from FragmentActivity | <p>I have a <code>FragmentActivity</code> where I add a <code>Fragment</code>.
Depending on some situation, I want to access <code>Buttons</code> from that fragment's layout and change click listeners of them.</p>
<p>What I do is:</p>
<pre><code>View view = myFragment.getView();
Button myButton = (Button) view.findViewById(R.id.my_button);
myButton.setOnClickListener(new MyClickListener());
</code></pre>
<p>But the <code>view</code> variable is always <code>null</code>.</p>
<p>How can I get the view of the activity?</p> | 17,023,533 | 5 | 7 | null | 2013-06-10 11:59:26.32 UTC | 2 | 2017-01-04 14:21:09.14 UTC | 2013-06-10 12:12:36.293 UTC | null | 2,450,717 | null | 2,450,717 | null | 1 | 31 | android|android-fragments|android-fragmentactivity | 77,375 | <p>If you want to access your component and set some data, I suggest you to make a method inside the fragment like this:</p>
<pre><code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
return view;
}
public void setSettings(){
Button button = (Button) getView().findViewById(R.id.my_button);
button.setOnClickListener(new MyClickListener());
}
}
</code></pre> |
16,749,637 | RESTful API Server in C# | <p>Are there any frameworks that allow a RESTful API Server to be written in C#?</p>
<p>I have seen MVC 4, however this seems to be providing a view that you can see in the browser, I just require the API server and no view. It would be great if it was able to provide a streaming API too.</p>
<p>Thanks</p> | 16,749,693 | 5 | 0 | null | 2013-05-25 12:38:20.247 UTC | 6 | 2019-02-10 09:51:05.6 UTC | null | null | null | null | 451,678 | null | 1 | 34 | c#|api|rest | 68,671 | <p>If you are using .NET Framework 4.5 you can use <a href="https://docs.microsoft.com/en-us/aspnet/web-api/" rel="noreferrer">Web API</a></p>
<p>If you are using .NET Framework 3.5 I highly recommend <a href="https://github.com/ServiceStackV3/ServiceStackV3" rel="noreferrer">ServiceStack</a></p>
<p>If you are using .NET Core then you can use <a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api" rel="noreferrer">ASP.NET Core Web API</a></p> |
16,792,841 | Detect if user clicks inside a circle | <p>How can I detect when the user clicks inside the red bubble?</p>
<p>It should not be like a square field. The mouse must be really inside the circle:</p>
<p><a href="https://i.stack.imgur.com/dylT0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/dylT0.jpg" alt="img"></a></p>
<p>Here's the code:</p>
<pre><code><canvas id="canvas" width="1000" height="500"></canvas>
<script>
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var w = canvas.width
var h = canvas.height
var bubble = {
x: w / 2,
y: h / 2,
r: 30,
}
window.onmousedown = function(e) {
x = e.pageX - canvas.getBoundingClientRect().left
y = e.pageY - canvas.getBoundingClientRect().top
if (MOUSE IS INSIDE BUBBLE) {
alert("HELLO!")
}
}
ctx.beginPath()
ctx.fillStyle = "red"
ctx.arc(bubble.x, bubble.y, bubble.r, 0, Math.PI*2, false)
ctx.fill()
ctx.closePath()
</script>
</code></pre> | 16,792,888 | 4 | 4 | null | 2013-05-28 13:03:34.777 UTC | 17 | 2016-11-23 03:42:15.877 UTC | 2015-12-17 12:06:09.91 UTC | null | 794,749 | user2039981 | null | null | 1 | 40 | javascript|html|events|canvas|click | 28,521 | <p>A circle, is the geometric position of all the points whose distance from a central point is equal to some number "R".</p>
<p>You want to find the points whose distance is less than or equal to that "R", our radius.</p>
<p>The distance equation in 2d euclidean space is <code>d(p1,p2) = root((p1.x-p2.x)^2 + (p1.y-p2.y)^2)</code>.</p>
<p>Check if the distance between your <code>p</code> and the center of the circle is less than the radius.</p>
<p>Let's say I have a circle with radius <code>r</code> and center at position <code>(x0,y0)</code> and a point <code>(x1,y1)</code> and I want to check if that point is in the circle or not.</p>
<p>I'd need to check if <code>d((x0,y0),(x1,y1)) < r</code> which translates to:</p>
<pre><code>Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r
</code></pre>
<p>In JavaScript.</p>
<p>Now you know all these values <code>(x0,y0)</code> being <code>bubble.x</code> and <code>bubble.y</code> and <code>(x1,y1)</code> being <code>x</code> and <code>y</code>.</p> |
16,586,899 | Android Studio cannot resolve R in imported project? | <p>I'm trying the new Android Studio. I've exported a project from eclipse, using the build gradle option. I've then imported it in Android Studio. The R.java file under gen has a j in a little red circle on it. And in my source files, I get "cannot resolve symbol R" wherever I have a reference to a resource, e.g. "R.layout.account_list" etc.</p>
<p>I have never used Intellij before. Would appreciate any help as there obviously aren't many answer yet about Android Studio. Thanks!</p> | 16,588,886 | 31 | 6 | null | 2013-05-16 12:02:52.823 UTC | 12 | 2016-10-24 09:15:12.643 UTC | null | null | null | null | 2,340,402 | null | 1 | 48 | android|intellij-idea|android-resources|android-studio | 105,519 | <ol>
<li>Press F4 into <strong>Project Structure</strong>, Check <strong>SDKs</strong> on left</li>
<li>Click <strong>Modules</strong> ---> <strong>Source</strong> Tab, check <strong>gen</strong> and <strong>src</strong> as sources </li>
</ol>
<p>PS: The answer over a year old and the menus have changed. </p> |
16,841,382 | what is the performance impact of using int64_t instead of int32_t on 32-bit systems? | <p>Our C++ library currently uses time_t for storing time values. I'm beginning to need sub-second precision in some places, so a larger data type will be necessary there anyway. Also, it might be useful to get around the Year-2038 problem in some places. So I'm thinking about completely switching to a single Time class with an underlying int64_t value, to replace the time_t value in all places.</p>
<p>Now I'm wondering about the performance impact of such a change when running this code on a 32-bit operating system or 32-bit CPU. IIUC the compiler will generate code to perform 64-bit arithmetic using 32-bit registers. But if this is too slow, I might have to use a more differentiated way for dealing with time values, which might make the software more difficult to maintain.</p>
<p>What I'm interested in:</p>
<ul>
<li>which factors influence performance of these operations? Probably the compiler and compiler version; but does the operating system or the CPU make/model influence this as well? Will a normal 32-bit system use the 64-bit registers of modern CPUs?</li>
<li>which operations will be especially slow when emulated on 32-bit? Or which will have nearly no slowdown?</li>
<li>are there any existing benchmark results for using int64_t/uint64_t on 32-bit systems?</li>
<li>does anyone have own experience about this performance impact?</li>
</ul>
<p>I'm mostly interested in g++ 4.1 and 4.4 on Linux 2.6 (RHEL5, RHEL6) on Intel Core 2 systems; but it would also be nice to know about the situation for other systems (like Sparc Solaris + Solaris CC, Windows + MSVC).</p> | 16,841,814 | 4 | 10 | null | 2013-05-30 16:28:18.587 UTC | 14 | 2018-02-13 06:55:33.397 UTC | null | null | null | null | 2,148,773 | null | 1 | 54 | c++|performance|32bit-64bit|32-bit|int64 | 21,915 | <blockquote>
<p>which factors influence performance of these operations? Probably the
compiler and compiler version; but does the operating system or the
CPU make/model influence this as well?</p>
</blockquote>
<p>Mostly the processor architecture (and model - please read model where I mention processor architecture in this section). The compiler may have some influence, but most compilers do pretty well on this, so the processor architecture will have a bigger influence than the compiler. </p>
<p>The operating system will have no influence whatsoever (other than "if you change OS, you need to use a different type of compiler which changes what the compiler does" in some cases - but that's probably a small effect). </p>
<blockquote>
<p>Will a normal 32-bit system use the 64-bit registers of modern CPUs?</p>
</blockquote>
<p>This is not possible. If the system is in 32-bit mode, it will act as a 32-bit system, the extra 32-bits of the registers is completely invisible, just as it would be if the system was actually a "true 32-bit system". </p>
<blockquote>
<p>which operations will be especially slow when emulated on 32-bit? Or which will have nearly no slowdown?</p>
</blockquote>
<p>Addition and subtraction, is worse as these have to be done in sequence of two operations, and the second operation requires the first to have completed - this is not the case if the compiler is just producing two add operations on independent data. </p>
<p>Mulitplication will get a lot worse if the input parameters are actually 64-bits - so 2^35 * 83 is worse than 2^31 * 2^31, for example. This is due to the fact that the processor can produce a 32 x 32 bit multiply into a 64-bit result pretty well - some 5-10 clockcycles. But a 64 x 64 bit multiply requires a fair bit of extra code, so will take longer.</p>
<p>Division is a similar problem to multiplication - but here it's OK to take a 64-bit input on the one side, divide it by a 32-bit value and get a 32-bit value out. Since it's hard to predict when this will work, the 64-bit divide is probably nearly always slow. </p>
<p>The data will also take twice as much cache-space, which may impact the results. And as a similar consequence, general assignment and passing data around will take twice as long as a minimum, since there is twice as much data to operate on. </p>
<p>The compiler will also need to use more registers. </p>
<blockquote>
<p>are there any existing benchmark results for using int64_t/uint64_t on 32-bit systems?</p>
</blockquote>
<p>Probably, but I'm not aware of any. And even if there are, it would only be somewhat meaningful to you, since the mix of operations is HIGHLY critical to the speed of operations. </p>
<p>If performance is an important part of your application, then benchmark YOUR code (or some representative part of it). It doesn't really matter if Benchmark X gives 5%, 25% or 103% slower results, if your code is some completely different amount slower or faster under the same circumstances. </p>
<blockquote>
<p>does anyone have own experience about this performance impact?</p>
</blockquote>
<p>I've recompiled some code that uses 64-bit integers for 64-bit architecture, and found the performance improve by some substantial amount - as much as 25% on some bits of code. </p>
<p>Changing your OS to a 64-bit version of the same OS, would help, perhaps?</p>
<p>Edit: </p>
<p>Because I like to find out what the difference is in these sort of things, I have written a bit of code, and with some primitive template (still learning that bit - templates isn't exactly my hottest topic, I must say - give me bitfiddling and pointer arithmetics, and I'll (usually) get it right... )</p>
<p>Here's the code I wrote, trying to replicate a few common functons:</p>
<pre><code>#include <iostream>
#include <cstdint>
#include <ctime>
using namespace std;
static __inline__ uint64_t rdtsc(void)
{
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (uint64_t)lo)|( ((uint64_t)hi)<<32 );
}
template<typename T>
static T add_numbers(const T *v, const int size)
{
T sum = 0;
for(int i = 0; i < size; i++)
sum += v[i];
return sum;
}
template<typename T, const int size>
static T add_matrix(const T v[size][size])
{
T sum[size] = {};
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
sum[i] += v[i][j];
}
T tsum=0;
for(int i = 0; i < size; i++)
tsum += sum[i];
return tsum;
}
template<typename T>
static T add_mul_numbers(const T *v, const T mul, const int size)
{
T sum = 0;
for(int i = 0; i < size; i++)
sum += v[i] * mul;
return sum;
}
template<typename T>
static T add_div_numbers(const T *v, const T mul, const int size)
{
T sum = 0;
for(int i = 0; i < size; i++)
sum += v[i] / mul;
return sum;
}
template<typename T>
void fill_array(T *v, const int size)
{
for(int i = 0; i < size; i++)
v[i] = i;
}
template<typename T, const int size>
void fill_array(T v[size][size])
{
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
v[i][j] = i + size * j;
}
uint32_t bench_add_numbers(const uint32_t v[], const int size)
{
uint32_t res = add_numbers(v, size);
return res;
}
uint64_t bench_add_numbers(const uint64_t v[], const int size)
{
uint64_t res = add_numbers(v, size);
return res;
}
uint32_t bench_add_mul_numbers(const uint32_t v[], const int size)
{
const uint32_t c = 7;
uint32_t res = add_mul_numbers(v, c, size);
return res;
}
uint64_t bench_add_mul_numbers(const uint64_t v[], const int size)
{
const uint64_t c = 7;
uint64_t res = add_mul_numbers(v, c, size);
return res;
}
uint32_t bench_add_div_numbers(const uint32_t v[], const int size)
{
const uint32_t c = 7;
uint32_t res = add_div_numbers(v, c, size);
return res;
}
uint64_t bench_add_div_numbers(const uint64_t v[], const int size)
{
const uint64_t c = 7;
uint64_t res = add_div_numbers(v, c, size);
return res;
}
template<const int size>
uint32_t bench_matrix(const uint32_t v[size][size])
{
uint32_t res = add_matrix(v);
return res;
}
template<const int size>
uint64_t bench_matrix(const uint64_t v[size][size])
{
uint64_t res = add_matrix(v);
return res;
}
template<typename T>
void runbench(T (*func)(const T *v, const int size), const char *name, T *v, const int size)
{
fill_array(v, size);
uint64_t long t = rdtsc();
T res = func(v, size);
t = rdtsc() - t;
cout << "result = " << res << endl;
cout << name << " time in clocks " << dec << t << endl;
}
template<typename T, const int size>
void runbench2(T (*func)(const T v[size][size]), const char *name, T v[size][size])
{
fill_array(v);
uint64_t long t = rdtsc();
T res = func(v);
t = rdtsc() - t;
cout << "result = " << res << endl;
cout << name << " time in clocks " << dec << t << endl;
}
int main()
{
// spin up CPU to full speed...
time_t t = time(NULL);
while(t == time(NULL)) ;
const int vsize=10000;
uint32_t v32[vsize];
uint64_t v64[vsize];
uint32_t m32[100][100];
uint64_t m64[100][100];
runbench(bench_add_numbers, "Add 32", v32, vsize);
runbench(bench_add_numbers, "Add 64", v64, vsize);
runbench(bench_add_mul_numbers, "Add Mul 32", v32, vsize);
runbench(bench_add_mul_numbers, "Add Mul 64", v64, vsize);
runbench(bench_add_div_numbers, "Add Div 32", v32, vsize);
runbench(bench_add_div_numbers, "Add Div 64", v64, vsize);
runbench2(bench_matrix, "Matrix 32", m32);
runbench2(bench_matrix, "Matrix 64", m64);
}
</code></pre>
<p>Compiled with:</p>
<pre><code>g++ -Wall -m32 -O3 -o 32vs64 32vs64.cpp -std=c++0x
</code></pre>
<p>And the results are: <strong>Note: See 2016 results below</strong> - these results are slightly optimistic due to the difference in usage of SSE instructions in 64-bit mode, but no SSE usage in 32-bit mode.</p>
<pre><code>result = 49995000
Add 32 time in clocks 20784
result = 49995000
Add 64 time in clocks 30358
result = 349965000
Add Mul 32 time in clocks 30182
result = 349965000
Add Mul 64 time in clocks 79081
result = 7137858
Add Div 32 time in clocks 60167
result = 7137858
Add Div 64 time in clocks 457116
result = 49995000
Matrix 32 time in clocks 22831
result = 49995000
Matrix 64 time in clocks 23823
</code></pre>
<p>As you can see, addition, and multiplication isn't that much worse. Division gets really bad. Interestingly, the matrix addition is not much difference at all. </p>
<p>And is it faster on 64-bit I hear some of you ask:
Using the same compiler options, just -m64 instead of -m32 - yupp, a lot faster:</p>
<pre><code>result = 49995000
Add 32 time in clocks 8366
result = 49995000
Add 64 time in clocks 16188
result = 349965000
Add Mul 32 time in clocks 15943
result = 349965000
Add Mul 64 time in clocks 35828
result = 7137858
Add Div 32 time in clocks 50176
result = 7137858
Add Div 64 time in clocks 50472
result = 49995000
Matrix 32 time in clocks 12294
result = 49995000
Matrix 64 time in clocks 14733
</code></pre>
<p><strong>Edit, update for 2016</strong>:
four variants, with and without SSE, in 32- and 64-bit mode of the compiler.</p>
<p>I'm typically using clang++ as my usual compiler these days. I tried compiling with g++ (but it would still be a different version than above, as I've updated my machine - and I have a different CPU too). Since g++ failed to compile the no-sse version in 64-bit, I didn't see the point in that. (g++ gives similar results anyway)</p>
<p>As a short table: </p>
<pre><code>Test name | no-sse 32 | no-sse 64 | sse 32 | sse 64 |
----------------------------------------------------------
Add uint32_t | 20837 | 10221 | 3701 | 3017 |
----------------------------------------------------------
Add uint64_t | 18633 | 11270 | 9328 | 9180 |
----------------------------------------------------------
Add Mul 32 | 26785 | 18342 | 11510 | 11562 |
----------------------------------------------------------
Add Mul 64 | 44701 | 17693 | 29213 | 16159 |
----------------------------------------------------------
Add Div 32 | 44570 | 47695 | 17713 | 17523 |
----------------------------------------------------------
Add Div 64 | 405258 | 52875 | 405150 | 47043 |
----------------------------------------------------------
Matrix 32 | 41470 | 15811 | 21542 | 8622 |
----------------------------------------------------------
Matrix 64 | 22184 | 15168 | 13757 | 12448 |
</code></pre>
<p>Full results with compile options. </p>
<pre><code>$ clang++ -m32 -mno-sse 32vs64.cpp --std=c++11 -O2
$ ./a.out
result = 49995000
Add 32 time in clocks 20837
result = 49995000
Add 64 time in clocks 18633
result = 349965000
Add Mul 32 time in clocks 26785
result = 349965000
Add Mul 64 time in clocks 44701
result = 7137858
Add Div 32 time in clocks 44570
result = 7137858
Add Div 64 time in clocks 405258
result = 49995000
Matrix 32 time in clocks 41470
result = 49995000
Matrix 64 time in clocks 22184
$ clang++ -m32 -msse 32vs64.cpp --std=c++11 -O2
$ ./a.out
result = 49995000
Add 32 time in clocks 3701
result = 49995000
Add 64 time in clocks 9328
result = 349965000
Add Mul 32 time in clocks 11510
result = 349965000
Add Mul 64 time in clocks 29213
result = 7137858
Add Div 32 time in clocks 17713
result = 7137858
Add Div 64 time in clocks 405150
result = 49995000
Matrix 32 time in clocks 21542
result = 49995000
Matrix 64 time in clocks 13757
$ clang++ -m64 -msse 32vs64.cpp --std=c++11 -O2
$ ./a.out
result = 49995000
Add 32 time in clocks 3017
result = 49995000
Add 64 time in clocks 9180
result = 349965000
Add Mul 32 time in clocks 11562
result = 349965000
Add Mul 64 time in clocks 16159
result = 7137858
Add Div 32 time in clocks 17523
result = 7137858
Add Div 64 time in clocks 47043
result = 49995000
Matrix 32 time in clocks 8622
result = 49995000
Matrix 64 time in clocks 12448
$ clang++ -m64 -mno-sse 32vs64.cpp --std=c++11 -O2
$ ./a.out
result = 49995000
Add 32 time in clocks 10221
result = 49995000
Add 64 time in clocks 11270
result = 349965000
Add Mul 32 time in clocks 18342
result = 349965000
Add Mul 64 time in clocks 17693
result = 7137858
Add Div 32 time in clocks 47695
result = 7137858
Add Div 64 time in clocks 52875
result = 49995000
Matrix 32 time in clocks 15811
result = 49995000
Matrix 64 time in clocks 15168
</code></pre> |
16,998,432 | Sublime Text 2: How to get scss and Less files to have color? | <p>I'm using Sublime Text 2 and the <code>css.scss</code> and <code>css.less</code> files are in all white text - the comments, brackets, syntax - everything. If I look at my regular <code>css</code> files, they have color to differentiate all of the above. Has anyone else dealt with this? Is this some bug I'm getting? How could I add my own color or take the same settings from the regular <code>css</code> file and add it to the <code>less</code> and <code>scss</code> one's?</p> | 16,998,463 | 6 | 0 | null | 2013-06-08 10:14:48.557 UTC | 11 | 2019-01-18 09:15:21.517 UTC | null | null | null | null | 562,125 | null | 1 | 66 | sublimetext2|sublimetext | 45,501 | <p>You can set the syntax for any specific extension. Please see this:</p>
<p><a href="http://www.codechewing.com/library/set-default-syntax-highlight-for-different-filetypes-sublime-text/" rel="noreferrer">http://www.codechewing.com/library/set-default-syntax-highlight-for-different-filetypes-sublime-text/</a></p>
<p>Open the corresponding file with .scss/.less extension. From the menu at the top, goto <strong>View > Syntax > [Optional: Open all with current extension as...] > CSS</strong></p>
<p><img src="https://i.stack.imgur.com/J3gs5.jpg" alt="enter image description here"></p> |
16,839,658 | Printf width specifier to maintain precision of floating-point value | <p>Is there a <code>printf</code> width specifier which can be applied to a floating point specifier that would automatically format the output to the necessary number of <em>significant digits</em> such that when scanning the string back in, the original floating point value is acquired?</p>
<p>For example, suppose I print a <code>float</code> to a precision of <code>2</code> decimal places:</p>
<pre><code>float foobar = 0.9375;
printf("%.2f", foobar); // prints out 0.94
</code></pre>
<p>When I scan the output <code>0.94</code>, I have no standards-compliant guarantee that I'll get the original <code>0.9375</code> floating-point value back (in this example, I probably won't).</p>
<p>I would like a way tell <code>printf</code> to automatically print the floating-point value to the necessary number of <em>significant digits</em> to ensure that it can be scanned back to the original value passed to <code>printf</code>.</p>
<p>I could use some of the macros in <code>float.h</code> to <a href="https://stackoverflow.com/a/1701272/1806289">derive the maximum width</a> to pass to <code>printf</code>, but is there already a specifier to automatically print to the necessary number of <em>significant digits</em> -- or at least to the maximum width?</p> | 19,897,395 | 8 | 10 | null | 2013-05-30 15:04:36.327 UTC | 51 | 2021-09-18 13:19:19.487 UTC | 2017-05-23 12:02:44.073 UTC | null | -1 | null | 1,806,289 | null | 1 | 145 | c|floating-point|printf|c99|floating-point-precision | 335,288 | <p>I recommend @Jens Gustedt hexadecimal solution: use %a.</p>
<p>OP wants “print with maximum precision (or at least to the most significant decimal)”.</p>
<p>A simple example would be to print one seventh as in:</p>
<pre><code>#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01
</code></pre>
<hr>
<p>But let's dig deeper ...</p>
<p>Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers.
Let's assume <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format" rel="noreferrer">IEEE 754 double-precision binary</a>.
So the <code>OneSeventh = 1.0/7.0</code> results in the value below. Also shown are the preceding and following representable <code>double</code> floating point numbers.</p>
<pre><code>OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after = 0.1428571428571428 769682682968777953647077083587646484375
</code></pre>
<p>Printing the <em>exact</em> decimal representation of a <code>double</code> has limited uses.</p>
<p>C has 2 families of macros in <code><float.h></code> to help us.<br>
The first set is the number of <em>significant</em> digits to print in a string in decimal so when scanning the string back,
we get the original floating point. There are shown with the C spec's <em>minimum</em> value and a <em>sample</em> C11 compiler.</p>
<pre><code>FLT_DECIMAL_DIG 6, 9 (float) (C11)
DBL_DECIMAL_DIG 10, 17 (double) (C11)
LDBL_DECIMAL_DIG 10, 21 (long double) (C11)
DECIMAL_DIG 10, 21 (widest supported floating type) (C99)
</code></pre>
<p>The second set is the number of <em>significant</em> digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's <em>minimum</em> value and a <em>sample</em> C11 compiler. I believe available pre-C99.</p>
<pre><code>FLT_DIG 6, 6 (float)
DBL_DIG 10, 15 (double)
LDBL_DIG 10, 18 (long double)
</code></pre>
<p>The first set of macros seems to meet OP's goal of <em>significant</em> digits. But that <em>macro</em> is not always available.</p>
<pre><code>#ifdef DBL_DECIMAL_DIG
#define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else
#ifdef DECIMAL_DIG
#define OP_DBL_Digs (DECIMAL_DIG)
#else
#define OP_DBL_Digs (DBL_DIG + 3)
#endif
#endif
</code></pre>
<p>The "+ 3" was the crux of my previous answer.
Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.</p>
<p>Now how many <em>significant</em> digits to print is known and driven via <code><float.h></code>. </p>
<p>To print N <em>significant</em> decimal digits one may use various formats. </p>
<p>With <code>"%e"</code>, the <em>precision</em> field is the number of digits <em>after</em> the lead digit and decimal point.
So <code>- 1</code> is in order. Note: This <code>-1</code> is not in the initial <code>int Digs = DECIMAL_DIG;</code></p>
<pre><code>printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01
</code></pre>
<p>With <code>"%f"</code>, the <em>precision</em> field is the number of digits <em>after</em> the decimal point.
For a number like <code>OneSeventh/1000000.0</code>, one would need <code>OP_DBL_Digs + 6</code> to see all the <em>significant</em> digits.</p>
<pre><code>printf("%.*f\n", OP_DBL_Digs , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285
</code></pre>
<p>Note: Many are use to <code>"%f"</code>. That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.</p> |
4,453,352 | What goes in Model in MVVM? | <p>The things which are supposed to go into the Model are also allowed to go into the View-Model i.e. Public Properties, IDataErroInfo and INotifyPropertyChanged, then what should actually go into the model?</p> | 4,453,396 | 2 | 0 | null | 2010-12-15 18:10:51.007 UTC | 10 | 2020-09-10 21:49:04.777 UTC | null | null | null | null | 538,091 | null | 1 | 16 | wpf|mvvm | 6,712 | <h2>Model</h2>
<p>Business Data + Business Logic + Business Rules</p>
<h2>View</h2>
<p>Application UI</p>
<h2>ViewModel</h2>
<p>Wrapper Over Model which is easily readable/bindable by View using minimum Effort/Code.</p>
<ol>
<li><strong><code>IDataErrorInfo</code></strong> - Should go into ViewModel</li>
<li><strong><code>INotifyPropertyChanged</code></strong> - Should go into ViewModel. Could also go in the Model if necessary (But not recommended)</li>
<li><strong>Public Properties</strong> - Yes of course a Model should have them.</li>
</ol> |
4,720,597 | Profile bug (Error launching remote program: failed to get the task for process XXX.) | <p>Today I was messing with my Developer/Distribution settings and I seem to have changed something that I can not figure out. I am running Xcode 3.2.5 and iOS 4.2.</p>
<p>When I set to build on my device in Debug mode, I can install my app on my device with no problem</p>
<p>When I set to build on my device in Release mode, I get the following error:</p>
<pre><code>Error launching remote program: failed to get the task for process XXX.
Error launching remote program: failed to get the task for process XXX.
The program being debugged is not being run.
The program being debugged is not being run.
</code></pre>
<p>The program quits, but it seems to have installed on my device as I can then launch it with no problems.</p>
<p>In my Project profile, I have no code signing entitlements and Code Signing Identity set to iPhone Developer.</p>
<p>In my Target profile under release, I have my Code Signing Entitlements set to: "Entitlements.plist" and my Code Signing Entity set to "iPhone Distribution" which is set to my Ad Hoc profile.</p>
<p>I've searched the web and have tried restarting my device, deleting the provision profile and creating a new one, etc.</p>
<p>Any help would be appreciated, thanks.</p> | 4,720,689 | 2 | 0 | null | 2011-01-18 04:54:02.933 UTC | 7 | 2012-08-07 13:19:36.853 UTC | null | null | null | null | 563,360 | null | 1 | 33 | iphone|ios4|adhoc | 17,989 | <p>The problem is because you are trying to debug your application using distribution provisioning profile. If you want to run your application in debug mode, you have to sign it with development provisioning profile and certificate (<strong>both in build settings and in target</strong>). If you are trying to create a distributable, sign it with distribution credentials and add Entitlements.plist (again both in build settings and target).</p> |
4,727,536 | How do I stop a process running in IntelliJ such that it calls the shutdown hooks? | <p>When I run my program in IntelliJ then use the STOP button, it does not call my shutdown hooks that I've created. Is there a way in IntelliJ to have those called on shutdown?</p> | 4,727,696 | 2 | 0 | null | 2011-01-18 18:16:02.933 UTC | 8 | 2020-05-08 02:15:34.03 UTC | 2020-05-08 02:15:34.03 UTC | null | 1,402,846 | null | 252,253 | null | 1 | 78 | java|intellij-idea | 32,578 | <p>You need to use the <strong>Exit</strong> button in the <strong>Run</strong> panel, not the Stop button. Note that it will only work when Running and will not work when Debugging.</p>
<p>Here is the screenshot if you can't find it:</p>
<p><img src="https://i.stack.imgur.com/7geJA.png" alt="Exit"></p>
<p>This feature uses platform specific code and currently works on Windows and Linux only. <s>Once <a href="http://youtrack.jetbrains.net/issue/IDEA-56273" rel="noreferrer">IDEA-56273</a> is fixed, this feature should be also available on Mac.</s> It is fixed in 10.5 version of IDEA.</p> |
9,767,054 | Read the log file (*.LDF) in SQL Server 2008 | <p>I'm searching for a way to read the <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2008" rel="nofollow">SQL Server 2008</a> log file, not to show the information, but to read the meaning of the symbols and the structure of the LOG table. I'm using <code>DBCC LOG('my_table', 3)</code>.</p> | 19,081,922 | 3 | 9 | null | 2012-03-19 08:35:40.003 UTC | 4 | 2016-02-13 10:13:21.877 UTC | 2016-02-13 10:09:01.813 UTC | null | 63,550 | null | 1,265,987 | null | 1 | 5 | sql|sql-server-2008|logfiles | 81,112 | <p>See my answer in this Stack Overflow post: <em><a href="https://stackoverflow.com/questions/4153514/how-can-i-view-sql-server-2005-transaction-log-file/19081839#19081839">How can I view SQL Server 2005 Transaction log file</a></em></p>
<p>Or</p>
<p>Use this command:</p>
<pre><code>Select * from ::fn_dblog(null,null)
</code></pre>
<p>And for more information, see <em><a href="http://sqlfascination.com/2010/02/03/how-do-you-decode-a-simple-entry-in-the-transaction-log-part-1/" rel="nofollow noreferrer">How Do You Decode A Simple Entry in the Transaction Log</a></em>.</p> |
9,752,137 | How to format column to number format in Excel sheet? | <p>Below is the VBA code. Sheet2 contains all of the values in general format. After running the code, values in column 'C' of Sheet3 contain exponential values for numbers which are 13 or more digits.</p>
<p>What should be done so that column 'C' of Sheet3 does not contain exponential values?</p>
<pre><code>private Sub CommandButton1_Click()
Dim i, j, k As Variant
k = 1
For i = 1 To 30000
If Sheet2.Range("c" & i).Value >= 100 And Sheet2.Range("c" & i).Value < 1000 Then
Sheet3.Range("a" & k).Value = Sheet2.Range("a" & i).Value
Sheet3.Range("b" & k).Value = Sheet2.Range("b" & i).Value
Sheet3.Range("c" & k).Value = Sheet2.Range("c" & i).Value
k = k + 1
End If
Next
End Sub
</code></pre> | 9,752,956 | 4 | 4 | null | 2012-03-17 17:28:25.55 UTC | 1 | 2021-07-16 07:31:18.71 UTC | 2014-08-07 18:16:56.687 UTC | null | 2,541,090 | null | 1,249,645 | null | 1 | 8 | excel|vba | 133,463 | <p>This will format column A as text, B as General, C as a number.</p>
<pre><code>Sub formatColumns()
Columns(1).NumberFormat = "@"
Columns(2).NumberFormat = "General"
Columns(3).NumberFormat = "0"
End Sub
</code></pre> |
9,873,990 | Round to .5 or 1.0 in SQL | <p>I'm looking to round values like</p>
<blockquote>
<p>2.3913 -> 2.5</p>
<p>4.6667 -> 4.5</p>
<p>2.11 -> 2</p>
</blockquote>
<p>How can I manage this in SQL?</p>
<p>Thanks</p> | 9,874,054 | 2 | 4 | null | 2012-03-26 14:25:46.817 UTC | 1 | 2020-10-15 14:51:21.05 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 251,671 | null | 1 | 24 | sql|tsql|numbers|decimal|rounding | 38,776 | <pre><code>SELECT ROUND(2.2 * 2, 0) / 2
</code></pre>
<p>gets you to the nearest .5</p> |
10,030,362 | App is behaving different on iPhone 5.1 simulator and real iPhone 4 with iOS 5.1 | <h2>In a nutshell:</h2>
<p>When the title of a back-button of a navigation controller gets changed, in some cases the old title is stuck and the new title will not be displayed. This happens only in some reproduceable situations, while it works as designed in other situations.</p>
<p><strong>It depends on the hardware</strong></p>
<ul>
<li>The error happens on iPhone 3G (iOS 4.2.1) and in the simulator (iOS 5.1) </li>
<li>With identical sourcecode there is no error on iPhone 4 (iOS 5.1)</li>
</ul>
<p><strong>It depends on the word that is written to the title</strong></p>
<ul>
<li>When the button is created, and it gets from my selfwritten creating-method the same word as title that it would have got automatically (i.e. the title of the previous page on the navigation controller's stack), and when the other circumstances match, then, when trying to change the button's title at a later moment, the old text is stuck and the new title will not show up. </li>
<li>When at creation time the button gets a word as title that is different from its default-title, then every later changes of its title works fine, as long as you don't assign the default-title to it.</li>
<li>If, after a lot of successfull changes with many different titles, you put the word on the buttons title, that was its default title, then this word is stuck. Later changes will not be accepted (without any message, and only if the other circumstances match)</li>
</ul>
<p><strong>It depends on whether the button was invisible in the meantime or not.</strong></p>
<ul>
<li>If another view was pushed on the navigation controllers stack, so that the old page with the flawed button became hidden by the new page, and when the new page was popped from the stack later again which makes the button visible again, (and when the other circumstances match) then the old text was stuck and the trial to change it is ignored (without any message). </li>
<li>If the button was newer hidden, changing its title never is no problem. I works always.</li>
</ul>
<p><strong>The correct title is visible during animation</strong></p>
<ul>
<li>When the attempt to change the back-button's title was ignored due to the combination of the circumstances described above, the proper title anyhow becomes visible for about 0.3 seconds when this back-button is hit and the page's slide-to-right-animation is processed. At the beginning of the animation the old stuck title is replaced by the proper title, and the correct title is visible during the animation.</li>
</ul>
<hr>
<h2>Detailed description</h2>
<p>It's about the text on a <code>UINavigationController</code>'s back button. I change this buttons title in dependence of new language-settings. At the moment my app has a maximum of 3 view controllers in the navigation controllers stack. Each of them is a different subclass of `UITableViewController.</p>
<p>Table 1, named <code>GeneralTableVC</code> is the root view on the stack. It has no back button. It gives the user a summary of what he has stored inside the app and it displayes a toolbar with a settings-button.</p>
<p>It is the navitation controller who provides this Toolbar that is visible in Table 1. It is set to invisible in Table 2 and 3. At the moment there is only one button in that toolbar named "Settings". Touching this Settings-Button will push Table 2 onto the stack.</p>
<p>Table 2, named <code>SettingsTabVC</code> has a back button, and this is the one that makes problems in the simulator but works fine on my real iPhone 4 running iOS 5.1.</p>
<p>By touching the first row of Table 2 a new Table (Table 3) will be created and pushed onto the stack.</p>
<p>Table 3, named <code>LangSelectTableVC</code> also has a back button, but this one works pretty fine in both devices, iPhone simulator and real iPhone 4.</p>
<p>Table 3 is a language selection table that displayes a list of all available languages (at the moment just english and german). Touching a row changes settings immediately. The active view (Table 3) will be redrawn, and within a few milliseconds all texts on screen appear in the new language.</p>
<p>Redrawing the table itself is no problem, as well as the title in the navigation bar. But the text on the back button must be translated too, and this is a little bit tricky. I have done the very same trick on both back-buttons, and it works fine for the button visible on Table 3 who is directing to Table 2. But with the very same code there is a problem in the simulator (but not on a real iPhone) with the button on Table 2 who is directing to Table 1.</p>
<p>I give you some code-snippets and some screenshots to show you what I've done and what is happening:</p>
<hr>
<h2>Sourcecode</h2>
<p><strong>ARC (automatic reference counting) is in use.</strong></p>
<p>I did define a redraw-Protocol:</p>
<p><strong>Protocols.h</strong></p>
<pre><code>#ifndef ToDo_Project_Protocols_h
#define ToDo_Project_Protocols_h
@protocol redrawProt
- (void) mustRedraw;
@end
#endif
</code></pre>
<p>This is the header of Table 1:</p>
<p><strong>GeneralTableVC.h</strong></p>
<pre><code>#import <UIKit/UIKit.h>
#import "Protocols.h"
// some other imports
@interface GeneralTabVC : UITableViewController <redrawProt>
@property id<redrawProt> parent;
@property Boolean mustRedrawMyself;
@property NSString* backTitle;
@property UIBarButtonItem* myBackButton;
@property UIBarButtonItem* parBackButton;
- (id) initWithParent:(id<redrawProt>)par andBackTitle:(NSString*)bT andBackButton:(UIBarButtonItem*)bB;
@end
</code></pre>
<p>The header files of the other Tables, <code>SettingsTabVC.h</code> and <code>LangSelectTabVC.h</code> define the same properties and an identical init-function</p>
<p>The program starts here:</p>
<p><strong>part of AppDelegate.m</strong></p>
<pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// some code
GeneralTabVC* genTabCon = [[GeneralTabVC alloc] initWithParent:nil andBackTitle:nil andBackButton:nil];
UINavigationController* navCon = [[UINavigationController alloc] initWithRootViewController:genTabCon];
// some other code
}
</code></pre>
<p>Next comes the implementation of Table 1 (<code>GeneralTableVC.m</code>). The Code in Table 2 (<code>SettingsTabVC.m</code>) and Table 3 (<code>LangSelectTabVC.m</code>) is analogously the same. I don't show those parts of code that implements the protocol UITableViewDataSource. I think those parts are not really important for explaining the problem.</p>
<p>In this code you will find the macro <code>LocalizedString(keyword)</code> which does exactly the same as <code>NSLocalizedString(keyword,comment)</code>, which is translating the keyword into the desired language. My version of this macro uses a different bundel for translation (not the main bundle)</p>
<p><strong>GeneralTableVC.m</strong></p>
<pre><code>#import "GeneralTabVC.h"
#import "SettingsTabVC.h"
#define MYTITLE @"summary"
id<redrawProt> parent;
Boolean mustRedrawMyself;
NSString* backTitle;
UIBarButtonItem* myBackButton;
UIBarButtonItem* parBackButton;
@interface GeneralTabVC ()
@end
@implementation GeneralTabVC
@synthesize parent, mustRedrawMyself, backTitle, myBackButton, parBackButton;
- (void) mustRedraw {
self.mustRedrawMyself = YES;
}
- (void) redraw {
if ((self.parBackButton) && (self.backTitle)) {
// Important!
// here I change the back buttons title!
self.parBackButton.title = LocalizedString(self.backTitle);
}
if (self.parent) {
[self.parent mustRedraw];
}
self.title = LocalizedString(MYTITLE);
[self.tableView reloadData];
self.mustRedrawMyself = NO;
}
- (id) initWithParent:(id<redrawProt>)par andBackTitle:(NSString*)bT andBackButton:(UIBarButtonItem *)bB {
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
self.parent = par;
self.mustRedrawMyself = NO;
self.backTitle = bT;
self.parBackButton = bB;
}
return self;
}
- (void) toolbarInit {
// this method exists only in Table 1, not in other tables
// it creates a UIBarButtonItem, adds it to self.toolbarItems
// and makes it visible
}
- (void)SettingsAction:(id)sender {
// this method exists only in Table 1, not in other tables
// it will be executed after the user tabs on the settings-
// button in the toolbar
SettingsTabVC* setTabCon = [[SettingsTabVC alloc] initWithParent:self andBackTitle:MYTITLE andBackButton:self.myBackButton];
[self.navigationController pushViewController:setTabCon animated:YES];
}
- (void) viewDidLoad {
[super viewDidLoad];
self.title = LocalizedString(MYTITLE);
// I want an Edit-Button. Localization of this button is
// not yet done. At the moment is uses the systems language,
// not the apps language.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self toolbarInit];
}
- (void) viewWillAppear:(BOOL)animated {
// this is an important method! Maybe here is the reason for
// my problem!
[super viewWillAppear:animated];
// When ever this controllers view is going to appear, and
// when ever it is necessary to redraw it in a new language,
// it will redraw itself:
if (self.mustRedrawMyself) {
[self redraw];
}
// And here comes the buggy back button:
// When ever this controllers view is going to appear,
// a new back button will be created with a title in the
// new language:
UIBarButtonItem* BB = [[UIBarButtonItem alloc] init];
BB.title = LocalizedString(MYTITLE);
self.myBackButton = BB;
self.navigationItem.backBarButtonItem = self.myBackButton;
}
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// show toolbar:
[self.navigationController setToolbarHidden:NO animated:YES];
}
// next methods are about InterfaceOrientation and the
// UITableViewDataSource protocoll. They are not important
// for the problem.
// but maybe the very last method is important. It comes in
// different versions in the three implementation files:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// This is the version of GeneralTableVC.m (Table 1)
// It does nothing (at the actual stage of expansion, in later
// versions it will start the main business logic of this app)
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// This is the version of SettingsTableVC.m (Table 2)
// Tabbing onto row 0 of section 0 will push the
// language-selection-table (Table 3) on screen:
if (indexPath.section == 0) {
if (indexPath.row == 0) {
// create Table 3:
LangSelectTabVC* langTabCon = [[LangSelectTabVC alloc] initWithParent:self andBackTitle:MYTITLE andBackButton:self.myBackButton];
[self.navigationController pushViewController:langTabCon animated:YES];
} else {
// do something else (nothing at this stage of expansion)
}
} else {
// do something else (nothing at this stage of expansion)
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// This is the version of LangSelectTableVC.m (Table 3)
// here I do some magic to select and store the new language.
// Part of this magic is transforming indexPath.row
// into a valid language-code, putting it into the
// settings-object, and registering this object to
// NSUserDefaults
}
@end
</code></pre>
<hr>
<h2>Screenshots</h2>
<p>Starting the app on iPhone 5.1 simulator will put Table 1 (<code>GeneralTableVC</code>) on screen:</p>
<p><img src="https://i.stack.imgur.com/xESOl.png" alt="after starting the app"></p>
<p>In the toolbar on the screens button, on its right side, you find a settings-button. Pressing this button brings the next table on screen:</p>
<p><img src="https://i.stack.imgur.com/aT3yB.png" alt="settings-screen"></p>
<p>Watch the back button in the title bar. It displays the text "Summary", which is correct, since the previous table title was "Summary".</p>
<p>Now we tab onto the first row ("<code>Language English ></code>"):</p>
<p><img src="https://i.stack.imgur.com/HGho7.png" alt="before changing language"></p>
<p>Everything is fine.
Now let's change the language. Tab on "<code>German</code>":</p>
<p><img src="https://i.stack.imgur.com/ORPQb.png" alt="after changing language"></p>
<p>Wow! Everything is in German now. Even the back button has changed from "Settings" to "Einstellungen".</p>
<p>Lets tab on that "Einstellungen" back button:</p>
<p><img src="https://i.stack.imgur.com/rKfNz.png" alt="back button has wrong language in simulator"></p>
<p>Almost everthing is fine now; everything has changed into german. Everything but the back button, which still says "Summary" instead of "Überblick". And I do not understand why, because when I do exactly the same steps with exactly the same sourcecode on my real iPhone 4, the last screen looks like this:</p>
<p><img src="https://i.stack.imgur.com/SVIil.png" alt="correct langugage on real iPhone"></p>
<p>Mind the text on the back-button. On a real iPhone 4 it is the german word "Überblick" (which is what I want), but in the simulator it is the english word "Summary".
And this means to me, on some phones (like my iPhone 4) the user gets what is expected, but maybe on some other phones (maybe iPhone 4S) the user gets a buggy display.</p>
<p>Has anybody an idea what is wrong with my code?</p>
<hr>
<h2>EDITs</h2>
<p><strong>Edit:</strong> 2012-04-06 09:04 +02:00 (central european summer time)</p>
<p>I did manage to test my app on an other piece of hardware, an old iPhone 3G (iOS 4.2.1) On the old iPhone my app is behaving exactly the same way like in the simulator. Running the same app on iPhone 4 produces a different behaviour.</p>
<p>To be more precise:</p>
<ul>
<li>On iPhone 4 (iOS 5.1): App is doing what I want, no faulty behavior.</li>
<li>On Simulator (iOS 5.1): App displays wrong title on a navigation controllers back button.</li>
<li>On iPhone 3G (iOS 4.2.1): App shows the same faulty behaviour as in the simulator.</li>
</ul>
<hr>
<p><strong>Edit:</strong> 2012-04-07 10:14 +02:00 (central european summer time)</p>
<p>By watching the transition on the iPhone 3G, I fond out something interesting and maybe helpfull: When I tab on the button with the wrong text, the following happens:</p>
<ol>
<li>The wrong text is replaced by the correct text </li>
<li>After this replacement the view dissapears animated (sliding to the right) and the underlaying view becomes visible. This transition has a duration of aproximately 0.3 seconds, and in this short interval the correct text is visible in all hardware-iPhones and in the simulator too.</li>
</ol>
<p>But the question still is: Why is the wront text displayed in iPhone 3G and Simulator? Why is the correct text always visible in iPhone 4?</p>
<p>To me it looks, as if there was two buttons at the same place, one over the other. In iPhone 4 "my" custom button is in front, hiding the old systemgenerated button, but in the simulator and in iPhone 3G the old systemgenerated button is in front, hiding my custom button. But: Even if my hidden custom button is bigger (wider) than the systemgenerated, nothing of it is visible. Only when the slide-out animation starts, my button becomes visible.</p>
<hr>
<p><strong>Edit:</strong> 2012-04-07 16:38 +02:00 (central european summer time)</p>
<p>Next interesting fact:</p>
<p>This is what happened until now:</p>
<p>When the button appers for the first time (2nd screenshot, see below), I put a word as title on it, that is identic to the word it would have become before from the system. Then the user selects some action, and this button is hidden by another view. After another user-action the button is revealed again, it now it shall get a new word as title (same meaning, but new language), but on iPhone 3G and on the simulator the old title is "stronger". The new title will not be displayed. The old title sticks there.</p>
<p>This does not happen if at first appearence I write a word as title onto the button, that is different from the systemgenerated title. If the first title is different from the default-title, a later change will be executed on all iPhones and on the simulator.</p>
<p>That makes me believe, that iOS does some kind of "optimization": If, at first appearance of the button, the custom title is identic to the systemgenerated title, than a later change of the buttons title will be ignored, but only on iPhone 3G and simulator. On iPhone 4 a later change will be allowed in any case.</p>
<p>But setting a different title at the beginning to prevent the app from its faulty behaviour is not an option.</p> | 10,245,035 | 3 | 7 | null | 2012-04-05 14:17:08.96 UTC | 4 | 2012-04-20 11:06:39.05 UTC | 2012-04-10 11:37:12.093 UTC | null | 1,302,716 | null | 1,302,716 | null | 1 | 29 | iphone|ios|ios-simulator | 2,247 | <h2><strong>Apple support did answer</strong></h2>
<p>I contacted Apple support for that issue and they did answer.</p>
<p>The problem was, that the navigation bar holds all back-buttons for views on the navigation controllers stack and all this buttons needs to be updated at the same time. Updating the views that lay on the stack within their viewWillAppear-Methods is good, but trying to update the back-button at this place is no good idea.</p>
<hr>
<p><strong>The solution:</strong></p>
<p>Extend the interface of UIViewController:</p>
<pre><code>@interface UIViewController (extended)
- (NSString *)localizedKey;
@end
</code></pre>
<p>For each UIViewController that puts a view on the UINavigationController's stack implement this method:</p>
<pre><code>- (NSString*) localizedKey {
return @"a title-keyword";
}
</code></pre>
<p>Do not mess around with <code>UIBarButtonItem</code> or <code>self.navigationItem.backBarButtonItem</code> in any of the UIViewControllers.</p>
<p>When if comes that titles need to be changed, do it for ALL back buttons with this snippet of code (remember: <code>LocalizedString(key)</code> is a self-written macro similar to <code>NSLocalizedString(key,comment)</code>):</p>
<pre><code>NSArray* vcs = [self.navigationController viewControllers];
for (UIViewController* vc in vcs) {
vc.navigationItem.backBarButtonItem.title = LocalizedString([vc localizedKey]);
vc.title = LocalizedString([vc localizedKey]);
}
</code></pre>
<hr>
<p><strong>Verbatim answer of Apple Support:</strong></p>
<blockquote>
<p>We're fighting the navigation bar in forcing an update at the wrong time. Notice all the views in each view controller get updated properly. So the navigation bar needs special attention to get what we want.</p>
<p>To get this to work, you need to change the back buttons to all the view controllers on the stack at once, (at the time the user selects a language) instead of when they each appear via "viewWillAppear".</p>
<p>This requires the ability to obtain the localized key for that button in a public way. I introduced a category to UIViewController to easily adopt this:</p>
<p>@interface UIViewController (extended)<br>
- (NSString *)localizedKey;<br>
@end</p>
<p>Then your LangSelectTabVC class can change all the back buttons at once. This approach will make the button titles redraw correctly.</p>
<p>So in viewWillAppear, you won't have to update each back button. Doing it there appears to be too late for UIKit to catch that update. You also re-create a new back button when an update occurs. This is not necessary, just take the current one and change it's title:</p>
<p>NSArray *vcs = [self.navigationController viewControllers];<br>
for (UIViewController *vc in vcs)<br>
{<br>
vc.navigationItem.backBarButtonItem.title = LocalizedString([vc localizedKey]);<br>
vc.title = LocalizedString([vc localizedKey]);<br>
} </p>
<p>I've attached a modified project showing this workaround.</p>
</blockquote> |
10,174,420 | Why can't I reference System.ComponentModel.DataAnnotations? | <p>I'm trying to use DataAnnotations in my WPF project to specify a maximum length of strings, with the following:</p>
<pre><code>using System.ComponentModel.DataAnnotations;
</code></pre>
<p>However, I get the error</p>
<blockquote>
<p>The type or namespace name 'DataAnnotations' does not exist in the
namespace 'System.ComponentModel' (are you missing an assembly
reference?)</p>
</blockquote>
<p>I've seen other examples where <code>DataAnnotations</code> <em>does</em> exist in this namespace. I'm using C#4. Is there any reason why I can't use this? What can I do to fix it?</p> | 10,174,457 | 17 | 4 | null | 2012-04-16 12:50:56.783 UTC | 11 | 2022-06-16 18:04:57.757 UTC | null | null | null | null | 181,771 | null | 1 | 120 | c#|wpf|data-annotations | 154,044 | <p>You have to reference the assembly in which this namespace is defined (it is not referenced by default in the visual studio templates). Open your reference manager and add a reference to the System.ComponentModel.DataAnnotations assembly (Solution explorer -> Add reference -> Select .Net tab -> select System.ComponentModel.DataAnnotations from the list)</p> |
10,085,806 | Extracting specific columns from a data frame | <p>I have an R data frame with 6 columns, and I want to create a new dataframe that only has three of the columns.</p>
<p>Assuming my data frame is <code>df</code>, and I want to extract columns <code>A</code>, <code>B</code>, and <code>E</code>, this is the only command I can figure out:</p>
<pre><code> data.frame(df$A,df$B,df$E)
</code></pre>
<p>Is there a more compact way of doing this?</p> | 29,736,003 | 10 | 1 | null | 2012-04-10 02:24:04.437 UTC | 129 | 2020-06-30 14:20:29.953 UTC | 2020-04-16 22:35:01.54 UTC | null | 6,461,462 | Aren Cambre | 425,477 | null | 1 | 432 | r|dataframe|r-faq | 1,496,055 | <p>Using the <a href="http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html">dplyr</a> package, if your data.frame is called <code>df1</code>:</p>
<pre><code>library(dplyr)
df1 %>%
select(A, B, E)
</code></pre>
<p>This can also be written without the <code>%>%</code> pipe as:</p>
<pre><code>select(df1, A, B, E)
</code></pre> |
8,192,185 | Using std::array with initialization lists | <p>Unless I am mistaken, it should be possible to create a std:array in these ways:</p>
<pre><code>std::array<std::string, 2> strings = { "a", "b" };
std::array<std::string, 2> strings({ "a", "b" });
</code></pre>
<p>And yet, using GCC 4.6.1 I am unable to get any of these to work. The compiler simply says:</p>
<pre><code>expected primary-expression before ',' token
</code></pre>
<p>and yet initialization lists work just fine with std::vector. So which is it? Am I mistaken to think std::array should accept initialization lists, or has the GNU Standard C++ Library team goofed?</p> | 8,192,275 | 3 | 6 | null | 2011-11-19 05:46:51.007 UTC | 10 | 2021-08-12 11:15:14.587 UTC | 2011-11-19 06:32:35.037 UTC | null | 897,778 | null | 897,778 | null | 1 | 56 | c++|c++11|libstdc++ | 43,354 | <p><code>std::array</code> is funny. It is defined basically like this:</p>
<pre><code>template<typename T, int size>
struct std::array
{
T a[size];
};
</code></pre>
<p>It is a struct which contains an array. It does not have a constructor that takes an initializer list. But <code>std::array</code> is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array <em>inside</em> the struct, you need a second set of curly braces:</p>
<pre><code>std::array<std::string, 2> strings = {{ "a", "b" }};
</code></pre>
<p>Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.</p> |
7,778,723 | What are the .db-shm and .db-wal extensions in Sqlite databases? | <p>I am seeing some strange behavior with my application and the state of its database file after running some tests that close the database, delete it, and replace it with a test fixture. When I examine the database file with a tool on my debugging PC, it doesn't match what the application itself seems to be reporting. It's possible that this strange behavior is related to <a href="http://code.google.com/p/android/issues/detail?id=13727" rel="noreferrer">this bug</a>.</p>
<p>I noticed that there are two files with the same base name as the database (with the normal <code>.db</code> extension.) The file extensions are <code>.db-shm</code> and <code>.db-wal</code>, and each is newer than the <code>.db</code> file's timestamp. </p>
<p>I assume that these are some type of temporary files. However, I am wondering if the application is terminated, shouldn't they be deleted? More importantly, I assume whatever data is stored in them is updated inside the <code>.db</code> file before the application is terminated by the operating system. Is this correct?</p> | 7,779,752 | 3 | 2 | null | 2011-10-15 15:25:03.107 UTC | 14 | 2022-04-28 17:41:23.69 UTC | 2011-10-15 18:09:16.26 UTC | null | 403,455 | null | 403,455 | null | 1 | 90 | android|sqlite|file-extension | 94,747 | <p>You are correct, these are temporary files created by SQLite. If you are manually deleting the main db you should probably delete these too. From what I can gather the WAL is a replacement for the rollback journal that enables SQLite to rollback changes when a transaction fails. How SQLite uses them and why they are kept around for so long is up to the authors of SQLite but in general SQLite seems pretty rock solid so I wouldn't worry too much about them. For more info take a look here:</p>
<p><a href="http://www.sqlite.org/fileformat2.html#walindexformat" rel="noreferrer">http://www.sqlite.org/fileformat2.html#walindexformat</a></p>
<p>These files are a new feature of SQLite 3.7. I'm not sure if their existence relates to the bug you point out but the bug report suggests a work-around anyway.</p>
<p><strong>UPDATE:</strong></p>
<p>Better documentation about the WAL is here:</p>
<p><a href="https://www.sqlite.org/wal.html" rel="noreferrer">https://www.sqlite.org/wal.html</a></p>
<p>The contents of the WAL are periodically moved to the DB file but this is not guaranteed to occur each time the process exits. Thus when WAL is enabled each SQLite DB consists of two files on disk that must be preserved, both the .db file and the .db-wal file.</p>
<p>The .db-shm file is a shared memory file that contains only temporary data.</p> |
11,686,854 | How to register a Zend\Log Instance in the ServiceManager in ZF2 | <p>I am wondering what is the best way to initiate and re-use a logger instance through the ServiceManager in ZF2.
Of course I can do a simple method to be used in any class, like: </p>
<pre><code>public function getLogger () {
$this->logger = new Logger();
$this->logger->addWriter(new Writer\Stream('/log/cms_errors.log'));
return $logger;
}
</code></pre>
<p>but I was wondering what is the best way to register a similar structure in the global.php.
So far I can </p>
<p>add the following to global.php</p>
<pre><code>'Zend\Log'=>array(
'timestampFormat' => 'Y-m-d',
array(
'writerName' => 'Stream',
'writerParams' => array(
'stream' => '/log/zend.log',
),
'formatterName' => 'Simple',
),
),
</code></pre>
<p>If I try invoking it through: </p>
<pre><code>$this->getServiceLocator()->get('Zend\Log')
</code></pre>
<p>I get a : </p>
<pre><code>Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Zend\Log
</code></pre> | 12,886,079 | 5 | 0 | null | 2012-07-27 11:28:04.097 UTC | 10 | 2014-06-20 19:15:14.537 UTC | 2012-09-19 00:10:05.4 UTC | null | 1,483,513 | null | 277,861 | null | 1 | 7 | zend-framework|zend-framework2|zend-log | 11,257 | <p>Add the following data to 'global.php'</p>
<pre><code>'service_manager' => array(
'factories' => array(
'Zend\Log' => function ($sm) {
$log = new Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream('./data/logs/logfile');
$log->addWriter($writer);
return $log;
},
),
),
</code></pre>
<p>And then you'll be able to call</p>
<pre><code>$this->getServiceLocator()->get('Zend\Log')->info('Something...');
</code></pre> |
12,003,660 | Javascript DateDiff | <p>I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (<a href="https://stackoverflow.com/questions/327429/whats-the-best-way-to-calculate-date-difference-in-javascript">What's the best way to calculate date difference in Javascript</a>) and I also looked at this tutorial (<a href="http://www.javascriptkit.com/javatutors/datedifference.shtml" rel="nofollow noreferrer">http://www.javascriptkit.com/javatutors/datedifference.shtml</a>) but I can't seem to get it.</p>
<p>Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?</p>
<pre><code>//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
</code></pre> | 12,003,702 | 4 | 0 | null | 2012-08-17 10:00:43.877 UTC | 1 | 2019-03-03 10:15:30.853 UTC | 2019-03-03 10:15:30.853 UTC | null | 4,519,059 | null | 1,227,427 | null | 1 | 8 | javascript|date|datediff | 71,749 | <p>Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields <code>NaN</code>.</p>
<p>The second trry has no closing <code>)</code>. Apart from that, you're calling <code>getTime</code> on strings. You'd need to use <code>new Date(...).getTime()</code>. Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.</p> |
11,923,317 | creating django forms | <p>I'm struggling to get my head round django forms.. I've been reading various documentation but just can't quite grasp the concepts. I have got to grips with models, views and templates. What I am trying to do is to create a form with various fields composing of dropdown lists and checkboxes which are populated by values in a database. </p>
<p>I have a working app called vms. Using the models.py I have a built a simple schema that holds size and type. Size consists of 'small', 'medium' & 'large'. Type is 'windows' & 'linux'. Using the admin site, I can add an extra size, for example 'Extra Large'.</p>
<p>What I would like to do is create a form that has a drop down list of the vm sizes. If an extra size gets added via the admin site, I would like that size to appear in the drop down list.</p>
<p>I would submit my attempts at the code, but actually am struggling with the concepts. Can anyone help guide me in how to accomplish the above?</p>
<p>Thanks
Oli</p> | 11,924,616 | 3 | 2 | null | 2012-08-12 15:19:50.823 UTC | 14 | 2020-07-24 06:10:16.963 UTC | null | null | null | null | 1,436,318 | null | 1 | 15 | python|django|django-forms | 16,337 | <p>Forms are just a tool to simplify and speed-up (the development of) the process of fetching POST data from the request. A manual way would be to do <code>request.POST.get('somefield')</code> for all the fields there are in some HTML form. But Django can do better than that...</p>
<p>In its essence, a Form class holds a number of Fields and performs these tasks:</p>
<ol>
<li>display HTML inputs,</li>
<li>collect and validate data when user submits it,</li>
<li>if fields don't validate, return the values along with error messages to HTML,</li>
<li>if all fields validate, provide <code>form.cleaned_data</code> dictionary as a convenient way to access these values in view.</li>
</ol>
<p>With these values, I could then manually create a new instance of a <code>MyModel</code> and save it. Of course, I would have to define a Field in the Form for every Field in MyModel model.</p>
<p>This means that, basically, I <em>could</em> do something like this:<br>
(forgive me for not testing this code, so I can't vouch that it's 100% correct)</p>
<pre><code>models.py:
class MyModel(models.Model):
field1 = models.CharField(max_length=40, blank=False, null=False)
field2 = models.CharField(max_length=60, blank=True, null=True)
forms.py:
class FormForMyModel(forms.Form):
form_field1 = forms.CharField(max_length=40, required=True)
form_field2 = forms.CharField(max_length=60, required=False)
views.py:
def create_a_my_model(request):
if request.method == 'POST':
form = FormForMyModel(request.POST)
if form.is_valid():
my_model = MyModel()
my_model.field1 = form.cleaned_data.get('form_field1', 'default1')
my_model.field2 = form.cleaned_data.get('form_field2', 'default2')
my_model.save()
else:
form = FormForMyModel()
context_data = {'form': form}
return HttpResponse('templtate.html', context_data)
</code></pre>
<p>(this could be written with a few lines of code less, but it's meant to be as clear as possible)</p>
<p>Notice there are no relation between model Fields and form Fields! We have to manually assign values to MyModel instance when creating it.</p>
<p>The above example outlines generic form workflow. It is often needed in complex situations, but not in such a simple one as is this example.</p>
<p>For this example (and a LOT of real-world examples), Django can do better than that...</p>
<p>You can notice two annoying issues in the above example:</p>
<ol>
<li>I have to define Fields on <code>MyModel</code> and Fields on <code>FormForMyModel</code> separately. However, there is a lot of similarity between those two groups (types) of Fields, so that's kind of duplicate work. The similarity grows when adding labels, validators, etc.</li>
<li>creating of <code>MyModel</code> instance is a bit silly, having to assign all those values manually.</li>
</ol>
<p>This is where a <strong>ModelForm</strong> comes in.</p>
<p>These act basically just like a regular form (actually, they <em>are</em> extended from regular forms), but they can save me some of the work (the two issues I just outlined, of course :) ).</p>
<p>So back to the two issues: </p>
<ol>
<li><p>Instead of defining a form Field for each model Field, I simply define <code>model = MyModel</code> in the the <code>Meta</code> class. This instructs the Form to automatically generate form Fields from model Fields.</p></li>
<li><p>Model forms have <code>save</code> method available. This can be used to create instance of model in one line in the view, instead of manually assigning field-by-field.</p></li>
</ol>
<p>So, lets make the example above with a <code>ModelForm</code>:</p>
<pre><code>models.py:
class MyModel(models.Model):
field1 = models.CharField(max_length=40, blank=False, null=False)
field2 = models.CharField(max_length=60, blank=True, null=True)
forms.py:
class MyModelForm(forms.ModelForm): # extending ModelForm, not Form as before
class Meta:
model = MyModel
views.py:
def create_a_my_model(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
# save the model to database, directly from the form:
my_model = form.save() # reference to my_model is often not needed at all, a simple form.save() is ok
# alternatively:
# my_model = form.save(commit=False) # create model, but don't save to database
# my.model.something = whatever # if I need to do something before saving it
# my.model.save()
else:
form = MyModelForm()
context_data = {'form': form}
return HttpResponse('templtate.html', context_data)
</code></pre>
<p>Hope this clears up the usage of Django forms a bit.</p>
<p>Just one more note - it is perfectly ok to define form Fields on a <code>ModelForm</code>. These will not be used in <code>form.save()</code> but can still be access with <code>form.cleaned_data</code> just as in a regular Form.</p> |
11,689,557 | Delete all views from Sql Server | <p>By using this statement in SQL Server: </p>
<pre><code>EXEC sp_msforeachtable 'DROP TABLE ?'
</code></pre>
<p>I know it's possible to delete all tables at once.</p>
<p>Is there a similar statement for views? I tried this hoping to be lucky:
EXEC sp_msforeachview 'DROP VIEW ?' but it doesn't work!</p> | 11,689,661 | 7 | 1 | null | 2012-07-27 14:11:42.227 UTC | 9 | 2018-05-02 17:42:08.757 UTC | 2017-11-21 07:04:12.403 UTC | null | 2,451,726 | null | 1,464,026 | null | 1 | 35 | sql|sql-server-2008|sp-msforeachtable | 52,489 | <p>Here you have, no cursor needed:</p>
<pre><code>DECLARE @sql VARCHAR(MAX) = ''
, @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(v.name) +';' + @crlf
FROM sys.views v
PRINT @sql;
EXEC(@sql);
</code></pre> |
11,697,943 | When should one use CONNECT and GET HTTP methods at HTTP Proxy Server? | <p>I'm building a WebClient library. Now I'm implementing a proxy feature, so I am making some research and I saw some code using the <code>CONNECT</code> method to request a URL.</p>
<p>But checking it within my web browser, it doesn't use the <code>CONNECT</code> method but calls the GET method instead.</p>
<p>So I'm confused. When I should use both methods?</p> | 11,698,002 | 4 | 0 | null | 2012-07-28 03:12:00.047 UTC | 27 | 2021-04-13 21:36:32.693 UTC | 2016-01-12 20:27:28.113 UTC | null | 432,681 | null | 1,015,090 | null | 1 | 85 | proxy|httpwebrequest|http-request|http-proxy|proxy-server | 104,155 | <p>A CONNECT request urges your proxy to establish an HTTP tunnel to the remote end-point.
<strong>Usually</strong> is it used for SSL connections, though it can be used with HTTP as well (used for the purposes of proxy-chaining and tunneling)</p>
<pre><code>CONNECT www.google.com:443
</code></pre>
<p>The above line opens a connection from your proxy to www.google.com on port 443.
After this, content that is sent by the client is forwarded by the proxy to <code>www.google.com:443</code>.</p>
<p>If a user tries to retrieve a page <a href="http://www.google.com">http://www.google.com</a>, the proxy can send the exact same request and retrieve response for him, on his behalf.</p>
<p>With SSL(HTTPS), only the two remote end-points understand the requests, and the proxy cannot decipher them. Hence, all it does is open that tunnel using CONNECT, and lets the two end-points (webserver and client) talk to each other directly.</p>
<p><strong>Proxy Chaining:</strong></p>
<p>If you are chaining 2 proxy servers, this is the sequence of requests to be issued.</p>
<pre><code>GET1 is the original GET request (HTTP URL)
CONNECT1 is the original CONNECT request (SSL/HTTPS URL or Another Proxy)
User Request ==CONNECT1==> (Your_Primary_Proxy ==CONNECT==> AnotherProxy-1 ... ==CONNECT==> AnotherProxy-n) ==GET1(IF is http)/CONNECT1(IF is https)==> Destination_URL
</code></pre> |
11,692,613 | Python - sum values in dictionary | <p>I have got pretty simple list:</p>
<pre><code>example_list = [
{'points': 400, 'gold': 2480},
{'points': 100, 'gold': 610},
{'points': 100, 'gold': 620},
{'points': 100, 'gold': 620}
]
</code></pre>
<p>How can I sum all <em>gold</em> values? I'm looking for nice oneliner.</p>
<p>Now I'm using this code (but it's not the best solution):</p>
<pre><code>total_gold = 0
for item in example_list:
total_gold += example_list["gold"]
</code></pre> | 11,692,630 | 5 | 3 | null | 2012-07-27 17:21:44.23 UTC | 28 | 2022-02-25 12:07:13.093 UTC | 2012-07-27 17:27:40.403 UTC | null | 382,971 | null | 382,971 | null | 1 | 91 | python|list|dictionary | 106,323 | <pre><code>sum(item['gold'] for item in myList)
</code></pre> |
11,686,690 | Handle ModelState Validation in ASP.NET Web API | <p>I was wondering how I can achieve model validation with ASP.NET Web API. I have my model like so:</p>
<pre><code>public class Enquiry
{
[Key]
public int EnquiryId { get; set; }
[Required]
public DateTime EnquiryDate { get; set; }
[Required]
public string CustomerAccountNumber { get; set; }
[Required]
public string ContactName { get; set; }
}
</code></pre>
<p>I then have a Post action in my API Controller:</p>
<pre><code>public void Post(Enquiry enquiry)
{
enquiry.EnquiryDate = DateTime.Now;
context.DaybookEnquiries.Add(enquiry);
context.SaveChanges();
}
</code></pre>
<p>How do I add <code>if(ModelState.IsValid)</code> and then handle the error message to pass down to the user?</p> | 11,724,405 | 11 | 0 | null | 2012-07-27 11:16:42.95 UTC | 44 | 2022-01-27 10:12:24.623 UTC | 2017-05-15 07:45:20.22 UTC | null | 492,336 | null | 1,005,030 | null | 1 | 112 | c#|asp.net-web-api | 132,524 | <p>For separation of concern, I would suggest you use action filter for model validation, so you don't need to care much how to do validation in your api controller:</p>
<pre><code>using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace System.Web.Http.Filters
{
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
</code></pre> |
11,977,102 | Order data frame rows according to vector with specific order | <p>Is there an easier way to ensure that a data frame's rows are ordered according to a "target" vector as the one I implemented in the short example below?</p>
<pre><code>df <- data.frame(name = letters[1:4], value = c(rep(TRUE, 2), rep(FALSE, 2)))
df
# name value
# 1 a TRUE
# 2 b TRUE
# 3 c FALSE
# 4 d FALSE
target <- c("b", "c", "a", "d")
</code></pre>
<p>This somehow seems to be a bit too "complicated" to get the job done:</p>
<pre><code>idx <- sapply(target, function(x) {
which(df$name == x)
})
df <- df[idx,]
rownames(df) <- NULL
df
# name value
# 1 b TRUE
# 2 c FALSE
# 3 a TRUE
# 4 d FALSE
</code></pre> | 11,977,256 | 6 | 0 | null | 2012-08-15 20:53:10.033 UTC | 58 | 2021-01-12 00:41:59.13 UTC | 2019-01-24 13:26:37.887 UTC | null | 2,370,483 | null | 989,691 | null | 1 | 200 | r|sorting|dataframe | 171,500 | <p>Try <code>match</code>:</p>
<pre><code>df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]
name value
2 b TRUE
3 c FALSE
1 a TRUE
4 d FALSE
</code></pre>
<p>It will work as long as your <code>target</code> contains exactly the same elements as <code>df$name</code>, and neither contain duplicate values.</p>
<p>From <code>?match</code>:</p>
<pre><code>match returns a vector of the positions of (first) matches of its first argument
in its second.
</code></pre>
<p>Therefore <code>match</code> finds the row numbers that matches <code>target</code>'s elements, and then we return <code>df</code> in that order.</p> |
20,038,673 | My html page is not scrolling in browsers | <p>The page on my website is not scrolling. If there are more content than screen can fit you can not actually see it because scroll is not working. I'm not and CSS guru and I don't know if the problem is actually with CSS or HTML. </p>
<p>I've spend some time trying to understand the problem but i'm not a CSS guru so I hope someone can help me. The page is using tweeter-bootstrap and custom theme for it (which i did not write). When I don't include theme CSS file scrolling is working fine. </p>
<p>Part of my theme CSS file:</p>
<pre><code>body {
color: #000;
font-family: 'Play', sans-serif;
font-size: 16px;
line-height: 25px;
background: #e0dbcd url('../images/bg.jpg');
letter-spacing:0.2px;
overflow: hidden;
}
</code></pre> | 20,038,715 | 5 | 6 | null | 2013-11-18 01:39:36.017 UTC | 3 | 2020-03-29 18:36:55.173 UTC | 2013-11-20 13:04:11.093 UTC | null | 492,620 | null | 375,373 | null | 1 | 15 | css|html|twitter-bootstrap|twitter-bootstrap-3 | 53,641 | <p>remove <code>overflow: hidden;</code> from <code>body</code> in the bootstrap-theme.css file.</p> |
3,303,312 | How do I convert a string to a valid variable name in Python? | <p>I need to convert an arbitrary string to a string that is a valid variable name in Python.</p>
<p>Here's a very basic example:</p>
<pre><code>s1 = 'name/with/slashes'
s2 = 'name '
def clean(s):
s = s.replace('/', '')
s = s.strip()
return s
# the _ is there so I can see the end of the string
print clean(s1) + '_'
</code></pre>
<p>That is a very naive approach. I need to check if the string contains invalid variable name characters and replace them with ''</p>
<p>What would be a pythonic way to do this?</p> | 3,303,361 | 4 | 3 | null | 2010-07-21 19:59:30.433 UTC | 8 | 2022-08-05 10:00:44.063 UTC | 2022-08-05 10:00:44.063 UTC | null | 4,865,723 | null | 89,766 | null | 1 | 34 | python|validation|string|variables | 14,120 | <p><a href="http://docs.python.org/reference/lexical_analysis.html#identifiers" rel="noreferrer">According to Python</a>, an identifier is a letter or underscore, followed by an unlimited string of letters, numbers, and underscores:</p>
<pre><code>import re
def clean(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
return s
</code></pre>
<p>Use like this:</p>
<pre><code>>>> clean(' 32v2 g #Gmw845h$W b53wi ')
'v2gGmw845hWb53wi'
</code></pre> |
3,333,461 | Regular expression which matches a pattern, or is an empty string | <p>I have the following Regular Expression which matches an email address format:</p>
<pre><code>^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$
</code></pre>
<p>This is used for validation with a form using JavaScript. However, this is an optional field. Therefore how can I change this regex to match an email address format, or an empty string?</p>
<p>From my limited regex knowledge, I think <code>\b</code> matches an empty string, and <code>|</code> means "Or", so I tried to do the following, but it didn't work:</p>
<pre><code>^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$|\b
</code></pre> | 3,333,525 | 4 | 4 | null | 2010-07-26 09:04:49.053 UTC | 21 | 2018-08-09 18:06:38.627 UTC | 2012-07-27 09:55:09.807 UTC | null | 225,037 | null | 370,103 | null | 1 | 115 | javascript|regex|email-validation|string | 145,560 | <p>To match <code>pattern</code> or an empty string, use</p>
<pre><code>^$|pattern
</code></pre>
<h3>Explanation</h3>
<ul>
<li><code>^</code> and <code>$</code> are the beginning and end of the string anchors respectively.</li>
<li><code>|</code> is used to denote alternates, e.g. <code>this|that</code>.</li>
</ul>
<h3>References</h3>
<ul>
<li><a href="http://www.regular-expressions.info/anchors.html" rel="noreferrer">regular-expressions.info/Anchors</a> and <a href="http://www.regular-expressions.info/alternation.html" rel="noreferrer">Alternation</a></li>
</ul>
<hr>
<h3>On <code>\b</code></h3>
<p><code>\b</code> in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at <em>very specific places</em>, namely at the boundaries of a word.</p>
<p>That is, <code>\b</code> is located:</p>
<ul>
<li>Between consecutive <code>\w</code> and <code>\W</code> (either order):
<ul>
<li>i.e. between a word character and a non-word character</li>
</ul></li>
<li>Between <code>^</code> and <code>\w</code>
<ul>
<li>i.e. at the beginning of the string if it starts with <code>\w</code></li>
</ul></li>
<li>Between <code>\w</code> and <code>$</code>
<ul>
<li>i.e. at the end of the string if it ends with <code>\w</code></li>
</ul></li>
</ul>
<h3>References</h3>
<ul>
<li><a href="http://www.regular-expressions.info/wordboundaries.html" rel="noreferrer">regular-expressions.info/Word Boundaries</a></li>
</ul>
<hr>
<h3>On using regex to match e-mail addresses</h3>
<p>This is not trivial depending on specification.</p>
<h3>Related questions</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses"> What is the best regular expression for validating email addresses? </a></li>
<li><a href="https://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard"> Regexp recognition of email address hard? </a></li>
<li><a href="https://stackoverflow.com/questions/3232/how-far-should-one-take-e-mail-address-validation"> How far should one take e-mail address validation? </a></li>
</ul> |
3,846,296 | How to overload the operator++ in two different ways for postfix a++ and prefix ++a? | <p>How to overload the operator++ in two different ways for postfix <code>a++</code> and prefix <code>++a</code>?</p> | 3,846,374 | 5 | 2 | null | 2010-10-02 15:09:55.98 UTC | 39 | 2018-07-04 22:11:26.137 UTC | 2015-06-16 08:27:17.03 UTC | null | 895,245 | null | 457,445 | null | 1 | 115 | c++|operator-overloading | 94,426 | <p>Should look like this:</p>
<pre><code>class Number
{
public:
Number& operator++ () // prefix ++
{
// Do work on this. (increment your object here)
return *this;
}
// You want to make the ++ operator work like the standard operators
// The simple way to do this is to implement postfix in terms of prefix.
//
Number operator++ (int) // postfix ++
{
Number result(*this); // make a copy for result
++(*this); // Now use the prefix version to do the work
return result; // return the copy (the old) value.
}
};
</code></pre> |
3,607,593 | Is it faster to add to a collection then sort it, or add to a sorted collection? | <p>If I have a <code>Map</code> like this:</p>
<pre><code>HashMap<Integer, ComparableObject> map;
</code></pre>
<p>and I want to obtain a collection of values sorted using natural ordering, which method is fastest?</p>
<h2>(A)</h2>
<p>Create an instance of a sortable collection like <code>ArrayList</code>, add the values, then sort it:</p>
<pre><code>List<ComparableObject> sortedCollection = new ArrayList<ComparableObject>(map.values());
Collections.sort(sortedCollection);
</code></pre>
<h2>(B)</h2>
<p>Create an instance of an ordered collection like <code>TreeSet</code>, then add the values:</p>
<pre><code>Set<ComparableObject> sortedCollection = new TreeSet<ComparableObject>(map.values());
</code></pre>
<p>Note that the resulting collection is never modified, so the sorting only needs to take place once.</p> | 3,607,684 | 7 | 6 | null | 2010-08-31 09:12:46.327 UTC | 22 | 2020-08-07 18:59:23.89 UTC | null | null | null | null | 402,033 | null | 1 | 84 | java|sorting|collections | 35,419 | <p>TreeSet has a <code>log(n)</code> time complexity guarantuee for <code>add()/remove()/contains()</code> methods.
Sorting an <code>ArrayList</code> takes <code>n*log(n)</code> operations, but <code>add()/get()</code> takes only <code>1</code> operation.</p>
<p>So if you're mainly retrieving, and don't sort often, <code>ArrayList</code> is the better choice. If you sort often but dont retrieve that much <code>TreeSet</code> would be a better choice.</p> |
3,601,013 | UITableViewCell separator not showing up | <p>I made a custom UITableViewCell in IB, but for some reason, despite the single line option for separator being selected, there are no separator lines on my table.</p>
<p>Has this happened to any of you before? What gives?</p>
<p>Thanks!</p> | 3,601,169 | 8 | 0 | null | 2010-08-30 13:59:32.143 UTC | 5 | 2016-07-08 16:03:32.86 UTC | null | null | null | null | 323,929 | null | 1 | 33 | iphone|uitableview|cell|separator | 21,133 | <p>Is the UITableViewCell in IB associated with a UITableViewCell subclass that overrides <code>drawRect:</code>? If so, make sure you are calling the super implementation, as that's what draws the line at the bottom. If you are overriding <code>layoutSubviews</code> make sure no views are obscuring the bottom of the cell.</p> |
3,590,165 | How can I convert each item in the list to string, for the purpose of joining them? | <p>I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,</p>
<pre><code>myList.append(munfunc())
</code></pre>
<p>How should I convert the returned result to a string in order to join it with the list?</p>
<p>Do I need to do the following for every integer value:</p>
<pre><code>myList.append(str(myfunc()))
</code></pre>
<p>Is there a more Pythonic way to solve casting problems?</p> | 3,590,168 | 9 | 0 | null | 2010-08-28 09:07:38.59 UTC | 49 | 2022-07-01 01:07:31.463 UTC | 2022-07-01 01:07:31.463 UTC | null | 523,612 | null | 429,507 | null | 1 | 366 | python|string|list | 480,464 | <p>Calling <code>str(...)</code> is the Pythonic way to convert something to a string.</p>
<p>You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with <code>,</code>:</p>
<pre><code>print(','.join(str(x) for x in list_of_ints))
</code></pre> |
3,958,615 | Import file size limit in PHPMyAdmin | <p>I have changed all the php.ini parameters I know:
<code>upload_max_filesize</code>, <code>post_max_size</code>.</p>
<p>Why am I still seeing 2MB?</p>
<p>Im using Zend Server CE, on a Ubuntu VirtualBox over a Windows 7 host.</p> | 3,958,659 | 29 | 4 | null | 2010-10-18 11:24:55.727 UTC | 120 | 2021-11-17 04:13:23.91 UTC | 2018-03-17 01:37:49.23 UTC | null | 5,771,029 | null | 234,253 | null | 1 | 368 | php|mysql|phpmyadmin | 1,078,514 | <p>You probably didn't restart your server ;)</p>
<p>Or you modified the wrong <code>php.ini</code>.</p>
<p>Or you actually managed to do both ^^</p> |
7,932,060 | Create a vertical Menu in a Wpf | <p>How is it possible to create a vertical menu on the left side of the window in Visual Studio (in a wpf) with xaml like the one in <a href="http://www.wpftutorial.net/">http://www.wpftutorial.net/</a>? I try the code:</p>
<pre><code><Menu DockPanel.Dock="Left" VerticalAlignment="Top" Background="Gray" BorderBrush="Black">
</code></pre>
<p>but it does not the task, since it presents a horizontal menu on the top.</p>
<p>It is not required to be done definitely by the control menu. If any other control with similar appearance is appropriate, it is acceptable. </p> | 7,932,115 | 4 | 3 | null | 2011-10-28 16:27:37.33 UTC | 5 | 2022-01-08 17:54:42.8 UTC | 2011-10-28 16:36:14.697 UTC | null | 41,071 | null | 954,724 | null | 1 | 18 | wpf|xaml | 44,911 | <p>Sure, just change <code>MenuItem.ItemsPanel</code> to use a Vertical StackPanel instead of the Default Horizontal one</p>
<pre><code><Menu>
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</Menu.ItemsPanel>
</Menu>
</code></pre> |
7,890,488 | How to perform a LEFT JOIN in SQL Server between two SELECT statements? | <p>I have two SELECT statements in SQL Server like these:</p>
<pre><code>(SELECT [UserID] FROM [User])
(SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043)
</code></pre>
<p>I want to perform a LEFT JOIN between these two SELECT statements on [UserID] attribute and [TailUser] attribute. I want to join existent records in second query with the corresponding records in first query and NULL value for absent records. How can I do this?</p> | 7,890,528 | 4 | 1 | null | 2011-10-25 14:03:18.64 UTC | 9 | 2021-04-29 13:14:44.073 UTC | 2011-10-25 14:42:39.6 UTC | null | 13,302 | null | 774,437 | null | 1 | 43 | sql|sql-server-2008|relational-database | 183,204 | <pre><code>SELECT * FROM
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser
</code></pre> |
8,296,170 | What is a .pid file and what does it contain? | <p>I recently come across a file with the extension .pid and explored inside it but didn't find much. The documentation says:</p>
<blockquote>
<p>A Pid-File is a file containing the process identification number (pid) that is stored in a well-defined location of the filesystem thus allowing other programs to find out the pid of a running script.</p>
</blockquote>
<p>Can anyone shed more light on this, or guide me to details of what's contained in the pid file?</p> | 8,296,204 | 4 | 0 | null | 2011-11-28 13:01:52.643 UTC | 56 | 2022-03-23 20:41:50.91 UTC | 2017-08-05 00:35:06.743 UTC | null | 4,694,621 | null | 468,896 | null | 1 | 233 | linux|unix|pid | 199,054 | <p>The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using <code>cat filename.pid | xargs kill</code></p> |
4,640,934 | make characters optional in regular expression | <p>I am trying to validate a (US) phone number with no extra characters in it. so the format is 1-555-555-5555 with no dashes, spaces, etc and the 1 is optional. However, my regular expression will ONLY except numbers with the leading 1 and says numbers without it are invalid. Here is what I am using where did I go wrong?</p>
<pre><code>"^(1)\\d{10}$"
</code></pre> | 4,640,950 | 3 | 2 | null | 2011-01-09 18:30:01.12 UTC | 1 | 2014-11-09 01:21:49.553 UTC | null | null | null | null | 384,306 | null | 1 | 22 | java|regex | 38,074 | <p>Use:</p>
<pre><code>"^1?\\d{10}$"
</code></pre>
<p>The ? means "optional".</p> |
4,487,546 | Do while loop in SQL Server 2008 | <p>Is there any method for implement <code>do while</code> loop in SQL server 2008?</p> | 4,487,576 | 5 | 3 | null | 2010-12-20 07:03:20.817 UTC | 41 | 2017-09-22 11:08:35.15 UTC | 2013-08-08 03:38:20.93 UTC | null | 1,750,719 | null | 1,750,719 | null | 1 | 136 | sql-server|sql-server-2008|loops|while-loop|do-while | 584,513 | <p>I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.</p>
<p>Examples are taken from here: <a href="http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/" rel="noreferrer">http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/</a></p>
<blockquote>
<ol>
<li><p>Example of WHILE Loop</p>
<pre><code>DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
END
GO
</code></pre>
<p>ResultSet:</p>
<pre><code>1
2
3
4
5
</code></pre></li>
<li><p>Example of WHILE Loop with BREAK keyword</p>
<pre><code>DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
IF @intFlag = 4
BREAK;
END
GO
</code></pre>
<p>ResultSet:</p>
<pre><code>1
2
3
</code></pre></li>
<li><p>Example of WHILE Loop with CONTINUE and BREAK keywords</p>
<pre><code>DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
CONTINUE;
IF @intFlag = 4 -- This will never executed
BREAK;
END
GO
</code></pre>
<p>ResultSet:</p>
<pre><code>1
2
3
4
5
</code></pre></li>
</ol>
</blockquote>
<p>But try to <strong><em>avoid loops</em></strong> at database level.
<a href="http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/" rel="noreferrer">Reference</a>.</p> |
4,617,914 | How to create a "unique" constraint on a boolean MySQL column? | <p>I would like to add a <code>BOOLEAN</code> column to a MySQL table which will be named <code>is_default</code>. In this column, only one record can have <code>is_default</code> set to <code>true</code>.</p>
<p>How can I add this constraint to my column with MySQL?</p>
<p>Thanks!</p>
<hr>
<p>UPDATE</p>
<p>If it is not a constraint that I should add. How are we dealing with this type of problem on DBs?</p> | 4,618,525 | 6 | 0 | null | 2011-01-06 17:43:44.717 UTC | 5 | 2020-06-15 20:24:53.777 UTC | 2020-06-15 20:24:53.777 UTC | null | 814,702 | null | 266,406 | null | 1 | 28 | sql|mysql|constraints | 17,049 | <p>I think this is not the best way to model the situation of a single default value.</p>
<p>Instead, I would leave the IsDefault column out and create a separate table with one row and only the column(s) that make(s) up the primary key of your main table. In this table you place the PK value(s) that identify the default record.</p>
<p>This results in considerably less storage and avoids the update issue of temporarily not having a default value (or, alternatively, temporarily having <em>two</em> default values) when you update.</p>
<p>You have numerous options for ensuring that there is one-and-only-one row in the default table.</p> |
4,820,094 | Programmatically creating Views in IOS (how does it work)? | <p>A little background: I'm going through the CS193P iTune videos and I was stuck on the assignment 3 for the longest time. Basically, the assignment asks you to programmatically create a custom view to display a shape on the screen. I'm not using any view controllers by the way.</p>
<p>I could not get my view to display until I finally dragged a View object in Interface Builder and change the object name to my custom view class. So my question is when people say to programmatically create a view, are they just saying manually create the class but when you need to display it use IB? I can't help feeling like I misunderstood something?</p>
<p>edit: let me be more clear. My custom view has been initialized with a frame of 0, 0, 200, 150 and drawRect is overriden to draw a square in it. My view doesn't even show up if try adding it to the main window within my controller:</p>
<pre><code> UIWindow* window = [UIApplication sharedApplication].keyWindow;
[window addSubview:polygonView];
</code></pre>
<p>However, if use drag a view in IB and change the class to my view class, it shows up fine.</p>
<p>Edit: Added some code. This is my controller's awakeFromNib method where the view should be drawn.</p>
<pre><code> - (void)awakeFromNib {
shape = [[PolygonShape alloc] initWithNumberOfSides:numberOfSidesLable.text.integerValue minimumNumberOfSides:3 maximumNumberOfSides:12];
polygonView = [[PolygonView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIWindow *window = [UIApplication sharedApplication].keyWindow;
polygonView.backgroundColor = [UIColor blackColor];
[window addSubview:polygonView];
[self updateInterface];
}
</code></pre>
<p>Part of my controller's updateInterface method:</p>
<pre><code>- (void)updateInterface {
[polygonView setPolygon:shape];
[polygonView setNeedsDisplay];
...
}
</code></pre>
<p>PolygonView.h</p>
<pre><code>#import <UIKit/UIKit.h>
#import "PolygonShape.h"
@interface PolygonView : UIView {
IBOutlet PolygonShape *polygon;
}
@property (readwrite, assign) PolygonShape *polygon;
- (void)drawRect:(CGRect)rect;
@end
</code></pre>
<p>PolygonView.m</p>
<pre><code>#import "PolygonView.h"
@implementation PolygonView
@synthesize polygon;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
nslog(@"initialized");
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGRect bounds = [self bounds];
[[UIColor grayColor] set];
UIRectFill(bounds);
CGRect square = CGRectMake(10, 10, 10, 100);
[[UIColor blackColor] set];
UIRectFill(square);
[[UIColor redColor] set];
UIRectFill(square);
NSLog(@"drawRect called");
}
@end
</code></pre>
<p>The polygonView is being initialized but the drawRect isn't being called.</p> | 4,820,729 | 8 | 5 | null | 2011-01-27 18:07:04.233 UTC | 11 | 2019-04-16 18:34:31.76 UTC | 2011-01-28 17:14:27.64 UTC | null | 591,651 | null | 591,651 | null | 1 | 16 | iphone|objective-c|ios|views | 68,154 | <p>To be even more specific to your question, the syntax would be</p>
<pre><code>UIWindow* window = [UIApplication sharedApplication].keyWindow;
UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 0, 0, 200, 150)];
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];
[window addSubview:polygonView];
[polygonView release];
</code></pre>
<p>This is a pattern you will use for not only this but subviews afterwards. Also, another note is with many of the templates, the viewController is already set up with it's own view. When you want to make a custom view, you create it like above but instead of the method above you set the viewControllers view to the newly created view like so:</p>
<pre><code>viewController.view = polygonView;
</code></pre>
<p>Good luck!</p> |
4,384,829 | jQuery onClick capture the id of the element | <p>i have many input fields like this</p>
<pre><code><input type="radio" name="name" id="name" onchange="enableTxt()" />
</code></pre>
<p>when i click this radio button i wanna capture the id of the radio input. i am using the following code</p>
<pre><code>function enableTxt() {
var id = $(this).attr("id");
alert(id);
}
</code></pre>
<p>Am getting this error</p>
<pre><code>a.attributes is undefined
</code></pre> | 4,384,858 | 8 | 3 | null | 2010-12-08 06:41:14.767 UTC | 6 | 2022-07-01 03:52:36.743 UTC | null | null | null | null | 155,196 | null | 1 | 38 | jquery|jquery-selectors | 111,170 | <p>HTML:</p>
<pre><code><input type="radio" name="name" id="name" onchange="enableTxt(this)" />
</code></pre>
<p>JS:</p>
<pre><code>function enableTxt(elem) {
var id = $(elem).attr("id");
alert(id);
}
</code></pre> |
4,328,947 | Limit file format when using <input type="file">? | <p>I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <code><input type="file"></code> element in HTML. I have a feeling it's impossible, but I'd like to know if there <em>is</em> a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.</p> | 23,706,177 | 12 | 4 | null | 2010-12-01 20:44:40.973 UTC | 168 | 2022-09-06 05:28:52.503 UTC | 2017-02-27 12:45:33.55 UTC | null | 1,724,702 | null | 383,609 | null | 1 | 876 | html|file|types | 703,013 | <p>Strictly speaking, the answer is <strong>no</strong>. A developer <em>cannot</em> prevent a user from uploading files of any type or extension.<br/><br/>But still, the <strong><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept" rel="noreferrer">accept</a></strong> attribute of <code><input type = "file"></code> can help to provide a filter in the file select dialog box provided by the user's browser/OS. For example,</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" /></code></pre>
</div>
</div>
</p>
<p>should provide a way to filter out files other than .xls or .xlsx. Although the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input" rel="noreferrer">MDN</a> page for <code>input</code> element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.</p>
<p>So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> </code></pre>
</div>
</div>
</p>
<p>[<strong>Edge</strong> (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is <code>All files (*)</code>.]<br /></p>
<p>You can also use asterisks in MIME-types. For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
<input type="file" accept="video/*" /> <!-- all video types --> </code></pre>
</div>
</div>
</p>
<p>W3C <strong><a href="https://html.spec.whatwg.org/multipage/input.html#attr-input-accept" rel="noreferrer">recommends</a></strong> authors to specify both MIME-types and their corresponding extensions in the <code>accept</code> attribute. So, the <strong>best</strong> approach is:<br /></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Right approach: Use both file extensions and their corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> </code></pre>
</div>
</div>
</p>
<p>JSFiddle of the same: <a href="http://jsfiddle.net/sachinjoseph/BkcKQ/" rel="noreferrer">here</a>.<br /></p>
<p><strong>Reference:</strong> <a href="http://www.iana.org/assignments/media-types/media-types.xhtml" rel="noreferrer">List of MIME-types</a><br /><br />
<strong>IMPORTANT:</strong> Using the <code>accept</code> attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be <a href="https://stackoverflow.com/a/4329103/1724702">this</a>), and definitely file types <em><strong>MUST be verified on the server</strong></em>, using a combination of MIME-type using both the file extension and its binary signature (<a href="https://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature">ASP.NET</a>, <a href="https://stackoverflow.com/questions/310714/how-to-check-file-types-of-uploaded-files-in-php">PHP</a>, <a href="https://stackoverflow.com/questions/4600679/detect-mime-type-of-uploaded-file-in-ruby">Ruby</a>, <a href="https://stackoverflow.com/questions/8666445/check-file-type-after-upload">Java</a>). You might also want to refer to <a href="http://en.wikipedia.org/wiki/List_of_file_signatures" rel="noreferrer">these</a> <a href="http://www.garykessler.net/library/file_sigs.html" rel="noreferrer">tables</a> for file types and their <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29" rel="noreferrer">magic numbers</a>, to perform a more robust server-side verification.<br /><br />
Here are <a href="https://stackoverflow.com/questions/3597082/how-is-a-website-hacked-by-a-maliciously-encoded-image-that-contained-a-php-scr">three</a> <a href="http://www.acunetix.com/websitesecurity/upload-forms-threat/" rel="noreferrer">good</a> <a href="http://www.hanselman.com/blog/BackToBasicsWhenAllowingUserUploadsDontAllowUploadsToExecuteCode.aspx" rel="noreferrer">reads</a> on file-uploads and security.</p>
<p><strong>EDIT:</strong> Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.</p> |
4,288,303 | Can't install PostgreSQL: An error occurred executing the Microsoft VC++ runtime installer on Windows XP | <p>I downloaded installer postgresql-9.0.1-1-windows.exe from the official site, ran it, and then got an error:</p>
<blockquote>
<p>An error occurred executing the Microsoft VC++ runtime installer</p>
</blockquote>
<p>What is the reason for this error message?</p>
<p>Platform: Windows XP SP3, Dell Inspiron 1501. Processor: AMD Sempron 3500+</p> | 4,289,626 | 14 | 1 | null | 2010-11-26 20:14:37.457 UTC | 17 | 2020-09-28 09:31:58.637 UTC | 2019-10-22 07:36:12.687 UTC | null | 63,550 | null | 250,849 | null | 1 | 101 | postgresql|windows-xp | 109,615 | <p>One of the reasons this can happen is because the installer attempts to install an older version of the VC++ runtime than what you are currently using.</p>
<p>See this installation log, found in your user's temporary directory (e.g. <code>dd_vcredist_amd64_20190214193107.log</code>):</p>
<blockquote>
<p>[20C0:20E4][2019-02-14T19:31:07]e000: Error 0x80070666: Cannot install a product when a newer version is installed.</p>
</blockquote>
<p><a href="http://archives.postgresql.org/pgsql-admin/2010-10/msg00107.php" rel="noreferrer">A workaround</a> is to prevent the runtimes from installing with the <code>--install_runtimes</code> option:</p>
<pre class="lang-none prettyprint-override"><code>postgresql-9.6.12-1-windows-x64.exe --install_runtimes 0
</code></pre> |
4,426,442 | Unix tail equivalent command in Windows Powershell | <p>I have to look at the last few lines of a large file (typical size is 500MB-2GB). I am looking for a equivalent of Unix command <code>tail</code> for Windows Powershell. A few alternatives available on are,</p>
<p><a href="http://tailforwin32.sourceforge.net/">http://tailforwin32.sourceforge.net/</a></p>
<p>and</p>
<pre>Get-Content [filename] | Select-Object -Last 10</pre>
<p>For me, it is not allowed to use the first alternative, and the second alternative is slow. Does anyone know of an efficient implementation of tail for PowerShell.</p> | 4,427,285 | 14 | 5 | null | 2010-12-13 06:55:28.41 UTC | 129 | 2022-01-05 16:30:09.77 UTC | 2010-12-13 08:47:52.667 UTC | null | 310,574 | null | 520,382 | null | 1 | 436 | windows|powershell|tail | 419,514 | <p>Use the <code>-wait</code> parameter with Get-Content, which displays lines as they are added to the file. This feature was present in PowerShell v1, but for some reason not documented well in v2.</p>
<p>Here is an example</p>
<pre><code>Get-Content -Path "C:\scripts\test.txt" -Wait
</code></pre>
<p>Once you run this, update and save the file and you will see the changes on the console.</p> |
14,430,321 | Underscore.js: Sum of items in a collection | <p>I made a small plnkr <a href="http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview" rel="noreferrer">here</a> to show what I am trying to achieve. I have a big dataset, where I like to sum the individual type to get a total.</p>
<p>I could think of iterating and adding the results to an object hash, but wonder more elegant way to solve it with underscore. I am using underscore.js, but never tried map reduce or other functional paradigm. Please update the plnkr to learn how to do this.</p>
<p><a href="http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview" rel="noreferrer">http://plnkr.co/edit/B5HGxhwvWsfvOR97z7TL?p=preview</a></p>
<pre><code>var data = [ {'type': "A", 'val':2},
{'type': "B", 'val':3},
{'type': "A", 'val':1},
{'type': "C", 'val':5} ];
_.each(data, function (elm, index) {
console.log(elm);
});
/*
Desired output
out = [ {'type': "A", 'total':3},
{'type': "B", 'total':3},
{'type': "C", 'total':5} ];
*/
</code></pre> | 14,430,590 | 3 | 0 | null | 2013-01-20 23:00:00.787 UTC | 8 | 2014-11-03 19:20:36.517 UTC | null | null | null | null | 303,477 | null | 1 | 17 | javascript|underscore.js | 32,376 | <pre><code>var data = [ { type: "A", val: 2 },
{ type: "B", val: 3 },
{ type: "A", val: 1 },
{ type: "C", val: 5 } ];
var groups = _(data).groupBy('type');
var out = _(groups).map(function(g, key) {
return { type: key,
val: _(g).reduce(function(m,x) { return m + x.val; }, 0) };
});
</code></pre>
<p><a href="http://jsbin.com/otucik/37/edit">DEMO</a></p> |
14,730,311 | WPF borderless window with shadow VS2012 style | <p>I'm trying to create an application that looks like Visual Studio 2012. I have used <a href="http://msdn.microsoft.com/en-us/library/system.windows.shell.windowchrome.aspx" rel="noreferrer">WindowChrome</a> to remove the window borders, and changed the border color in my xaml.</p>
<p>What I don't know how to do is paint the shadow of the window, here you can see an screenshot of what I'm saying:</p>
<p><img src="https://i.stack.imgur.com/ZHptQ.png" alt="Visual Studio Borderless window with shadow"></p>
<p>As you can see there is a shadow and its color is also the border color</p>
<p>Do you know how to implement it using WPF?</p> | 14,790,533 | 5 | 1 | null | 2013-02-06 13:29:41.813 UTC | 18 | 2020-10-21 17:42:05.38 UTC | 2013-03-10 14:47:51.047 UTC | null | 1,420,197 | null | 402,081 | null | 1 | 21 | c#|wpf|user-interface|visual-studio-2012 | 36,310 | <h1>Update (October '17)</h1>
<p>It has been four years now and I was interested in tackling this again and thus I have been messing around with <em>MahApps.Metro</em> once again and <a href="https://github.com/ChristianIvicevic/ModernChrome" rel="noreferrer">derived my own library based on it</a>. My <em>ModernChrome</em> library provides a custom window that looks like Visual Studio 2017:</p>
<p><a href="https://i.stack.imgur.com/l1X2u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l1X2u.png" alt="ModernChrome Sample"></a></p>
<p>Since you are most likely only interested in the part about the glowing border, you should either use <em>MahApps.Metro</em> itself or see how I created a class <code>GlowWindowBehavior</code> which attaches glow borders to my custom <code>ModernWindow</code> class. It is hevily dependant on some internals of <em>MahApps.Metro</em> and the two dependency properties <code>GlowBrush</code> and <code>NonActiveGlowBrush</code>.</p>
<p>If you only want to include the glowing borders to your custom applications just reference <em>MahApps.Metro</em> and copy over my <code>GlowWindowBehavior.cs</code> and create a custom window class and adapt the references accordingly. This is a matter of 15 minutes at most.</p>
<p>This question and my answer have been accessed very frequently so I hope you will find my newest proper solution useful :)</p>
<hr>
<h1>Original post (February '13)</h1>
<p>I have been working on such a library to copy the Visual Studio 2012 user interface. A custom chrome isn't that difficult but what you should take care of is this glowing border which is hard to implement. You could just say set the background color of your window to transparent and set the padding of the main grid to about 30px. A border around the grid could be colored and associated with a colored shadow effect but this approach forces you to set <code>AllowsTransparency</code> to true which drastically reduces visual performance of your application and this is something you definitely do not want to do!</p>
<p>My current approach to create such a window which just has a colored shadow effect on a border and is transparent but has no content at all. Evertime the position of my main window changes I just update the position of the window which holds the border. So in the end I am handling two windows with messages to fake that the border would be part of the main window. This was necessary because the DWM library doesn't provide a way to have a colored drop shadow effect for windows and I think Visual Studio 2012 does that similiar like I tried.</p>
<p>And to extend this post with more information: Office 2013 does that differently. The border around a window is just 1px thick and colored, yet the shadow is drawn by DWM with a code like <a href="https://stackoverflow.com/a/6313576/796036">this one</a> here. If you can live without having blue/purple/green borders and just usual ones this is the approach I would choose! Just don't set <code>AllowsTransparency</code> to true, otherwise you have lost.</p>
<p>And here is a screenshot of my window with strange color to highlight what it looks like:</p>
<p><img src="https://i.stack.imgur.com/uDf33.png" alt="Metro UI"></p>
<hr>
<p><strong>Here are some hints on how to start</strong></p>
<p>Please keep in mind that my code is quite long, such that I will only be able to show you the basic things to do and you should be able to at least start somehow. First of all I'm going to assume that we have designed our main window somehow (either manually or with the <code>MahApps.Metro</code> package I tried out yesterday - with some modifications to the sourcecode this is really good<sup>(1)</sup>) and we are currently working to implement the glowing shadow border, which I will call <code>GlowWindow</code> from now on. The easiest approach is to create a window with the following XAML code</p>
<pre><code><Window x:Class="MetroUI.Views.GlowWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="GlowWindow"
Title="" Width="300" Height="100" WindowStartupLocation="Manual"
AllowsTransparency="True" Background="Transparent" WindowStyle="None"
ShowInTaskbar="False" Foreground="#007acc" MaxWidth="5000" MaxHeight="5000">
<Border x:Name="OuterGlow" Margin="10" Background="Transparent"
BorderBrush="{Binding Foreground, ElementName=GlowWindow}"
BorderThickness="5">
<Border.Effect>
<BlurEffect KernelType="Gaussian" Radius="15" RenderingBias="Quality" />
</Border.Effect>
</Border>
</Window>
</code></pre>
<p>The resulting window should look like the following picture.</p>
<p><img src="https://i.stack.imgur.com/ztObi.png" alt="GlowWindow"></p>
<p>The next steps are quite difficult - when our main window spawns we want to make the GlowWindow visible but behind the main window and we have to update the position of the GlowWindow when the main window is being moved or resized. What I suggest to prevent visual glitches that can AND will occur is to hide the GlowWindow during every change of either location or size of the window. Once finished with such action just show it again.</p>
<p>I have some method which is called in different situations (it might be a lot but just to get sure)</p>
<pre><code>private void UpdateGlowWindow(bool isActivated = false) {
if(this.DisableComposite || this.IsMaximized) {
this.glowWindow.Visibility = System.Windows.Visibility.Collapsed;
return;
}
try {
this.glowWindow.Left = this.Left - 10;
this.glowWindow.Top = this.Top - 10;
this.glowWindow.Width = this.Width + 20;
this.glowWindow.Height = this.Height + 20;
this.glowWindow.Visibility = System.Windows.Visibility.Visible;
if(!isActivated)
this.glowWindow.Activate();
} catch(Exception) {
}
}
</code></pre>
<p>This method is mainly called in my custom <code>WndProc</code> I have attached to the main window:</p>
<pre><code>/// <summary>
/// An application-defined function that processes messages sent to a window. The WNDPROC type
/// defines a pointer to this callback function.
/// </summary>
/// <param name="hwnd">A handle to the window.</param>
/// <param name="uMsg">The message.</param>
/// <param name="wParam">Additional message information. The contents of this parameter depend on
/// the value of the uMsg parameter.</param>
/// <param name="lParam">Additional message information. The contents of this parameter depend on
/// the value of the uMsg parameter.</param>
/// <param name="handled">Reference to boolean value which indicates whether a message was handled.
/// </param>
/// <returns>The return value is the result of the message processing and depends on the message sent.
/// </returns>
private IntPtr WindowProc(IntPtr hwnd, int uMsg, IntPtr wParam, IntPtr lParam, ref bool handled) {
// BEGIN UNMANAGED WIN32
switch((WinRT.Message)uMsg) {
case WinRT.Message.WM_SIZE:
switch((WinRT.Size)wParam) {
case WinRT.Size.SIZE_MAXIMIZED:
this.Left = this.Top = 0;
if(!this.IsMaximized)
this.IsMaximized = true;
this.UpdateChrome();
break;
case WinRT.Size.SIZE_RESTORED:
if(this.IsMaximized)
this.IsMaximized = false;
this.UpdateChrome();
break;
}
break;
case WinRT.Message.WM_WINDOWPOSCHANGING:
WinRT.WINDOWPOS windowPosition = (WinRT.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WinRT.WINDOWPOS));
Window handledWindow = (Window)HwndSource.FromHwnd(hwnd).RootVisual;
if(handledWindow == null)
return IntPtr.Zero;
bool hasChangedPosition = false;
if(this.IsMaximized == true && (this.Left != 0 || this.Top != 0)) {
windowPosition.x = windowPosition.y = 0;
windowPosition.cx = (int)SystemParameters.WorkArea.Width;
windowPosition.cy = (int)SystemParameters.WorkArea.Height;
hasChangedPosition = true;
this.UpdateChrome();
this.UpdateGlowWindow();
}
if(!hasChangedPosition)
return IntPtr.Zero;
Marshal.StructureToPtr(windowPosition, lParam, true);
handled = true;
break;
}
return IntPtr.Zero;
// END UNMANAGED WIN32
}
</code></pre>
<p>However there is still an issue left - once you resize your main window the GlowWindow will not be able to cover the whole window with its size. That is if you resize your main window to about MaxWidth of your screen, then the widt of the GlowWindow would be the same value + 20 as I have added a margin of 10 to it. Therefore the right edge would be interrupted right before the right edge of the main window which looks ugly. To prevent this I used a hook to make the GlowWindow a toolwindow:</p>
<pre><code>this.Loaded += delegate {
WindowInteropHelper wndHelper = new WindowInteropHelper(this);
int exStyle = (int)WinRT.GetWindowLong(wndHelper.Handle, (int)WinRT.GetWindowLongFields.GWL_EXSTYLE);
exStyle |= (int)WinRT.ExtendedWindowStyles.WS_EX_TOOLWINDOW;
WinRT.SetWindowLong(wndHelper.Handle, (int)WinRT.GetWindowLongFields.GWL_EXSTYLE, (IntPtr)exStyle);
};
</code></pre>
<p>And still we will have some issues - when you go with the mouse over the GlowWindow and left click it will be activated and get the focus which means it will overlap the main window which looks like this:</p>
<p><img src="https://i.stack.imgur.com/g5dYW.png" alt="Overlapping GlowWindow"></p>
<p>To prevent that just catch the <code>Activated</code> event of the border and bring the main window to the foreground.</p>
<p><strong>How should YOU do this?</strong></p>
<p>I suggest NOT to try this out - it took me about a month to achieve what I wanted and still it has some issues, such that I would go for an approach like Office 2013 does - colored border and usual shadow with the DWM API calls - nothing else and still it looks good.</p>
<p><img src="https://i.stack.imgur.com/y95wS.png" alt="Office 2013"></p>
<hr>
<p><sup>(1)</sup> I have just edited some files to enable the border around the window which is disabled on Window 8 for me. Furthermore I have manipulated the <code>Padding</code> of the title bar such that it doesn't look that sqeezed inplace and lastly I have change the All-Caps property to mimic Visual Studio's way of rendering the title. So far the <code>MahApps.Metro</code> is a better way of drawing the main window as it even supports AeroSnap I couldn't implement with usual P/Invoke calls.</p> |
14,712,223 | How to handle anchor hash linking in AngularJS | <p>Do any of you know how to nicely handle anchor hash linking in <strong>AngularJS</strong>?</p>
<p>I have the following markup for a simple FAQ-page</p>
<pre><code><a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>
</code></pre>
<p>When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.)</p>
<p>My first thought was to create a route matching "<strong>/faq/:chapter</strong>" and in the corresponding controller check <code>$routeParams.chapter</code> after a matching element and then use jQuery to scroll down to it.</p>
<p>But then AngularJS shits on me again and just scrolls to the top of the page anyway.</p>
<p>So, anyone here done anything similar in the past and knows a good solution to it?</p>
<p>Edit: Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/</p> | 14,717,011 | 28 | 8 | null | 2013-02-05 16:29:38.017 UTC | 144 | 2021-07-08 14:42:02.867 UTC | 2018-02-13 07:24:36.583 UTC | null | 2,172,547 | null | 384,868 | null | 1 | 323 | javascript|angularjs|anchor|hashtag | 233,207 | <p>You're looking for <a href="https://docs.angularjs.org/api/ng/service/$anchorScroll" rel="noreferrer"><code>$anchorScroll()</code></a>.</p>
<p><a href="https://docs.angularjs.org/api/ng/service/$anchorScroll" rel="noreferrer">Here's the (crappy) documentation.</a></p>
<p><a href="https://github.com/angular/angular.js/blob/master/src/ng/anchorScroll.js" rel="noreferrer">And here's the source.</a></p>
<p>Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in <code>$location.hash()</code></p>
<pre><code>app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
}
});
<a ng-click="scrollTo('foo')">Foo</a>
<div id="foo">Here you are</div>
</code></pre>
<p><a href="http://plnkr.co/edit/PCO051UJS8EHbdkmFV40?p=preview" rel="noreferrer">Here is a plunker to demonstrate</a></p>
<p><strong>EDIT: to use this with routing</strong></p>
<p>Set up your angular routing as usual, then just add the following code.</p>
<pre><code>app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
});
</code></pre>
<p>and your link would look like this:</p>
<pre><code><a href="#/test?scrollTo=foo">Test/Foo</a>
</code></pre>
<p>Here is a <a href="http://plnkr.co/edit/De6bBrkHpojgAbEvHszu" rel="noreferrer">Plunker demonstrating scrolling with routing and $anchorScroll</a></p>
<p><strong>And even simpler:</strong></p>
<pre><code>app.run(function($rootScope, $location, $anchorScroll) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
if($location.hash()) $anchorScroll();
});
});
</code></pre>
<p>and your link would look like this:</p>
<pre><code><a href="#/test#foo">Test/Foo</a>
</code></pre> |
14,770,829 | Grouping timestamps by day, not by time | <p>I've got a table storing user access/view logs for the webservice I run. It tracks the time as a timestamp though I'm finding when I do aggregate reporting I only care about the day, not the time.</p>
<p>I'm currently running the following query:</p>
<pre><code>SELECT
user_logs.timestamp
FROM
user_logs
WHERE
user_logs.timestamp >= %(timestamp_1)s
AND user_logs.timestamp <= %(timestamp_2)s
ORDER BY
user_logs.timestamp
</code></pre>
<p>There are often other where conditions but they shouldn't matter to the question. I'm using Postgres but I'd assume whatever feature is used will work in other languages.</p>
<p>I pull the results into a Python script which counts the number of views per date but it'd make much more sense to me if the database could group and count for me.</p>
<p>How do I strip it down so it'll group by the day and ignore the time?</p> | 14,771,089 | 1 | 0 | null | 2013-02-08 10:48:18.437 UTC | 15 | 2020-03-18 16:30:48.98 UTC | 2020-03-18 16:30:48.98 UTC | null | 631,348 | null | 1,384,652 | null | 1 | 80 | sql|postgresql | 72,979 | <pre><code>SELECT date_trunc('day', user_logs.timestamp) "day", count(*) views
FROM user_logs
WHERE user_logs.timestamp >= %(timestamp_1)s
AND user_logs.timestamp <= %(timestamp_2)s
group by 1
ORDER BY 1
</code></pre> |
19,331,606 | onclick add image to div | <p>I am trying to get image in a <code><div></code> using <code>onclick</code>. </p>
<p>Now I am getting the text on click. but I want to get the image in div on click...</p>
<p>How can i do this...?</p>
<p>Here is code I have implemented,,</p>
<p>Code:</p>
<pre><code><script>
function myFunction()
{
document.getElementById("surprise").innerHTML=images/aftersurprise.png;
}
</script>
</code></pre>
<p>When I click on element I should get the <code>aftersurprise.png</code> image on surprise element...</p> | 19,331,616 | 7 | 0 | null | 2013-10-12 07:16:29.917 UTC | 1 | 2019-03-26 10:04:18.883 UTC | 2013-10-12 07:39:44.927 UTC | user2672373 | null | null | 2,749,219 | null | 1 | 2 | javascript|html|onclick | 40,048 | <p>use </p>
<pre><code>document.getElementById("surprise").innerHTML="<img src='images/aftersurprise.png' />";
</code></pre> |
29,950,299 | Distributed Web crawling using Apache Spark - Is it Possible? | <p>An interesting question asked of me when I attended one interview regarding web mining. The question was, is it possible to crawl the Websites using Apache Spark?</p>
<p>I guessed that it was possible, because it supports distributed processing capacity of Spark. After the interview I searched for this, but couldn't find any interesting answer. Is that possible with Spark?</p> | 29,960,707 | 5 | 1 | null | 2015-04-29 17:13:20.16 UTC | 10 | 2021-02-11 12:56:10.507 UTC | 2016-12-29 18:28:06.037 UTC | user6022341 | 1,506,477 | null | 4,847,488 | null | 1 | 17 | web|apache-spark|web-crawler | 16,903 | <p>How about this way:</p>
<p>Your application would get a set of websites URLs as input for your crawler, if you are implementing just a normal app, you might do it as follows:</p>
<ol>
<li>split all the web pages to be crawled into a list of separate site, each site is small enough to fit in a single thread well:
<code>for example: you have to crawl www.example.com/news from 20150301 to 20150401, split results can be: [www.example.com/news/20150301, www.example.com/news/20150302, ..., www.example.com/news/20150401]</code></li>
<li>assign each base url(<code>www.example.com/news/20150401</code>) to a single thread, it is in the threads where the really data fetch happens</li>
<li>save the result of each thread into FileSystem.</li>
</ol>
<p>When the application become a spark one, same procedure happens but encapsulate in Spark notion: we can customize a CrawlRDD do the same staff:</p>
<ol>
<li>Split sites: <code>def getPartitions: Array[Partition]</code> is a good place to do the split task.</li>
<li>Threads to crawl each split: <code>def compute(part: Partition, context: TaskContext): Iterator[X]</code> will be spread to all the executors of your application, run in parallel.</li>
<li>save the rdd into HDFS.</li>
</ol>
<p>The final program looks like:</p>
<pre class="lang-scala prettyprint-override"><code>class CrawlPartition(rddId: Int, idx: Int, val baseURL: String) extends Partition {}
class CrawlRDD(baseURL: String, sc: SparkContext) extends RDD[X](sc, Nil) {
override protected def getPartitions: Array[CrawlPartition] = {
val partitions = new ArrayBuffer[CrawlPartition]
//split baseURL to subsets and populate the partitions
partitions.toArray
}
override def compute(part: Partition, context: TaskContext): Iterator[X] = {
val p = part.asInstanceOf[CrawlPartition]
val baseUrl = p.baseURL
new Iterator[X] {
var nextURL = _
override def hasNext: Boolean = {
//logic to find next url if has one, fill in nextURL and return true
// else false
}
override def next(): X = {
//logic to crawl the web page nextURL and return the content in X
}
}
}
}
object Crawl {
def main(args: Array[String]) {
val sparkConf = new SparkConf().setAppName("Crawler")
val sc = new SparkContext(sparkConf)
val crdd = new CrawlRDD("baseURL", sc)
crdd.saveAsTextFile("hdfs://path_here")
sc.stop()
}
}
</code></pre> |
36,719,540 | How can I get an oauth2 access_token using Python | <p>For a project someone gave me this data that I have used in Postman for testing purposes:</p>
<p>In Postman this works perfectly.</p>
<p>Auth URL: <a href="https://api.example.com/oauth/access_token" rel="noreferrer">https://api.example.com/oauth/access_token</a><br>
Access Token URL: <a href="https://api.example.com/access_token" rel="noreferrer">https://api.example.com/access_token</a><br>
client ID: abcde<br>
client secret: 12345<br>
Token name: access_token<br>
Grant type: Client Credentials </p>
<p>All I need is to get back the access token. </p>
<p>Once, I got the access token I can continue. </p>
<p>I have already tried several Python packages and some custom code, but somehow this seemingly simple task starts to create a real headache. </p>
<p>One exemple I tried:</p>
<pre><code>import httplib
import base64
import urllib
import json
def getAuthToken():
CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
conn = httplib.HTTPSConnection("api.example.com")
url = "/oauth/access_token"
params = {
"grant_type": "client_credentials"
}
client = CLIENT_ID
client_secret = CLIENT_SECRET
authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')
requestUrl = url + "?" + urllib.urlencode(params)
headersMap = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + authString
}
conn.request("POST", requestUrl, headers=headersMap)
response = conn.getresponse()
if response.status == 200:
data = response.read()
result = json.loads(data)
return result["access_token"]
</code></pre>
<p>Then I have got this one:</p>
<pre><code>import requests
import requests.auth
CLIENT_ID = "abcde"
CLIENT_SECRET = "12345"
TOKEN_URL = "https://api.example.com/oauth/access_token"
REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
post_data = {"grant_type": "client_credentials",
"code": code,
"redirect_uri": REDIRECT_URI}
response = requests.post(TOKEN_URL,
auth=client_auth,
data=post_data)
token_json = response.json()
return token_json["access_token"]
</code></pre>
<p>If this would work, what should I put into the <code>code</code> parameter</p>
<p>I really hope someone can help me out here. </p>
<p>Thanks in advance.</p> | 36,737,820 | 3 | 0 | null | 2016-04-19 13:13:46.69 UTC | 15 | 2022-07-19 12:06:48.51 UTC | 2018-10-10 07:49:27.67 UTC | null | 9,928,700 | null | 5,039,579 | null | 1 | 17 | python|google-oauth | 81,268 | <p>I was finally able to get it done by using the <a href="https://rauth.readthedocs.io/en/latest/" rel="nofollow noreferrer">rauth</a> library (<code>pip install rauth</code>).</p>
<p>This is the code I used:</p>
<pre><code>from rauth import OAuth2Service
class ExampleOAuth2Client:
def __init__(self, client_id, client_secret):
self.access_token = None
self.service = OAuth2Service(
name="foo",
client_id=client_id,
client_secret=client_secret,
access_token_url="http://api.example.com/oauth/access_token",
authorize_url="http://api.example.com/oauth/access_token",
base_url="http://api.example.com/",
)
self.get_access_token()
def get_access_token(self):
data = {'code': 'bar', # specific to my app
'grant_type': 'client_credentials', # generally required!
}
session = self.service.get_auth_session(data=data, decoder=json.loads)
self.access_token = session.access_token
</code></pre> |
36,076,924 | How can I display a loading control while a process is waiting for be finished? | <p>I decided to use this third-party component to make a simple loading control in my windows form.</p>
<p><a href="http://www.codeproject.com/Articles/14841/How-to-write-a-loading-circle-animation-in-NET" rel="noreferrer">http://www.codeproject.com/Articles/14841/How-to-write-a-loading-circle-animation-in-NET</a></p>
<p>This works fine when turns on and off changing the property "Active" to true or false in a single request (one per time). The problem is when a process is waiting to be served, and I pretend to Active the loadingControl before the process starts and turn off when I "think" that the process has to be finished. When I do it, the image loading is shown as a static image. (Without animation). </p>
<p>I'm sorry for this question, I'm new in C#. But I think that I need to use Threads or something similar.</p>
<p>So my general code is this:</p>
<pre class="lang-cs prettyprint-override"><code>using [libraries here]...;
namespace [namespace here]
{
Public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.loadingCircle1.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(showLoading));
this.loadingCircle1.Visible = true;
t.Start();
//Import an Excel
t.Abort();
}
public void showLoading()
{
loadingCircle1.Active = true;
loadingCircle1.RotationSpeed = 10;
}
}
}
</code></pre>
<p>But Always the Loading shows as a static image without the animation.</p> | 36,079,335 | 2 | 0 | null | 2016-03-18 05:39:30.13 UTC | 13 | 2018-11-24 14:28:31.153 UTC | 2018-11-24 14:28:31.153 UTC | null | 8,967,612 | null | 2,620,208 | null | 1 | 18 | c#|.net|winforms|loading | 61,390 | <p>You create a thread, which simply sets two properties and then ends. The <code>t.Abort</code> will probably do nothing, since the thread will have been exited by that time. Even worse, you import the excel file on the UI thread, which blocks any animation and freezes the complete UI.</p>
<p>This is how you should make it:</p>
<p><em>Remark:</em> Of course if your form is responsive, you must disable/enable the controls and prepare to the case what happens if your form is being closed during the load.</p>
<p><strong>1. Using threads</strong></p>
<p>If you really want to explicitly use threads, do it like this:</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread workerThread = null;
private void btnImport_Click(object sender, EventArgs e)
{
// start the animation (I used a progress bar, start your circle here)
progressBar1.Visible = true;
progressBar1.Style = ProgressBarStyle.Marquee;
// start the job and the timer, which polls the thread
btnImport.Enabled = false;
workerThread = new Thread(LoadExcel);
workerThread.Start();
timer1.Interval = 100;
timer1.Start();
}
private void LoadExcel()
{
// some work takes 5 sec
Thread.Sleep(5000);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (workerThread == null)
{
timer1.Stop();
return;
}
// still works: exiting
if (workerThread.IsAlive)
return;
// finished
btnImport.Enabled = true;
timer1.Stop();
progressBar1.Visible = false;
workerThread = null;
}
}
</code></pre>
<p><strong>2. Background worker</strong></p>
<p>The <code>BackgroundWorker</code> can throw an event when it is finished:</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
}
private void btnImport_Click(object sender, EventArgs e)
{
// start the animation
progressBar1.Visible = true;
progressBar1.Style = ProgressBarStyle.Marquee;
// start the job
btnImport.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
LoadExcel();
}
private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnImport.Enabled = true;
progressBar1.Visible = false;
}
private void LoadExcel()
{
// some work takes 5 sec
Thread.Sleep(5000);
}
}
</code></pre>
<p><strong>3. Using async-await</strong></p>
<p>This is the simplest one.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void btnImport_Click(object sender, EventArgs e)
{
// start the waiting animation
progressBar1.Visible = true;
progressBar1.Style = ProgressBarStyle.Marquee;
// simply start and await the loading task
btnImport.Enabled = false;
await Task.Run(() => LoadExcel());
// re-enable things
btnImport.Enabled = true;
progressBar1.Visible = false;
}
private void LoadExcel()
{
// some work takes 5 sec
Thread.Sleep(5000);
}
}
</code></pre> |
35,848,688 | What's the difference between replaceOne() and updateOne() in MongoDB? | <p>MongoDB bulk operations have two options:</p>
<ol>
<li><p><a href="https://docs.mongodb.org/manual/reference/method/Bulk.find.updateOne/" rel="noreferrer"><strong><code>Bulk.find.updateOne()</code></strong></a></p>
<blockquote>
<p>Adds a single document update operation to a bulk operations list. The operation can either replace an existing document or update specific fields in an existing document.</p>
</blockquote></li>
<li><p><a href="https://docs.mongodb.org/manual/reference/method/Bulk.find.replaceOne/" rel="noreferrer"><strong><code>Bulk.find.replaceOne()</code></strong></a></p>
<blockquote>
<p>Adds a single document replacement operation to a bulk operations list. Use the <code>Bulk.find()</code> method to specify the condition that determines which document to replace. The <code>Bulk.find.replaceOne()</code> method limits the replacement to a single document.</p>
</blockquote></li>
</ol>
<p>According to the documentation, both of these two methods can replace a matching document. Do I understand correctly, that <code>updateOne()</code> is more general purpose method, which can either replace the document exactly like <code>replaceOne()</code> does, or just update its specific fields?</p> | 35,848,817 | 3 | 0 | null | 2016-03-07 16:18:18.303 UTC | 8 | 2019-08-13 19:43:33.85 UTC | 2019-02-20 18:45:02.92 UTC | null | 462,347 | null | 462,347 | null | 1 | 74 | mongodb|mongodb-query|crud | 60,383 | <p>With <code>replaceOne()</code> you can only replace the entire document, while <code>updateOne()</code> allows for updating fields.</p>
<p>Since <code>replaceOne()</code> replaces the entire document - fields in the old document not contained in the new will be lost. With <code>updateOne()</code> new fields can be added without losing the fields in the old document.</p>
<p>For example if you have the following document:</p>
<pre><code>{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333
}
</code></pre>
<p>Using:</p>
<pre><code>replaceOne({"_id" : ObjectId("0123456789abcdef01234567")}, { "my_test_key4" : 4})
</code></pre>
<p>results in:</p>
<pre><code>{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key4" : 4.0
}
</code></pre>
<p>Using:</p>
<pre><code>updateOne({"_id" : ObjectId("0123456789abcdef01234567")}, {$set: { "my_test_key4" : 4}})
</code></pre>
<p>results in:</p>
<pre><code>{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333.0,
"my_test_key4" : 4.0
}
</code></pre>
<p>Note that with <code>updateOne()</code> you can use the <a href="https://docs.mongodb.org/manual/reference/operator/update/" rel="noreferrer">update operators</a> on documents.</p> |
643,385 | adding items to listview at runtime | <p>When I add new values to a listview using :</p>
<pre><code> Set lstView = ListView(0).ListItems.Add(, , txtName)
lstView.ListSubItems.Add , , txtValue
lstView.Refresh
</code></pre>
<p>The only problem is that this only displays a blank new line in the listview, any idea how to update it correctly?</p>
<p>Normally I am using a recordset so simply clear then repopulate the data but I need the user to be able to add entries to the listview. I will then cycle through the listview adding the values tot he DB only once the user has finished amending the listview.</p>
<p>Thanks in advance for any help.</p> | 643,536 | 1 | 1 | null | 2009-03-13 15:56:45.25 UTC | null | 2009-03-13 16:54:56.793 UTC | null | null | null | Denvar | 74,751 | null | 1 | 2 | vb6|listview|listviewitem | 56,077 | <p>Assuming the .View property of your ListView is set to "Report", the following will add a couple of rows to the control and set the sub item text.</p>
<pre><code>Dim li As ListItem
With ListView1
.ColumnHeaders.Add , , "One"
.ColumnHeaders.Add , , "Two"
.ColumnHeaders.Add , , "Three"
Set li = .ListItems.Add(, , "Row1Item1")
li.SubItems(1) = "Row1Item2"
li.SubItems(2) = "Row1Item3"
Set li = .ListItems.Add(, , "Row2Item1")
li.SubItems(1) = "Row2Item2"
li.SubItems(2) = "Row2Item3"
End With
</code></pre> |
33,748,552 | Tensorflow: How to replace a node in a calculation graph? | <p>If you have two disjoint graphs, and want to link them, turning this:</p>
<pre><code>x = tf.placeholder('float')
y = f(x)
y = tf.placeholder('float')
z = f(y)
</code></pre>
<p>into this:</p>
<pre><code>x = tf.placeholder('float')
y = f(x)
z = g(y)
</code></pre>
<p>Is there a way to do that? It seems like it could make construction easier in some cases. </p>
<p>For example if you have a graph that has the input image as a <code>tf.placeholder</code>, and want to optimize the input image, deep-dream style, is there a way to just replace the placeholder with a <code>tf.variable</code> node? Or do you have to think of that before building the graph?</p> | 33,770,771 | 4 | 0 | null | 2015-11-17 03:17:24.803 UTC | 17 | 2018-10-02 17:10:55.97 UTC | 2015-11-17 13:11:03.503 UTC | null | 997,378 | null | 997,378 | null | 1 | 38 | python|tensorflow | 20,818 | <p>TL;DR: If you can define the two computations as Python functions, you should do that. If you can't, there's more advanced functionality in TensorFlow to serialize and import graphs, which allows you to compose graphs from different sources.</p>
<p>One way to do this in TensorFlow is to build the disjoint computations as separate <code>tf.Graph</code> objects, then convert them to serialized protocol buffers using <a href="https://www.tensorflow.org/api_docs/python/tf/Graph#as_graph_def" rel="noreferrer"><code>Graph.as_graph_def()</code></a>:</p>
<pre><code>with tf.Graph().as_default() as g_1:
input = tf.placeholder(tf.float32, name="input")
y = f(input)
# NOTE: using identity to get a known name for the output tensor.
output = tf.identity(y, name="output")
gdef_1 = g_1.as_graph_def()
with tf.Graph().as_default() as g_2: # NOTE: g_2 not g_1
input = tf.placeholder(tf.float32, name="input")
z = g(input)
output = tf.identity(y, name="output")
gdef_2 = g_2.as_graph_def()
</code></pre>
<p>Then you could compose <code>gdef_1</code> and <code>gdef_2</code> into a third graph, using <a href="https://www.tensorflow.org/api_docs/python/tf/import_graph_def" rel="noreferrer"><code>tf.import_graph_def()</code></a>:</p>
<pre><code>with tf.Graph().as_default() as g_combined:
x = tf.placeholder(tf.float32, name="")
# Import gdef_1, which performs f(x).
# "input:0" and "output:0" are the names of tensors in gdef_1.
y, = tf.import_graph_def(gdef_1, input_map={"input:0": x},
return_elements=["output:0"])
# Import gdef_2, which performs g(y)
z, = tf.import_graph_def(gdef_2, input_map={"input:0": y},
return_elements=["output:0"]
</code></pre> |
27,691,792 | Vim - Quit/Close Netrw without selecting any file | <p>My question is fairly simple, still I can't find the answer anywhere :
In Vim, how can I close Netrw explorer without actually selecting a file?
What keystroke should I hit to close the explorer and go back to the currently opened file? </p>
<p>So far, I have to select the currently opened file from within Netrw if I want to get back to it, which happens to be impossible if I haven't saved it yet. </p>
<p>I may add that I RTFM, and do know the <code>:h netrw</code> command ;)</p>
<p>Many thanks.</p> | 27,692,161 | 5 | 0 | null | 2014-12-29 15:39:56.48 UTC | 8 | 2020-06-18 14:04:27.077 UTC | 2014-12-29 15:47:29.687 UTC | null | 877,353 | null | 877,353 | null | 1 | 43 | vim|netrw | 18,215 | <p>Use <code><c-6></code>/<code><c-^></code> to go back to the previous buffer. See <code>:h CTRL-6</code>.</p>
<p>Pro-tip: use <code>:Rex</code> to <em>resume</em> exploring. See <code>:h :Rex</code></p> |
36,088,224 | What does userspace mode means in kube-proxy's proxy mode? | <p>kube-proxy has an option called --proxy-mode,and according to the help message, this option can be <strong>userspace</strong> or <strong>iptables</strong>.(See below)</p>
<pre><code># kube-proxy -h
Usage of kube-proxy:
...
--proxy-mode="": Which proxy mode to use: 'userspace' (older, stable) or 'iptables' (experimental). If blank, look at the Node object on the Kubernetes API and respect the 'net.experimental.kubernetes.io/proxy-mode' annotation if provided. Otherwise use the best-available proxy (currently userspace, but may change in future versions). If the iptables proxy is selected, regardless of how, but the system's kernel or iptables versions are insufficient, this always falls back to the userspace proxy.
...
</code></pre>
<p>I can't figure out what does <strong>userspace</strong> mode means here.</p>
<p>Anyone can tell me what the working principle is when kube-proxy runs under <strong>userspace</strong> mode?</p> | 36,088,688 | 1 | 0 | null | 2016-03-18 15:25:32.457 UTC | 12 | 2017-04-07 09:49:35.657 UTC | 2017-04-07 09:49:35.657 UTC | null | 1,925,083 | null | 615,674 | null | 1 | 19 | kubernetes|kube-proxy | 8,714 | <p>Userspace and iptables refer to what actually handles the connection forwarding. In both cases, local iptables rules are installed to intercept outbound TCP connections that have a destination IP address associated with a service. </p>
<p>In the userspace mode, the iptables rule forwards to a local port where a go binary (kube-proxy) is listening for connections. The binary (running in userspace) terminates the connection, establishes a new connection to a backend for the service, and then forwards requests to the backend and responses back to the local process. An advantage of the userspace mode is that because the connections are created from an application, if the connection is refused, the application can retry to a different backend. </p>
<p>In iptables mode, the iptables rules are installed to directly forward packets that are destined for a service to a backend for the service. This is more efficient than moving the packets from the kernel to kube-proxy and then back to the kernel so it results in higher throughput and better tail latency. The main downside is that it is more difficult to debug, because instead of a local binary that writes a log to <code>/var/log/kube-proxy</code> you have to inspect logs from the kernel processing iptables rules. </p>
<p>In both cases there will be a kube-proxy binary running on your machine. In userspace mode it inserts itself as the proxy; in iptables mode it will configure iptables rather than to proxy connections itself. The same binary works in both modes, and the behavior is switched via a flag or by setting an annotation in the apiserver for the node. </p> |
45,263,064 | How can I fix this "ValueError: can't have unbuffered text I/O" in python 3? | <p>This is one of the MIT python project questions, but it's basically written for python 2.x users, so is there any way to fix the following code to operate in the latest python 3?</p>
<p>The current code is raising "ValueError: can't have unbuffered text I/O"</p>
<pre><code>WORDLIST_FILENAME = "words.txt"
def load_words():
print("Loading word list from file...")
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print(" ", len(wordlist), "words loaded.")
return wordlist
</code></pre> | 45,263,101 | 3 | 0 | null | 2017-07-23 08:29:48.947 UTC | 3 | 2021-09-30 11:47:36.183 UTC | 2019-11-10 13:27:55.743 UTC | null | 11,343 | null | 8,246,602 | null | 1 | 30 | python|python-3.x | 29,051 | <p>From <code>open</code>'s docstring:</p>
<blockquote>
<p>... buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (<strong>only allowed in binary mode</strong>) ...</p>
</blockquote>
<p>So change <code>inFile = open(WORDLIST_FILENAME, 'r', 0)</code></p>
<p>to</p>
<p><code>inFile = open(WORDLIST_FILENAME, 'r')</code>, or to</p>
<p><code>inFile = open(WORDLIST_FILENAME, 'rb', 0)</code> if you really need it (which I doubt).</p> |
22,724,921 | Do I need to do 'git init' before doing 'git clone' on a project | <p>I'm doing a <code>git clone</code> on a project following the instructions. But, do I need to do an <code>init</code> in the directory beforehand?</p> | 22,724,997 | 2 | 0 | null | 2014-03-28 23:28:01.717 UTC | 25 | 2015-10-14 20:03:18.427 UTC | 2015-10-14 20:03:18.427 UTC | null | 641,451 | null | 697,795 | null | 1 | 79 | git | 45,095 | <p><code>git clone</code> is basically a combination of:</p>
<ul>
<li><code>git init</code> (create the local repository)</li>
<li><code>git remote add</code> (add the URL to that repository)</li>
<li><code>git fetch</code> (fetch all branches from that URL to your local repository)</li>
<li><code>git checkout</code> (create all the files of the main branch in your working tree)</li>
</ul>
<p>Therefore, no, you don't have to do a <code>git init</code>, because it is already done by <code>git clone</code>.</p> |
27,162,552 | How to run ngrok in background? | <p>I tried running ngrok in the background with following command:</p>
<pre><code>./ngrok -subdomain test -config=ngrok.cfg 80 &
</code></pre>
<p>the process is running:</p>
<pre><code>[1] 3866
</code></pre>
<p>and the subdomain doesn't work.</p>
<p>It works with:</p>
<pre><code>./ngrok -subdomain test -config=ngrok.cfg 80
</code></pre>
<p>Does anyone know what is going wrong here?</p>
<p>Thank you.</p> | 27,163,717 | 21 | 0 | null | 2014-11-27 03:21:30.663 UTC | 14 | 2021-10-26 16:37:24.88 UTC | 2021-07-15 05:26:49.833 UTC | null | 5,918,539 | null | 4,040,776 | null | 1 | 35 | terminal|ngrok | 69,915 | <p>as explained <a href="https://github.com/inconshreveable/ngrok/issues/57">here</a></p>
<pre><code>ngrok -log=stdout 80 > /dev/null &
</code></pre> |
39,256,520 | Pyspark RDD .filter() with wildcard | <p>I have an Pyspark RDD with a text column that I want to use as a a filter, so I have the following code:</p>
<pre><code>table2 = table1.filter(lambda x: x[12] == "*TEXT*")
</code></pre>
<p>To problem is... As you see I'm using the <code>*</code> to try to tell him to interpret that as a wildcard, but no success.
Anyone has a help no that ?</p> | 39,256,540 | 1 | 0 | null | 2016-08-31 18:23:31.093 UTC | null | 2018-03-14 13:59:47.907 UTC | null | null | null | null | 6,127,305 | null | 1 | 7 | python|apache-spark|rdd | 42,068 | <p>The lambda function is pure python, so something like below would work</p>
<pre><code>table2 = table1.filter(lambda x: "TEXT" in x[12])
</code></pre> |
21,188,239 | Spring transaction: rollback on Exception or Throwable | <p>I wonder whether it makes sense to use instead of </p>
<pre><code>@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
</code></pre>
<p>to use <code>Throwable</code></p>
<pre><code>@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
</code></pre>
<p>As I understand catching <code>Error</code> will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?</p> | 21,188,820 | 4 | 0 | null | 2014-01-17 14:28:40.943 UTC | 12 | 2019-06-23 15:02:18.263 UTC | null | null | null | null | 71,420 | null | 1 | 29 | java|spring|transactions | 76,839 | <blockquote>
<p>As I understand catching Error will help us behave correctly even when something really bad happen. Or maybe it wouldn't help?</p>
</blockquote>
<p>You don't need to explicitly specify <code>rollbackFor = Throwable.class</code>, because spring will by default rollback the transaction if an <code>Error</code> occurs.</p>
<p>See <a href="http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back" rel="noreferrer">12.5.3 Rolling back a declarative transaction</a></p>
<blockquote>
<p>In its default configuration, the Spring Framework's transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. <strong>(Errors will also - by default - result in a rollback)</strong>. Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.</p>
</blockquote>
<p>Or take a look at the <a href="https://github.com/spring-projects/spring-framework/blob/aebb2d52e0a33dbf9779ebf3054a110c280d23ff/spring-tx/src/main/java/org/springframework/transaction/interceptor/DefaultTransactionAttribute.java#L134" rel="noreferrer"><code>DefaultTransactionAttribute</code></a></p>
<pre><code>public boolean rollbackOn(Throwable ex) {
return (ex instanceof RuntimeException || ex instanceof Error);
}
</code></pre> |
31,368,814 | Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference | <p><strong>MainActivity.java</strong> has following code:</p>
<pre><code>package com.softjourn.redmineclient.activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.softjourn.redmineclient.R;
import com.softjourn.redmineclient.models.Issue;
import com.softjourn.redmineclient.models.IssuesResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private final static String URI="https://redmineng.softjourn.if.ua/issues.json?assigned_to_id=me";
@Bind(R.id.list_issues) ListView mListIssues;
Login li;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
li = new Login();
li.execute(URI);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class Login extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(strings[0]).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
c.setUseCaches(false);
try {
c.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Authorization", "basic " + Base64.encodeToString("osavchak:mhgT7322".getBytes(), 0));
try {
c.connect();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader((c.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String output;
try {
while ((output = br.readLine()) != null) {
sb.append(output);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JsonArray ja = new JsonParser().parse(result).getAsJsonObject().getAsJsonArray("issues");
IssuesResponse ir = new IssuesResponse(ja);
ArrayAdapter<Issue> adapter = new ArrayAdapter<Issue>(MainActivity.this, android.R.layout.simple_list_item_1, ir.getIssues());
mListIssues.setAdapter(adapter);
}
}
}
</code></pre>
<p>I've created two model classes.</p>
<p>First, <strong>IssuesResponse.java</strong>:</p>
<pre><code>package com.softjourn .redmineclient.models;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class IssuesResponse {
@SerializedName("issues")
private List<Issue> issues;
public IssuesResponse(JsonArray ja) {
if (issues == null) {
}
for(JsonElement je : ja) {
Issue issue = new Issue(je);
issues.add(issue);
}
}
public List<Issue> getIssues() {
return issues;
}
}
</code></pre>
<p>The second one, <strong>Issue.java</strong>:</p>
<pre><code>package com.softjourn.redmineclient.models;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
public class Issue {
@SerializedName("id")
private int id;
@SerializedName("description")
private String description;
public Issue(JsonElement je) {
Issue issue = new Gson().fromJson(je,Issue.class);
this.id = issue.id;
this.description = issue.description;
}
}
</code></pre>
<p>When I run my application an error occurs:</p>
<blockquote>
<p>java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.softjourn.redmineclient.models.IssuesResponse.(IssuesResponse.java:26)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:125)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:79)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)</p>
</blockquote>
<p>I wait for your suggestions how it could be fixed.</p> | 31,368,849 | 1 | 0 | null | 2015-07-12 14:26:02.613 UTC | 3 | 2019-02-07 10:07:36.907 UTC | null | null | null | null | 4,558,182 | null | 1 | 24 | java|android|list|android-studio|stack-trace | 71,414 | <p>You haven't initialised <code>List<Issue></code> in the IssuesResponse class. Try</p>
<pre><code>private List<Issue> issues = new ArrayList<>();
</code></pre> |
48,070,452 | Uncaught (in promise) Error: Request failed with status code 404 | <p>I am getting above error while fetching some data from the API. Following is the code of the <code>action creator</code> where I am trying <code>GET</code> the data: </p>
<pre><code>import { FETCH_USER } from './types';
import axios from 'axios';
export const fetchUser = () => async dispatch => {
console.log('fetchUser');
const res= await axios.get('/api/current_user');
dispatch({ type: FETCH_USER, payload: res });
};
</code></pre>
<p>Also when I am debugging in the code editor, console is giving me below error: </p>
<p><code>SyntaxError: Unexpected token import</code></p> | 56,900,591 | 3 | 0 | null | 2018-01-03 02:36:06.253 UTC | 1 | 2021-07-03 20:46:53.05 UTC | 2018-09-12 13:56:09.017 UTC | null | 472,495 | null | 8,936,320 | null | 1 | 4 | reactjs|react-redux|axios|dispatch-async | 43,849 | <p>Generally this error comes when the url/location provided inside GET method is not correct.
So check the url/location again and correct it.</p>
<p>So most probably there is some mistake here : '/api/current_user' </p> |
7,634,715 | Python decoding Unicode is not supported | <p>I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8.</p>
<p>This is what I am trying to do:</p>
<pre><code>result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8")
</code></pre>
<p><code>searchGoogle</code> returns the first Google result for <code>param</code>.</p>
<p>This is the error I get:</p>
<pre><code>exceptions.TypeError: decoding Unicode is not supported
</code></pre>
<p>Does anyone know how I can make Python encode my output in UTF-8 to avoid this error?</p> | 7,634,778 | 1 | 0 | null | 2011-10-03 12:04:05.107 UTC | 17 | 2011-10-03 12:09:04.087 UTC | null | null | null | null | 486,845 | null | 1 | 81 | python|encoding|utf-8|character-encoding | 100,641 | <p>Looks like <code>google.searchGoogle(param)</code> already returns <code>unicode</code>:</p>
<pre><code>>>> unicode(u'foo', 'utf-8')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
unicode(u'foo', 'utf-8')
TypeError: decoding Unicode is not supported
</code></pre>
<p>So what you want is:</p>
<pre><code>result = google.searchGoogle(param).encode("utf-8")
</code></pre>
<p>As a side note, your code expects it to return a <code>utf-8</code> encoded string so what was the point in decoding it (using <code>unicode()</code>) and encoding back (using <code>.encode()</code>) using the same encoding?</p> |
50,283,857 | Using Cypress, how would I write a simple test to check that a logo image exists on a page | <p>specifically, I would like to test that the logo appears on the home page of the app. I guess I am not sure what I should use to look for the image.</p>
<p>I tried </p>
<pre><code>it('has a logo', function () {
cy.visit('http://localhost:3000')
cy.get('img').should('contains' , 'My-Logo.png')
})
</code></pre>
<p>instead of cy.get I also tried to just use </p>
<pre><code>cy.contains('My-Logo.png')
</code></pre>
<p>but it also fails.</p>
<p>I wasn't sure what element I should use or if I should be using get, but it fails. When I look at the source code for the web page, the logo is hidden within the javascript (nodeJS, vueJS,and expressJS application) and I noticed the javascript seems to add a sequence of numbers and letters to the image when I go to the image page even though the image name in the assets folder does not have it on there. My-Logo.d63b7f9.png.</p> | 50,284,329 | 2 | 0 | null | 2018-05-11 01:49:37.42 UTC | 2 | 2021-04-13 11:18:10.01 UTC | null | null | null | null | 5,692,673 | null | 1 | 29 | node.js|express|vue.js|cypress | 23,525 | <p>I figured out the solution on my own.</p>
<pre><code>cy.get('form').find('img').should('have.attr', 'src').should('include','My-Logo')
</code></pre>
<p>I inspected the element and found the <code><img src...</code> line was embedded within a <code><form></code>. I could do a <code>cy.get('form')</code> and pass, but could not do a <code>cy.get('img')</code> to pass. So then I chained them together and it passed. I am not sure why I cannot just simply add the second should statement, but it failed when I tried to just run:</p>
<pre><code>cy.get('form').find('img').should('include','My-Logo')
</code></pre>
<p>I am not entirely sure why, but it needed the first "should" statement. I got around VUE adding the sequence of numbers and letters by just asking for the name of the file without the extension. I hope this maybe helps someone else as the documentation did not seem to cover this.</p> |
22,405,085 | Mocking $httpBackend - how to handle "Unexpected request, No more request expected"? | <p>I have a Jasmine test that is coded like this:</p>
<pre><code> it ("should send correct message to server to get data, and correctly set up scope when receiving it", function(){
$httpBackend.when('GET', 'https://localhost:44300/api/projectconfiguration/12').respond(fakedDtoBase);
$routeParams.projectId=fakeId; // user asks for editing project
scope.$apply(function(){
var controller=controllerToTest(); // so controller gets data when it is created
});
expect(scope.projectData).toEqual(fakedDtoBase);
});
</code></pre>
<p>and it kind of works, but I get the error:</p>
<pre><code>Error: Unexpected request: GET views/core/main/main.html
No more request expected
at $httpBackend (C:/SVN/src/ClientApp/client/bower_components/angular-mocks/angular-mocks.js:1207:9)
at sendReq (C:/SVN/src/ClientApp/client/bower_components/angular/angular.js:7800:9)
at $http.serverRequest (C:/SVN/src/ClientApp/client/bower_components/angular/angular.js:7534:16)
(more stack trace)....
</code></pre>
<p>I do realise that I can mock every other call. But let's say I do not care what else my test wants to load as it may call few other things.
How I can make sure that every other requests just "happen silently", maybe offering a single dummy response for everything else?</p> | 22,405,251 | 4 | 0 | null | 2014-03-14 12:32:28.573 UTC | 11 | 2021-10-27 06:20:30.857 UTC | 2014-03-30 16:51:26.607 UTC | null | 2,256,325 | null | 820,947 | null | 1 | 36 | angularjs|jasmine|karma-runner | 58,181 | <p>Your test fails because a request is made which you haven't specified.</p>
<p>Try to add:</p>
<pre><code>$httpBackend.when('GET', 'views/core/main/main.html').respond(fakedMainResponse);
</code></pre>
<p>Of course you should also define <code>fakedMainResponse</code>.</p>
<p>Please take a look also at the <a href="http://docs.angularjs.org/api/ngMock/service/$httpBackend">documentation</a> (section Request Expectations vs Backend Definitions) which says:</p>
<blockquote>
<p>Request expectations provide a way to make assertions about requests
made by the application and to define responses for those requests.
<strong>The test will fail if the expected requests are not made or they are
made in the wrong order.</strong></p>
</blockquote>
<p>The second paramete of <code>$httpBackend.when</code> is actually a <code>RegExp</code>. So if you provide a <code>RegExp</code> that will match all other requests it should work. </p> |
3,136,453 | Immutable queue in Clojure | <p>What is the best way to obtain a simple, efficient immutable queue data type in Clojure?</p>
<p>It only needs two operations, enqueue and dequeue with the usual semantics.</p>
<p>I considered lists and vectors of course, but I understand that they have comparatively poor performance (i.e. O(n) or worse) for modifications at the end and beginning respectively - so not ideal for queues!</p>
<p>Ideally I'd like a proper persistent data structure with O(log n) for both enqueue and dequeue operations.</p> | 3,136,693 | 3 | 5 | null | 2010-06-28 21:57:50.943 UTC | 7 | 2016-10-08 00:28:11.53 UTC | null | null | null | null | 214,010 | null | 1 | 35 | algorithm|data-structures|clojure|queue|immutability | 6,537 | <p>Problem solved - solution for others who may find it helpful.</p>
<p>I've found that Clojure has the clojure.lang.PersistentQueue class that does what is needed.</p>
<p>You can create an instance like this:</p>
<pre><code>(def x (atom clojure.lang.PersistentQueue/EMPTY))
</code></pre>
<p>As far as I can see, you currently need to use the Java interop to create the instance but as Michal helpfully pointed out you can use peek, pop and conj subsequently.</p> |
2,935,784 | What is the "Roster" in XMPP? | <p>I'm learning XMPP and I repeatedly see the word "Roster" but I have no idea what it is.</p> | 2,935,789 | 3 | 0 | null | 2010-05-29 16:28:33.153 UTC | 14 | 2017-04-11 09:24:57.01 UTC | 2017-04-11 09:24:57.01 UTC | null | 1,529,709 | null | 100,015 | null | 1 | 79 | xmpp | 29,676 | <blockquote>
<p>contact list (in XMPP this is called a "roster")</p>
</blockquote>
<p>Source: <a href="http://xmpp.org/rfcs/rfc6121.html#intro-requirements" rel="noreferrer">XMPP-IM - RFC 6121 § 1.3: Requirements</a></p> |
2,847,185 | How to programmatically trigger the click on a link using jQuery? | <p>How to programmatically trigger the click on a link using jQuery?</p> | 2,847,191 | 4 | 2 | null | 2010-05-17 07:06:51.08 UTC | 3 | 2019-03-12 15:45:27.217 UTC | 2019-03-12 15:45:27.217 UTC | null | 107,625 | null | 179,855 | null | 1 | 79 | jquery | 83,372 | <pre><code>$('#your_link_id').click()
</code></pre>
<p>See the excellent jquery <a href="http://api.jquery.com/click/" rel="noreferrer">docs</a> for more information</p> |
29,303,155 | How does Spring Batch transaction management work? | <p>I'm trying to understand how Spring Batch does transaction management. This is not a technical question but more of conceptual one: what approach does Spring Batch use and what are the consequences of that approach?</p>
<p>Let me try to clarify this question a bit. For instance, looking at the TaskletStep, I see that generally a step execution looks something like this:</p>
<ol>
<li>several <em>JobRepository transactions</em> to prepare the step metadata</li>
<li>a <em>business transaction</em> for every chunk to process</li>
<li>more <em>JobRepository transactions</em> to update the step metadata with the results of chunk processing</li>
</ol>
<p>This seems to make sense. But what about a failure between 2 and 3? This would mean the business transaction was committed but Spring Batch was unable to record that fact in its internal metadata. So a restart would reprocess the same items again even though they have already been committed. Right?</p>
<p>I'm looking for an explanation of these details and the consequences of the design decisions made in Spring Batch. Is this documented somewhere? The Spring Batch reference guide has very few details on this. It simply explains things from the application developer's point of view.</p> | 29,304,822 | 1 | 0 | null | 2015-03-27 14:31:29.087 UTC | 10 | 2022-02-10 15:08:08.47 UTC | null | null | null | null | 1,688,586 | null | 1 | 17 | spring-batch | 28,667 | <p>There are two fundamental types of steps in Spring Batch, a Tasklet Step and a chunk based step. Each has it's own transaction details. Let's look at each:</p>
<p><strong>Tasklet Based Step</strong><br>
When a developer implements their own tasklet, the transactionality is pretty straight forward. Each call to the <code>Tasklet#execute</code> method is executed within a transaction. You are correct in that there are updates before and after a step's logic is executed. They are not technically wrapped in a transaction since rollback isn't something we'd want to support for the job repository updates.</p>
<p><strong>Chunk Based Step</strong><br>
When a developer uses a chunk based step, there is a bit more complexity involved due to the added abilities for skip/retry. However, from a simple level, each chunk is processed in a transaction. You still have the same updates before and after a chunk based step that are non-transactional for the same reasons previously mentioned.</p>
<p><strong>The "What if" scenario</strong><br>
In your question, you ask about what would happen if the business logic completed but the updates to the job repository failed for some reason. Would the previously updated items be re-processed on a restart. As in most things, that depends. If you are using stateful readers/writers like the <code>FlatFileItemReader</code>, with each commit of the business transaction, the job repository is updated with the current state of what has been processed (within the same transaction). So in that case, a restart of the job would pick up where it left off...in this case at the end, and process no additional records.</p>
<p>If you are not using stateful readers/writers or have save state turned off, then it is a bit of buyer beware and you may end up with the situation you describe. The default behavior in the framework is to save state so that restartability is preserved.</p> |
36,292,620 | Elixir: When to use .ex and when .exs files | <p>Elixir's documentation <a href="https://elixir-lang.org/getting-started/modules-and-functions.html#scripted-mode" rel="noreferrer">states</a> that</p>
<blockquote>
<p>In addition to the Elixir file extension .ex, Elixir also supports
.exs files for scripting. Elixir treats both files exactly the same
way, the only difference is in intention. .ex files are meant to be
compiled while .exs files are used for scripting, without the need for
compilation.</p>
</blockquote>
<p>But I'm still not sure when to use which file type. What are the downsides and the purpose of .ex and .exs?</p> | 36,293,239 | 4 | 0 | null | 2016-03-29 18:45:35.9 UTC | 13 | 2021-10-06 16:04:42.993 UTC | 2020-03-01 06:52:17.547 UTC | null | 1,417,451 | null | 69,349 | null | 1 | 93 | elixir | 22,770 | <p><code>.ex</code> is for compiled code, <code>.exs</code> is for interpreted code.</p>
<p>ExUnit tests, for example, are in <code>.exs</code> files so that you don't have to recompile every time you make a change to your tests. If you're writing scripts or tests, use <code>.exs</code> files. Otherwise, just use <code>.ex</code> files and compile your code.</p>
<p>As far as pros/cons, interpretation will take longer to execute (as elixir has to parse, tokenize, etc.), but doesn't require compilation to run. That's pretty much it - if the flexibility of running scripts is more important than optimized execution time, use <code>.exs</code>. Most of the time, you'll use <code>.ex</code>.</p> |
49,290,526 | Is there any straightforward way for Clap to display help when no command is provided? | <p>I'm using <a href="https://crates.io/crates/clap" rel="noreferrer">the Clap crate</a> for parsing command line parameters. I've defined a subcommand <code>ls</code> that should list files. Clap also defines a <code>help</code> subcommand that displays information about the application and its usage.</p>
<p>If no command is provided, nothing gets displayed at all, but I want the app to display help in that case.</p>
<p>I've tried this code, which looks pretty straightforward, but it doesn't work:</p>
<pre><code>extern crate clap;
use clap::{App, SubCommand};
fn main() {
let mut app = App::new("myapp")
.version("0.0.1")
.about("My first CLI APP")
.subcommand(SubCommand::with_name("ls").about("List anything"));
let matches = app.get_matches();
if let Some(cmd) = matches.subcommand_name() {
match cmd {
"ls" => println!("List something here"),
_ => eprintln!("unknown command"),
}
} else {
app.print_long_help();
}
}
</code></pre>
<p>I get an error that <code>app</code> is used after move:</p>
<pre class="lang-none prettyprint-override"><code>error[E0382]: use of moved value: `app`
--> src/main.rs:18:9
|
10 | let matches = app.get_matches();
| --- value moved here
...
18 | app.print_long_help();
| ^^^ value used here after move
|
= note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` trait
</code></pre>
<p>Reading through the documentation of Clap, I've found that the <code>clap::ArgMatches</code> that's returned in <code>get_matches()</code> has a method <a href="https://docs.rs/clap/2.31.1/clap/struct.ArgMatches.html#method.usage" rel="noreferrer"><code>usage</code></a> that returns the string for usage part, but, unfortunately, only this part and nothing else.</p> | 49,290,687 | 2 | 0 | null | 2018-03-15 02:16:41.493 UTC | 6 | 2022-03-16 12:42:08.04 UTC | 2021-07-15 01:40:02.123 UTC | null | 684,619 | null | 1,105,235 | null | 1 | 33 | rust|command-line-interface|clap | 5,863 | <p>Use <a href="https://docs.rs/clap/2.31.1/clap/enum.AppSettings.html#variant.ArgRequiredElseHelp" rel="noreferrer"><code>clap::AppSettings::ArgRequiredElseHelp</code></a>:</p>
<pre><code>App::new("myprog")
.setting(AppSettings::ArgRequiredElseHelp)
</code></pre>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/q/40951538/155423">Method call on clap::App moving ownership more than once</a></li>
</ul> |
49,087,643 | GraphQL Java client library | <p>I am looking for a java <em>client</em> library for GraphQL.
This is to use for server-to-server communication, both in java.
No android, not javascript... just java.
Apollo is the nearest answer, and it seems like it is for Android only, not for plain-java applications.
Lots of examples about build server in java, nothing about client.
Any idea?
Thanks!</p> | 49,273,780 | 1 | 0 | null | 2018-03-03 18:24:57.367 UTC | 4 | 2021-06-09 07:47:27.263 UTC | null | null | null | null | 9,439,222 | null | 1 | 32 | java|client|graphql | 12,520 | <p>There's a few clients available, all taking different approaches.</p>
<ol>
<li><a href="https://github.com/apollographql/apollo-android" rel="nofollow noreferrer">Apollo Android</a> - Originally intended for Android, but equally usable in any Java project. Someone also made a <a href="https://github.com/Sparow199/apollo-client-maven-plugin" rel="nofollow noreferrer">Maven plugin</a> for it.</li>
<li><a href="https://github.com/Shopify/graphql_java_gen" rel="nofollow noreferrer">Shopify's GraphQL Java gen</a> - Similar to what
wsdl2java does, for example, but not wrapped into a Maven plugin.
Generates a nice client, but requires Ruby... It's worth investigating if the Ruby dependency can be satisfied using JRuby JAR.</li>
<li><a href="https://github.com/americanexpress/nodes" rel="nofollow noreferrer">Nodes</a> A GraphQL JVM Client designed for constructing queries from standard model definitions. By American Express</li>
<li><a href="http://manifold.systems/docs.html#graphql" rel="nofollow noreferrer">Manifold</a> can be used as a GraphQL client</li>
<li><a href="https://github.com/ExpediaGroup/graphql-kotlin/" rel="nofollow noreferrer">graphql-kotlin</a> GraphQL Kotlin provides a set of lightweight type-safe GraphQL HTTP clients. The library provides Ktor HTTP client and Spring WebClient based reference implementations as well as allows for custom implementations using other engines. Type-safe data models are generated at build time by the GraphQL Kotlin Gradle and Maven plugins.</li>
</ol> |
179,510 | CSS - Is there a way to get rid of the selection rectangle after clicking a link? | <p>Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely?</p> | 179,532 | 2 | 0 | null | 2008-10-07 17:26:20.18 UTC | 9 | 2020-02-22 18:00:54.507 UTC | 2008-10-17 17:13:30.92 UTC | Mark Brady | null | Matthias | 16,440 | null | 1 | 47 | css|hyperlink | 26,680 | <p>Do you mean the dotted outline of a target?</p>
<p>Try:</p>
<pre><code>:focus {
outline: 0;
}
</code></pre>
<p>This would remove all focus outlines. IT's essentially the same as onclick in JavaScript terms. You might prefer to apply this to <code>a:focus</code>.</p> |
458,362 | How do I list all loaded assemblies? | <p>In .Net, I would like to enumerate all loaded assemblies over all AppDomains. Doing it for my program's AppDomain is easy enough <code>AppDomain.CurrentDomain.GetAssemblies()</code>. Do I need to somehow access every AppDomain? Or is there already a tool that does this?</p> | 458,390 | 2 | 3 | null | 2009-01-19 17:10:51.537 UTC | 18 | 2022-08-02 14:03:40.297 UTC | 2009-04-25 10:01:39.313 UTC | null | 49,246 | Abtin | 52,515 | null | 1 | 110 | c#|.net|assemblies | 112,431 | <p><strong>Using Visual Studio</strong></p>
<ol>
<li>Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)</li>
<li>While debugging, show the Modules window (Debug > Windows > Modules)</li>
</ol>
<p>This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).</p>
<p><a href="https://i.stack.imgur.com/vEhgX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vEhgX.png" alt="enter image description here"></a></p>
<p><strong>Using Process Explorer</strong></p>
<p>If you want an external tool you can use the <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">Process Explorer</a> (freeware, published by Microsoft)</p>
<p>Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc. </p>
<p><strong>Programmatically</strong></p>
<p>Check <a href="https://stackoverflow.com/questions/383686/how-do-you-loop-through-currenlty-loaded-assemblies">this SO</a> question that explains how to do it.</p> |
2,795,031 | synchronizing audio over a network | <p>I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box.</p>
<p>However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener).</p>
<p><strong>My question is</strong> if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it.</p>
<p>Some products already solving the problem (however still not sufficient for my overall use-case):</p>
<p><a href="http://www.sonos.com" rel="noreferrer">http://www.sonos.com</a></p>
<p><a href="http://netchorus.com/" rel="noreferrer">http://netchorus.com/</a></p>
<p>Any pointers are most welcome.
Thanks.</p>
<p>PS: <a href="https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network">This related question</a> seems to have died long ago. </p> | 2,795,223 | 5 | 4 | null | 2010-05-08 17:44:29.71 UTC | 27 | 2019-02-23 03:15:27.39 UTC | 2017-05-23 10:29:52.607 UTC | null | -1 | null | 7,891 | null | 1 | 45 | algorithm|audio|synchronization|streaming | 23,833 | <p>Ryan Barrett wrote up his findings on <a href="http://snarfed.org/space/synchronizing_mp3_playback" rel="noreferrer">his blog</a>.</p>
<p>His solution involved using <a href="http://en.wikipedia.org/wiki/Network_Time_Protocol" rel="noreferrer">NTP</a> as a method to keep all the clocks in-sync:</p>
<blockquote>
<p>Seriously, though, there's only one
trick to p4sync, and that is how it
uses NTP. One host acts as the p4sync
server. The other p4sync clients
synchronize their system clocks to the
server's clock, using SNTP. When the
server starts playing a song, it
records the time, to the millisecond.
The clients then retrieve that
timestamp, calculate the difference
between current time from that
timestamp, and seek forward that far
into the song.</p>
</blockquote> |
2,583,928 | Prefilling gmail compose screen with HTML text | <p>I found out that in order to open a Gmail compose screen you'd have to be logged in and open the following link:</p>
<p><a href="https://mail.google.com/a/domain/?view=cm&fs=1&tf=1&source=mailto&to=WHOEVER%40COMPANY.COM&su=SUBJECTHERE&cc=WHOEVER%40COMPANY.COM&bcc=WHOEVER%40COMPANY.COM&body=PREPOPULATEDBODY" rel="nofollow noreferrer">https://mail.google.com/a/domain/?view=cm&fs=1&tf=1&source=mailto&to=WHOEVER%40COMPANY.COM&su=SUBJECTHERE&cc=WHOEVER%40COMPANY.COM&bcc=WHOEVER%40COMPANY.COM&body=PREPOPULATEDBODY</a></p>
<p>Replacing the variables fills in the corresponding places on the compose form. However if I want to enter into the body multiline text or line breaks its just not working even if I urlencode it. Any ideas here?</p> | 2,585,630 | 6 | 4 | null | 2010-04-06 09:56:34.16 UTC | 12 | 2021-01-01 02:42:37.5 UTC | 2021-01-01 02:42:37.5 UTC | null | 1,783,163 | null | 89,752 | null | 1 | 12 | html|gmail|urlencode | 17,464 | <p>Check that your UrlEncode method really translates newlines into "%0a". Here's an example of a 2-line email body:</p>
<p><a href="https://mail.google.com/mail/?view=cm&ui=2&tf=0&fs=1&to=WHOEVER%40COMPANY.COM&su=SUBJECTHERE&body=LINE1%0aLINE2" rel="noreferrer">https://mail.google.com/mail/?view=cm&ui=2&tf=0&fs=1&to=WHOEVER%40COMPANY.COM&su=SUBJECTHERE&body=LINE1%0aLINE2</a></p> |
2,892,615 | How to remove auto focus/keyboard popup of a field when the screen shows up? | <p>I have a screen where the first field is an EditText, and it gains the focus at startup, also popups the numeric input type, which is very annoying</p>
<p>How can I make sure that when the activity is started the focus is not gained, and/or the input panel is not raised?</p> | 6,095,753 | 9 | 0 | null | 2010-05-23 16:58:58.48 UTC | 18 | 2020-07-22 08:51:23.733 UTC | 2018-04-13 09:20:18.537 UTC | null | 934,646 | null | 243,782 | null | 1 | 111 | android|keyboard|popup|android-softkeyboard | 83,183 | <pre><code>InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextField.getWindowToken(), 0);
</code></pre>
<p>or</p>
<p>set activity property in manifest file as below in the application tag</p>
<pre><code>android:windowSoftInputMode="stateHidden"
</code></pre> |
2,836,256 | Passing enum or object through an intent (the best solution) | <p>I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.</p>
<p>Basically I need a way to pass these objects to the activity from an Intent. I can use addExtras() but this requires a Parceable compatible class. I could make my classes to be passed serializable but as I understand this slows down the program.</p>
<p>What are my options?</p>
<p>Can I pass an Enum?</p>
<p>As an aside: is there a way to pass parameters to an Activity Constructor from an Intent?</p> | 9,753,178 | 15 | 1 | null | 2010-05-14 17:32:51.443 UTC | 47 | 2020-12-14 12:55:49.61 UTC | 2020-12-14 12:55:49.61 UTC | null | 1,306,012 | null | 248,521 | null | 1 | 246 | android | 120,628 | <p>This is an old question, but everybody fails to mention that Enums are actually <code>Serializable</code> and therefore can perfectly be added to an Intent as an extra. Like this:</p>
<pre><code>public enum AwesomeEnum {
SOMETHING, OTHER;
}
intent.putExtra("AwesomeEnum", AwesomeEnum.SOMETHING);
AwesomeEnum result = (AwesomeEnum) intent.getSerializableExtra("AwesomeEnum");
</code></pre>
<p>The suggestion to use static or application-wide variables is a really bad idea. This really couples your activities to a state managing system, and it is hard to maintain, debug and problem bound. </p>
<hr>
<p><strong>ALTERNATIVES:</strong></p>
<p>A good point was noted by <a href="https://stackoverflow.com/users/1924348/tedzyc">tedzyc</a> about the fact that the solution provided by <a href="https://stackoverflow.com/users/698373/oderik">Oderik</a> gives you an error. However, the alternative offered is a bit cumbersome to use (even using generics).</p>
<p>If you are really worried about the performance of adding the enum to an Intent I propose these alternatives instead:</p>
<p><em>OPTION 1:</em></p>
<pre><code>public enum AwesomeEnum {
SOMETHING, OTHER;
private static final String name = AwesomeEnum.class.getName();
public void attachTo(Intent intent) {
intent.putExtra(name, ordinal());
}
public static AwesomeEnum detachFrom(Intent intent) {
if(!intent.hasExtra(name)) throw new IllegalStateException();
return values()[intent.getIntExtra(name, -1)];
}
}
</code></pre>
<p>Usage:</p>
<pre><code>// Sender usage
AwesomeEnum.SOMETHING.attachTo(intent);
// Receiver usage
AwesomeEnum result = AwesomeEnum.detachFrom(intent);
</code></pre>
<p><em>OPTION 2:</em>
(generic, reusable and decoupled from the enum)</p>
<pre><code>public final class EnumUtil {
public static class Serializer<T extends Enum<T>> extends Deserializer<T> {
private T victim;
@SuppressWarnings("unchecked")
public Serializer(T victim) {
super((Class<T>) victim.getClass());
this.victim = victim;
}
public void to(Intent intent) {
intent.putExtra(name, victim.ordinal());
}
}
public static class Deserializer<T extends Enum<T>> {
protected Class<T> victimType;
protected String name;
public Deserializer(Class<T> victimType) {
this.victimType = victimType;
this.name = victimType.getName();
}
public T from(Intent intent) {
if (!intent.hasExtra(name)) throw new IllegalStateException();
return victimType.getEnumConstants()[intent.getIntExtra(name, -1)];
}
}
public static <T extends Enum<T>> Deserializer<T> deserialize(Class<T> victim) {
return new Deserializer<T>(victim);
}
public static <T extends Enum<T>> Serializer<T> serialize(T victim) {
return new Serializer<T>(victim);
}
}
</code></pre>
<p>Usage:</p>
<pre><code>// Sender usage
EnumUtil.serialize(AwesomeEnum.Something).to(intent);
// Receiver usage
AwesomeEnum result =
EnumUtil.deserialize(AwesomeEnum.class).from(intent);
</code></pre>
<p><em>OPTION 3 (with Kotlin):</em></p>
<p>It's been a while, but since now we have Kotlin, I thought I would add another option for the new paradigm. Here we can make use of extension functions and reified types (which retains the type when compiling).</p>
<pre><code>inline fun <reified T : Enum<T>> Intent.putExtra(victim: T): Intent =
putExtra(T::class.java.name, victim.ordinal)
inline fun <reified T: Enum<T>> Intent.getEnumExtra(): T? =
getIntExtra(T::class.java.name, -1)
.takeUnless { it == -1 }
?.let { T::class.java.enumConstants[it] }
</code></pre>
<p>There are a few benefits of doing it this way. </p>
<ul>
<li>We don't require the "overhead" of an intermediary object to do the serialization as it's all done in place thanks to <code>inline</code> which will replace the calls with the code inside the function.</li>
<li>The functions are more familiar as they are similar to the SDK ones.</li>
<li>The IDE will autocomplete these functions which means there is no need to have previous knowledge of the utility class.</li>
</ul>
<p>One of the downsides is that, if we change the order of the Emums, then any old reference will not work. This can be an issue with things like Intents inside pending intents as they may survive updates. However, for the rest of the time, it should be ok.</p>
<p>It's important to note that other solutions, like using the name instead of the position, will also fail if we rename any of the values. Although, in those cases, we get an exception instead of the incorrect Enum value.</p>
<p>Usage:</p>
<pre><code>// Sender usage
intent.putExtra(AwesomeEnum.SOMETHING)
// Receiver usage
val result = intent.getEnumExtra<AwesomeEnum>()
</code></pre> |
25,058,007 | MongoDB difference between $orderby and Sort | <p>I want to fetch the latest document, which obviously is a single document, thus <code>findOne</code> should work fine. But <code>findOne</code> here returns the first document inserted. So I have two options now either use <code>$orderBy</code> with <code>findOne</code> or use <code>.sort()</code> function with <code>.limit()</code> in <code>find()</code></p>
<p>Using $orderBy it would look something like:</p>
<pre><code>db.collection.findOne({$query:{},$orderby:{_id:-1}})
</code></pre>
<p>And using sort:</p>
<pre><code>db.collection.find().sort({_id:-1}).limit(1).pretty()
</code></pre>
<p>Both work fine, I just wanted to know which query should I prefer here? In terms of performance, or does both of them work the same way internally and there is no such difference between the two.</p> | 37,954,176 | 2 | 0 | null | 2014-07-31 11:41:02.18 UTC | 7 | 2016-06-21 21:20:08.347 UTC | 2016-03-09 15:05:42.603 UTC | null | 324,381 | null | 3,045,515 | null | 1 | 19 | mongodb|mongoose | 41,108 | <p>As of Mongo 3.2, <code>$orderby</code> is <a href="https://docs.mongodb.com/manual/reference/operator/meta/orderby/" rel="noreferrer">deprecated</a>.</p>
<p>The <a href="https://docs.mongodb.com/manual/reference/operator/meta/orderby/" rel="noreferrer">docs explicitly say</a>:</p>
<blockquote>
<p>The $orderby operator is deprecated. Use cursor.sort() instead.</p>
</blockquote>
<p>Unfortunately, <code>findOne()</code> doesn't support the <code>sort()</code> method, so you'll need to switch to <code>find()</code>:</p>
<pre><code>db.collection.find({}).sort({'key': -1}).limit(1)
</code></pre>
<p>This will return a <code>cursor</code>, so you'll then need to pull the first result from the cursor.</p> |
25,107,774 | How do I send an HTTP GET request from a Chrome extension? | <p>I'm working on a chrome extension that sends a HTTP request using the method GET.</p>
<p>How do I send a GET to <code>www.example.com</code> with the parameter <code>par</code> with value <code>0</code>?</p>
<pre class="lang-none prettyprint-override"><code>https://www.example.com?par=0
</code></pre>
<p>(the server reads the parameter <code>par</code> and does something)</p>
<p>I found this article, talking about <a href="https://developer.chrome.com/extensions/xhr" rel="noreferrer">Cross-Origin XMLHttpRequest</a>, but I don't know how their example could help me.</p> | 25,107,925 | 1 | 0 | null | 2014-08-03 18:28:58.107 UTC | 15 | 2022-01-11 21:19:49.953 UTC | 2022-01-11 21:19:49.953 UTC | null | 3,889,449 | null | 3,903,910 | null | 1 | 66 | javascript|google-chrome|google-chrome-extension|get|xmlhttprequest | 75,502 | <p>First, you'll need to edit your <code>manifest.json</code> and add the permission for <code>www.example.com</code>:</p>
<ul>
<li><p>For the new <a href="https://developer.chrome.com/docs/extensions/mv3/intro/" rel="noreferrer">Manifest V3</a>, use the <code>host_permissions</code> field:</p>
<pre class="lang-json prettyprint-override"><code>{
"manifest_version": 3,
...
"host_permissions": [
"https://www.example.com/*"
],
...
}
</code></pre>
</li>
<li><p>If you are still using the old Manifest V2, use the <code>permissions</code> field:</p>
<pre class="lang-json prettyprint-override"><code>{
"manifest_version": 2,
...
"permissions": [
"https://www.example.com/*"
],
...
}
</code></pre>
</li>
</ul>
<p>Then in your background page (or somewhere else) you can do:</p>
<pre><code>fetch('http://www.example.com?par=0').then(r => r.text()).then(result => {
// Result now contains the response text, do what you want...
})
</code></pre>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch" rel="noreferrer">MDN doc for <code>fetch()</code></a>.</p>
<hr />
<p>Deprecated version using <code>XMLHttpRequest</code> (ES5):</p>
<pre><code>function callback() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
result = xhr.responseText;
// ...
}
}
};
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com?par=0", true);
xhr.onreadystatechange = callback;
xhr.send();
</code></pre>
<p><strong>NOTE</strong> the warning at the top of the relative <a href="https://developer.chrome.com/extensions/xhr" rel="noreferrer">documentation page</a>:</p>
<blockquote>
<p>In Manifest V3, <code>XMLHttpRequest</code> is not supported in background pages (provided by Service Workers). Please consider using its modern replacement, <code>fetch()</code></p>
</blockquote> |
23,725,816 | Dispatch event with data | <p>I'd like to dispatch an event that will pass some data to any event listeners that listen on that event.</p>
<p>Considering a function that fires an event:</p>
<pre><code>function click() {
const x = 'foo'
document.dispatchEvent(new CustomEvent('clicked'))
}
click()
</code></pre>
<p>How can I pass custom data to the event listener?</p>
<pre><code>document.addEventListener('clicked', function(e) {
console.log(x) // logs "foo"
})
</code></pre> | 23,725,973 | 2 | 0 | null | 2014-05-18 19:10:21.047 UTC | 10 | 2021-05-19 16:35:54.223 UTC | 2021-05-19 16:35:54.223 UTC | null | 13,604,898 | null | 1,814,486 | null | 1 | 76 | javascript|events|custom-events | 71,589 | <p>Perhaps you are looking for <code>event.detail</code></p>
<pre><code>new CustomEvent('eventName', {'detail': data})
</code></pre>
<p>Instead of data use x and in event listener you can access x using event.detail</p>
<pre><code>function getSelectionBounds() {
var x = (bounds["x"].toFixed(2));
var y = "xyz";
var selectionFired = new CustomEvent("selectionFired", {
"detail": {"x":x,"y":y }
});
document.dispatchEvent(selectionFired);
};
document.addEventListener("selectionFired", function (e) {
alert(e.detail.x+" "+e.detail.y);
});
</code></pre> |
5,696,801 | IIS 7.5 applicationHost.config file is not being updated | <p>I'm currently playing around with the Microsoft.Web.Administration (MWA) namespace in order to adjust our application to configure IIS 7.5 with the new API.
I understood that all IIS level changes should be expressed in the following file (I'm on Win2K8-R2): </p>
<pre>%WINDIR%\System32\inetsrv\config\applicationHost.config</pre>
<p>So, when I use the <code>ServerManager</code> object to commit the configuration changes the file should be updated accordingly.</p>
<p>After adding a new MIME type (programmatic with MWA) I did not see any changes in the <code>applicationHost.config file</code>, but I do see the new MIME type in the IIS manager window and IIS recognizes this MIME type without problems. Even after restating the OS - The config file does not contain the newly added MIME type, but the IIS manager window does list it.</p>
<p>Because my application pools are forced to 32-bit (<code>Enable32BitAppOnWin64 = true</code>), I thought that the related config file should be located under <code>%WINDIR%\SysWOW64\inetsrv\Config</code>, but (if it exists...) - it also does not change after the code commits the updates.</p>
<p>Can someone please explain this? Am I missing something (looking at the wrong file maybe?)? Can someone please shed some light on the <code>SysWOW64\inetsrv\config</code> directory?</p>
<p>This is my code for adding the MIME type:</p>
<pre><code>ServerManager manager = new ServerManager();
ConfigurationElementCollection staticContentCollection = manager
.GetApplicationHostConfiguration()
.GetSection("system.webServer/staticContent")
.GetCollection();
//MIMETypes is a string[] array, each object is {FileExt},{MIMETypeStr}
foreach (string pair in MIMETypes)
{
string[] mimeProps = pair.Split(',');
ConfigurationElement mimeTypeEl = staticContentCollection
.Where(a =>
(string)a.Attributes["fileExtension"].Value == mimeProps[0])
.FirstOrDefault();
if (mimeTypeEl != null)
{
staticContentCollection.Remove(mimeTypeEl);
}
ConfigurationElement mimeMapElement =
staticContentCollection.CreateElement("mimeMap");
mimeMapElement["fileExtension"] = mimeProps[0];
mimeMapElement["mimeType"] = mimeProps[1];
staticContentCollection.Add(mimeMapElement);
}
manager.CommitChanges();
//At this point all is working but the config file does not reflect the change
</code></pre> | 5,697,389 | 2 | 0 | null | 2011-04-17 22:10:47.403 UTC | 8 | 2016-03-14 13:10:49.593 UTC | 2011-04-18 00:02:17.183 UTC | null | 419 | null | 608,377 | null | 1 | 28 | iis-7.5|mime-types|applicationhost | 35,898 | <p>I just tried your code and it works fine. You are aware that this mime type is being added to the global mime type collection and not to a site?</p>
<p>It also gets added to the end of the <code><staticContent></code> list, this list isn't re-sorted when you do <code>ServerManager.CommitChanges()</code>.</p>
<p>Also on Windows 2008-R2 the correct location for <code>applicationHost.config</code> is at:</p>
<pre>C:\Windows\System32\inetsrv\config</pre>
<p>I'm guess you're either using notepad.exe or NotePad2 to open this file (32 bit editors can't open it). Notepad won't reload the file upon a change and NotePad2 needs to be told to display a file change notification (alt-F5), out of the box it won't. </p>
<p>Also try adding something unusual like <code>.xxx</code>, run your update then open the config file and do a search. I guarantee it'll be there.</p>
<p><strong>Update:</strong></p>
<p>Further to your comments below, I'm not sure how you're able to open <code>applicationHost.config</code> using NotePad++ or any 32-bit editor, I certainly can't. Can you download NotePad2 which is a 64-bit editor:</p>
<blockquote>
<p><a href="http://www.flos-freeware.ch/notepad2.html">http://www.flos-freeware.ch/notepad2.html</a></p>
</blockquote>
<p>The release candidate works just fine.</p>
<p>On a default install of any 64 bit Windows 2008 or Windows 7 there shouldn't be an <code>applicationHost.config</code> in the <code>C:\Windows\SysWOW64\inetsrv\Config</code> folder. I'm not sure why you'd be seeing one there.</p> |
5,790,965 | Return total records from SQL Server when using ROW_NUMBER | <p>I would like to return the total number of records in the database so I can set up pagination. How do I return the total number of records in the DB when using the following paging method in SQL Server 2008?</p>
<pre><code> ALTER PROCEDURE [dbo].[Nop_LoadAllOptimized]
(
@PageSize int = 20,
@PageNumber int = 1,
@WarehouseCombinationID int = 1,
@CategoryId int = 58,
@OrderBy int = 0,
@TotalRecords int = null OUTPUT
)
AS
BEGIN
WITH Paging AS (
SELECT rn = (ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @OrderBy = 0 AND @CategoryID IS NOT NULL AND @CategoryID > 0
THEN pcm.DisplayOrder END ASC,
CASE WHEN @OrderBy = 0
THEN p.[Name] END ASC,
CASE WHEN @OrderBy = 5
THEN p.[Name] END ASC,
CASE WHEN @OrderBy = 10
THEN wpv.Price END ASC,
CASE WHEN @OrderBy = 15
THEN wpv.Price END DESC,
CASE WHEN @OrderBy = 20
THEN wpv.Price END DESC,
CASE WHEN @OrderBy = 25
THEN wpv.UnitPrice END ASC
)), p.*, pcm.DisplayOrder, wpv.Price, wpv.UnitPrice FROM Nop_Product p
INNER JOIN Nop_Product_Category_Mapping pcm ON p.ProductID=pcm.ProductID
INNER JOIN Nop_ProductVariant pv ON p.ProductID = pv.ProductID
INNER JOIN Nop_ProductVariant_Warehouse_Mapping wpv ON pv.ProductVariantID = wpv.ProductVariantID
WHERE pcm.CategoryID = @CategoryId AND (wpv.Published = 1 AND pv.Published = 1 AND p.Published = 1 AND p.Deleted = 0)
AND wpv.WarehouseID IN (select WarehouseID from Nop_WarehouseCombination where UserWarehouseCombinationID = @WarehouseCombinationID)
)
SELECT TOP (@PageSize) * FROM Paging PG
WHERE PG.rn > (@PageNumber * @PageSize) - @PageSize
SET @TotalRecords = @@ROWCOUNT
END
</code></pre> | 5,791,178 | 2 | 4 | null | 2011-04-26 13:19:55.24 UTC | 16 | 2013-04-28 23:21:34.723 UTC | 2011-04-26 17:19:31.267 UTC | null | 21,234 | null | 520,712 | null | 1 | 30 | sql-server|paging|sql-server-2008-r2 | 32,351 | <p>I typically do it this way - never really checked whether it's very efficient from a performance point of view:</p>
<pre><code>WITH YourCTE AS
(
SELECT
(list of columns),
ROW_NUMBER() OVER (ORDER BY ......) AS 'RowNum'
FROM dbo.YourBaseTable
)
SELECT
*,
(SELECT MAX(RowNum) FROM YourCTE) AS 'TotalRows'
FROM
YourCTE
WHERE
RowNum BETWEEN 101 AND 150
</code></pre>
<p>Basically, the <code>RowNum</code> value will have values 1 through the total of rows (if you don't have a <code>PARTITION BY</code> in your CTE) and thus selecting <code>MAX(RowNum)</code>, you get the total number of rows.</p> |
33,336,396 | HTML/CSS close button overlapping right/upper corner | <p>Looking to place a button overlying, and partially outside parent div such as in this picture. MY attempts have it within the parent DIV. The picture below is what I am after.</p>
<p><a href="https://i.stack.imgur.com/0g4EA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0g4EA.png" alt="enter image description here"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
width: 80%;
border-radius: 25px;
border: 2px solid Black;
padding: 15px 15px 15px 15px;
margin: 20px 20px 20px 20px;
background: #A4D3EE;
overflow: auto;
box-shadow: 5px 5px 2px #888888;
position: relative;
}
#x {
position: relative;
float: right;
background: red;
color: white;
top: -10px;
right: -10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<button id = "x">
X
</button>
Text Text Text
Text Text Text
Text Text Text
</div></code></pre>
</div>
</div>
</p> | 33,336,458 | 1 | 0 | null | 2015-10-25 23:43:05.97 UTC | 9 | 2020-02-17 21:17:35.327 UTC | null | null | null | null | 4,618,774 | null | 1 | 21 | html|css | 57,806 | <p>I guess this is what you looking for:</p>
<p>Just add <code>position:absolute;</code> instead <code>relative</code></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
width: 80%;
/*border-radius: 25px;*/
border: 2px solid Black;
padding: 15px 15px 15px 15px;
margin: 20px 20px 20px 20px;
background: #A4D3EE;
overflow: visible;
box-shadow: 5px 5px 2px #888888;
position: relative;
}
#x {
position: absolute;
background: red;
color: white;
top: -10px;
right: -10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<button id = "x">
X
</button>
Text Text Text
Text Text Text
Text Text Text
</div></code></pre>
</div>
</div>
</p> |
30,803,440 | Delayed rendering of React components | <p>I have a React component with a number of child components in it. I want to render the child components not at once but after some delay (uniform or different for each of the children).</p>
<p>I was wondering - is there a way how to do this?</p> | 30,807,560 | 10 | 0 | null | 2015-06-12 12:45:03.653 UTC | 26 | 2022-03-17 06:18:55.39 UTC | null | null | null | null | 1,213,844 | null | 1 | 75 | javascript|reactjs | 170,146 | <p>I think the most intuitive way to do this is by giving the children a "wait" <code>prop</code>, which hides the component for the duration that was passed down from the parent. By setting the default state to hidden, React will still render the component immediately, but it won't be visible until the state has changed. Then, you can set up <code>componentWillMount</code> to call a function to show it after the duration that was passed via props.</p>
<pre><code>var Child = React.createClass({
getInitialState : function () {
return({hidden : "hidden"});
},
componentWillMount : function () {
var that = this;
setTimeout(function() {
that.show();
}, that.props.wait);
},
show : function () {
this.setState({hidden : ""});
},
render : function () {
return (
<div className={this.state.hidden}>
<p>Child</p>
</div>
)
}
});
</code></pre>
<p>Then, in the Parent component, all you would need to do is pass the duration you want a Child to wait before displaying it.</p>
<pre><code>var Parent = React.createClass({
render : function () {
return (
<div className="parent">
<p>Parent</p>
<div className="child-list">
<Child wait={1000} />
<Child wait={3000} />
<Child wait={5000} />
</div>
</div>
)
}
});
</code></pre>
<p><a href="http://jsbin.com/gepujalepa/1/edit?html,css,js,output" rel="noreferrer">Here's a demo</a></p> |
31,109,659 | How does collisionBitMask work? Swift/SpriteKit | <p>As far as I'm aware the default for Physics bodies is to bounce off each other when they hit each other until you set their collisionBitMask to an equal number.</p>
<p>However, I'm having a huge issue accomplishing what seems like it should be very simple because of collisionBitmasks I believe.</p>
<pre><code>let RedBallCategory : UInt32 = 0x1 << 1
let GreenBallCategory: UInt32 = 0x1 << 2
let RedBarCategory : UInt32 = 0x1 << 3
let GreenBarCategory : UInt32 = 0x1 << 4
let WallCategory : UInt32 = 0x1 << 5
greenBall.physicsBody?.categoryBitMask = GreenBallCategory
greenBall.physicsBody?.contactTestBitMask = RedBarCategory
greenBall.physicsBody?.collisionBitMask = GreenHealthCategory
redBall.physicsBody?.categoryBitMask = RedBallCategory
redBall.physicsBody?.contactTestBitMask = GreenBarCategory
redBall.physicsBody?.collisionBitMask = RedHealthCategory
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = borderBody
self.physicsBody?.friction = 0
borderBody.contactTestBitMask = RedBallCategory | GreenBallCategory
borderBody.categoryBitMask = WallCategory
</code></pre>
<p>So here I've got my 2 balls and my border body. I can get collision detection which I want, but when I add the border body's category bit mask, it allows the balls to both go through and off the screen, which I don't want.</p>
<p>I also want the balls to bounce off each other, but only when I comment out one of the ball's categoryBitMasks do they bounce. Otherwise they go through each other.</p>
<p>That makes absolutely no sense to me because each of these items has a different collisionbitmask. I also had it sometimes where setting all the numbers equal to 5 would allow everything to pass through each other, but then setting it all to 6 would allow everything to hit each other.</p>
<p>How exactly do collision bitmasks work and is there a proper way to manage a lot of crisscrossing collision rules?</p> | 31,111,039 | 2 | 0 | null | 2015-06-29 07:04:48.177 UTC | 16 | 2020-05-20 18:14:14.67 UTC | 2020-05-20 18:14:14.67 UTC | null | 1,028,230 | null | 4,988,582 | null | 1 | 27 | swift|sprite-kit|skphysicsbody | 14,020 | <p>You can't get desired behaviour because you haven't set category, contact and collision bit masks properly. Here is an example on how you can set this to work:</p>
<pre><code>greenBall.physicsBody?.categoryBitMask = GreenBallCategory //Category is GreenBall
greenBall.physicsBody?.contactTestBitMask = RedBarCategory | WallCategory //Contact will be detected when GreenBall make a contact with RedBar or a Wall (assuming that redBar's masks are already properly set)
greenBall.physicsBody?.collisionBitMask = GreenBallCategory | RedBallCategory | WallCategory //Collision will occur when GreenBall hits GreenBall, RedBall or hits a Wall
redBall.physicsBody?.categoryBitMask = RedBallCategory //Category is RedBall
redBall.physicsBody?.contactTestBitMask = GreenBarCategory | GreenBallCategory | WallCategory //Contact will be detected when RedBall make a contact with GreenBar , GreenBall or a Wall
redBall.physicsBody?.collisionBitMask = RedBallCategory | GreenBallCategory | WallCategory //Collision will occur when RedBall meets RedBall, GreenBall or hits a Wall
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = borderBody
self.physicsBody?.friction = 0
borderBody.contactTestBitMask = RedBallCategory | GreenBallCategory //Contact will be detected when red or green ball hit the wall
borderBody.categoryBitMask = WallCategory
borderBody.collisionBitMask = RedBallCategory | GreenBallCategory // Collisions between RedBall GreenBall and a Wall will be detected
</code></pre>
<p>I would recommend you to read docs about <a href="https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/#//apple_ref/occ/instp/SKPhysicsBody/categoryBitMask">categoryBitMask</a> which is a mask that defines which categories a physics body belongs to:</p>
<blockquote>
<p>Every physics body in a scene can be assigned to up to 32 different
categories, each corresponding to a bit in the bit mask. You define
the mask values used in your game. In conjunction with the
collisionBitMask and contactTestBitMask properties, you define which
physics bodies interact with each other and when your game is notified
of these interactions.</p>
</blockquote>
<p><a href="https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/#//apple_ref/occ/instp/SKPhysicsBody/contactTestBitMask">contactTestBitMask</a> - A mask that defines which categories of bodies cause intersection notifications with a current physics body. </p>
<blockquote>
<p>When two bodies share the same space, each body’s category mask is
tested against the other body’s contact mask by performing a logical
AND operation. If either comparison results in a nonzero value, an
SKPhysicsContact object is created and passed to the physics world’s
delegate. For best performance, only set bits in the contacts mask for
interactions you are interested in.</p>
</blockquote>
<p><a href="https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/#//apple_ref/occ/instp/SKPhysicsBody/collisionBitMask">collisionBitmask</a> - A mask that defines which categories of physics bodies can collide with this physics body.</p>
<blockquote>
<p>When two physics bodies contact each other, a collision may occur.
This body’s collision mask is compared to the other body’s category
mask by performing a logical AND operation. If the result is a nonzero
value, this body is affected by the collision. Each body independently
chooses whether it wants to be affected by the other body. For
example, you might use this to avoid collision calculations that would
make negligible changes to a body’s velocity.</p>
</blockquote>
<p>So basically, to set up all these, you should ask your self something like:</p>
<p>Okay, I have a green ball, and a red ball , and wall objects on the scene. Between which bodies I want collisions to occur, or when I want to register contacts? I want a green and a red ball to collide with each other and to collide against the walls. Not a problem. I will first set up categories properly, and then I will set collision bit masks like this:</p>
<pre><code>greenBall.collisionBitMask = GreenBallCategory | RedBallCategory | WallCategory; //greenBall will collide with greenBall, redBall and a wall
redBall.collisionBitMask = GreenBallCategory | RedBallCategory | WallCategory
wall.collisionBitMask = GreenBall | RedBall
</code></pre>
<p>Now, I want to detect when some contacts occur (in <code>didBeginContact</code>: method)... But I don't want to get notified about all possible contacts, but rather to be notified just about contacts between balls (contacts between balls and a wall will be ignored). So lets set <code>contactTestBitMasks</code> to achieve this:</p>
<pre><code>greenBall.contactTestBitMask = GreenBallCategory | RedBallCategory;
redBall.contactTestBitMask = GreenBallCategory | RedBallCategory;
</code></pre>
<p>And that's it. The important thing is when you not using contact detection, you should not set <code>contactTestBitMask</code>. This is because of performance reasons. If you don't need collision detection, and you are interested only in detecting contacts, you can set <code>collisionBitMask = 0</code>.</p>
<p>Important:</p>
<p>Make sure you have set physics world's contact delegate in order to use <code>didBeginContact</code> and <code>didEndContact</code> methods:</p>
<pre><code>self.physicsWorld.contactDelegate = self; //where self is a current scene
</code></pre>
<p>Hope this helps a bit.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.