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
2,785,670
Best way to get an Application Context into a static method in Android
<p>I'm working on an Android application that has several Activities. In it I have a class with several static methods. I would like to be able to call these methods from the different Activities. I'm using the static methods to load data from an xml file via a XmlResourceParser. To create a XmlResourceParser requires a call on the Application Context. So my question is, what is the best way to get a reference to the Application Context into the static methods? Have each Activity get it and pass it in? Store it somehow in a global variable? </p>
2,786,189
4
1
null
2010-05-07 01:43:12.317 UTC
4
2018-04-03 15:12:32.91 UTC
null
null
null
null
19,072
null
1
33
android|android-context
52,423
<p>The better way would be to pass the Activity object as parameter to the static functions.</p> <p>AFAIK, there is no such method which will give you the application context in the static method.</p>
29,152,170
What is the difference between mock.patch.object(... and mock.patch(
<p>I am trying to understand the difference between these two approaches of mocking a method. Could someone please help distinguish them? For this example, I use the passlib library.</p> <pre><code>from passlib.context import CryptContext from unittest import mock with mock.patch.object(CryptContext, 'verify', return_value=True) as foo1: mycc = CryptContext(schemes='bcrypt_sha256') mypass = mycc.encrypt('test') assert mycc.verify('tesssst', mypass) with mock.patch('passlib.context.CryptContext.verify', return_value=True) as foo2: mycc = CryptContext(schemes='bcrypt_sha256') mypass = mycc.encrypt('test') assert mycc.verify('tesssst', mypass) </code></pre>
29,152,283
1
0
null
2015-03-19 18:18:55.533 UTC
27
2015-03-19 18:31:28.603 UTC
null
null
null
null
2,317,172
null
1
99
python|unit-testing|mocking
29,416
<p>You already discovered the difference; <code>mock.patch()</code> takes a string which will be resolved to an object <em>when applying the patch</em>, <code>mock.patch.object()</code> takes a direct reference.</p> <p>This means that <code>mock.patch()</code> doesn't require that you import the object before patching, while <code>mock.patch.object()</code> does require that you import before patching.</p> <p>The latter is then easier to use if you already have a reference to the object.</p>
31,812,433
Pygame sceen.fill() not filling up the color properly
<p>I've just started learning Pygame . I'm following <a href="https://lorenzod8n.wordpress.com/2007/05/25/pygame-tutorial-1-getting-started/" rel="noreferrer">this</a> tutorial. I ran the following program but it shows black color instead of blue :</p> <pre><code>import pygame h = input("Enter the height of the window : ") w = input("Enter the width of the window : ") screen = pygame.display.set_mode((w,h)) running = True while running: event = pygame.event.poll() if event.type == pygame.QUIT: running=0 screen.fill((0,0,1)) pygame.display.flip() </code></pre>
31,812,552
2
1
null
2015-08-04 14:45:48.773 UTC
0
2020-07-17 01:46:57.213 UTC
2017-06-19 18:51:51.957 UTC
null
7,051,394
null
5,128,663
null
1
10
python|pygame
40,996
<p>For Blue color, you should use <code>255</code> as the third element in the tuple, not <code>1</code>.</p> <p>Example -</p> <pre><code>while running: event = pygame.event.poll() if event.type == pygame.QUIT: running=0 screen.fill((0,0,255)) pygame.display.flip() </code></pre>
37,710,848
ImportError: No module named 'resource'
<p>I am using python 3.5 and I am doing Algorithms specialization courses on Coursera. Professor teaching this course posted a program which can help us to know the time and memory associated with running a program. It has <code>import resource</code> command at the top. I tried to run this program along with the programs I have written in python and every time I received <code>ImportError: No module named 'resource'</code> </p> <p>I used the same code in ubuntu and have no errors at all. </p> <p>I followed suggestions in stackoverflow answers and I have tried adding PYTHONPATH PYTHONHOME and edited the PATH environment variable.</p> <p>I have no idea of what else I can do here.</p> <p>Is there any file that I can download and install it in the Lib or site-packages folder of my python installation ?</p>
37,713,583
2
0
null
2016-06-08 19:04:54.47 UTC
3
2018-12-18 22:45:53.967 UTC
null
null
null
null
6,065,030
null
1
22
python|python-3.x|resources
47,787
<p><code>resource</code> is a Unix specific package as seen in <a href="https://docs.python.org/2/library/resource.html" rel="noreferrer">https://docs.python.org/2/library/resource.html</a> which is why it worked for you in Ubuntu, but raised an error when trying to use it in Windows.</p>
28,774,194
Reset/revert a whole branch to another branches state?
<p>I have a branch <em>A</em> and a branch <em>B</em> (and some other branches).</p> <p>Lets say <em>A</em>'s commit history looks like:</p> <ul> <li>commit 5</li> <li>commit 4</li> <li>commit 3</li> <li>...</li> </ul> <p>And <em>B</em>'s commit history:</p> <ul> <li>some other commit</li> <li>commit 4</li> <li>merge of other stuff from branch <em>C</em> (into branch <em>B</em>)</li> <li>commit 3</li> <li>...</li> </ul> <p>Basically what I want is to "delete" all changes made by the commits <em>some other commit</em> and <em>merge of other stuff from branch C</em> to branch <em>B</em>.</p> <p>I want the working tree of branch <em>B</em> to be exactly the same like branch <em>A</em>'s working tree.</p> <p>How do I achieve this?</p>
28,774,320
5
0
null
2015-02-27 21:01:50.573 UTC
8
2021-10-22 15:13:07.223 UTC
2021-10-22 15:13:07.223 UTC
null
1,057,485
null
3,314,143
null
1
39
git|git-merge|git-reset|git-revert
37,798
<p>One way to achieve this is through <code>git reset</code>. While on branch <code>B</code> execute</p> <pre class="lang-sh prettyprint-override"><code>git reset --hard A </code></pre> <p>Thereafter, branch <code>B</code> points to the head-commit of <code>A</code>. The <code>--hard</code> option resets the index and working tree so that all tracked files are reset to the version in branch <code>A</code>. The old HEAD commit-ID of <code>A</code> is stored in <code>.git/ORIG_HEAD</code> in order to allow undoing the change.</p> <p>Alternatively - while not on branch <code>B</code> - you can delete branch <code>B</code> and re-created it like this:</p> <pre class="lang-sh prettyprint-override"><code>git branch -d B # delete branch B git branch B A # re-create branch B and let it point to the commit of branch A </code></pre> <p>Other than the first suggestion, this will leave the index and working tree untouched.</p>
33,802,336
Visualizing output of convolutional layer in tensorflow
<p>I'm trying to visualize the output of a convolutional layer in tensorflow using the function <code>tf.image_summary</code>. I'm already using it successfully in other instances (e. g. visualizing the input image), but have some difficulties reshaping the output here correctly. I have the following conv layer:</p> <pre class="lang-py prettyprint-override"><code>img_size = 256 x_image = tf.reshape(x, [-1,img_size, img_size,1], "sketch_image") W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) </code></pre> <p>So the output of <code>h_conv1</code> would have the shape <code>[-1, img_size, img_size, 32]</code>. Just using <code>tf.image_summary("first_conv", tf.reshape(h_conv1, [-1, img_size, img_size, 1]))</code> Doesn't account for the 32 different kernels, so I'm basically slicing through different feature maps here.</p> <p>How can I reshape them correctly? Or is there another helper function I could use for including this output in the summary?</p>
33,816,991
5
0
null
2015-11-19 11:14:26.003 UTC
22
2019-09-07 13:40:17.593 UTC
2017-08-24 15:54:47.397 UTC
null
2,464,597
null
867,505
null
1
37
tensorflow|conv-neural-network
23,096
<p>I don't know of a helper function but if you want to see all the filters you can pack them into one image with some fancy uses of <code>tf.transpose</code>.</p> <p>So if you have a tensor that's <code>images</code> x <code>ix</code> x <code>iy</code> x <code>channels</code></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; V = tf.Variable() &gt;&gt;&gt; print V.get_shape() TensorShape([Dimension(-1), Dimension(256), Dimension(256), Dimension(32)]) </code></pre> <p>So in this example <code>ix = 256</code>, <code>iy=256</code>, <code>channels=32</code></p> <p>first slice off 1 image, and remove the <code>image</code> dimension</p> <pre class="lang-py prettyprint-override"><code>V = tf.slice(V,(0,0,0,0),(1,-1,-1,-1)) #V[0,...] V = tf.reshape(V,(iy,ix,channels)) </code></pre> <p>Next add a couple of pixels of zero padding around the image</p> <pre class="lang-py prettyprint-override"><code>ix += 4 iy += 4 V = tf.image.resize_image_with_crop_or_pad(image, iy, ix) </code></pre> <p>Then reshape so that instead of 32 channels you have 4x8 channels, lets call them <code>cy=4</code> and <code>cx=8</code>.</p> <pre class="lang-py prettyprint-override"><code>V = tf.reshape(V,(iy,ix,cy,cx)) </code></pre> <p>Now the tricky part. <code>tf</code> seems to return results in C-order, numpy's default. </p> <p>The current order, if flattened, would list all the channels for the first pixel (iterating over <code>cx</code> and <code>cy</code>), before listing the channels of the second pixel (incrementing <code>ix</code>). Going across the rows of pixels (<code>ix</code>) before incrementing to the next row (<code>iy</code>).</p> <p>We want the order that would lay out the images in a grid. So you go across a row of an image (<code>ix</code>), before stepping along the row of channels (<code>cx</code>), when you hit the end of the row of channels you step to the next row in the image (<code>iy</code>) and when you run out or rows in the image you increment to the next row of channels (<code>cy</code>). so:</p> <pre class="lang-py prettyprint-override"><code>V = tf.transpose(V,(2,0,3,1)) #cy,iy,cx,ix </code></pre> <p>Personally I prefer <code>np.einsum</code> for fancy transposes, for readability, but it's not in <code>tf</code> <a href="https://github.com/tensorflow/tensorflow/issues/175" rel="noreferrer">yet</a>.</p> <pre class="lang-py prettyprint-override"><code>newtensor = np.einsum('yxYX-&gt;YyXx',oldtensor) </code></pre> <p>anyway, now that the pixels are in the right order, we can safely flatten it into a 2d tensor:</p> <pre class="lang-py prettyprint-override"><code># image_summary needs 4d input V = tf.reshape(V,(1,cy*iy,cx*ix,1)) </code></pre> <p>try <code>tf.image_summary</code> on that, you should get a grid of little images. </p> <p>Below is an image of what one gets after following all the steps here.</p> <p><a href="https://i.stack.imgur.com/7qYQ3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7qYQ3.png" alt="enter image description here"></a></p>
29,854,314
Debug on real Apple Watch: Application Verification Failed
<p>I tried to debug my WatchKit app on a real Apple Watch today. After hitting the Debug button in Xcode, the main iPhone app was installed properly, but the Apple Watch only displayed the message <strong>Failed to install xxx, error: Application Verification Failed</strong>. The WatchKit app doesn't install.</p> <p>I was aware of this: <a href="https://stackoverflow.com/questions/29450131/watchkit-app-rejected-for-failing-to-install">WatchKit App Rejected for &quot;Failing to Install&quot;</a> , but it didn't help because my Xcode project file is alright.</p> <p>How to make debug work on a real Apple Watch?</p>
29,854,315
5
0
null
2015-04-24 17:54:33.033 UTC
12
2015-10-02 10:34:25.763 UTC
2017-05-23 11:45:29.597 UTC
null
-1
null
284,811
null
1
58
ios|watchkit|apple-watch
16,980
<p>It turns out you also have to <strong>add the UDID of the Apple Watch</strong> to the Apple Developer Portal, and update your Development provisioning profile to include this UDID. </p> <p>The UDID can be obtained in <strong>Devices</strong> window of Xcode. After pairing, the info of the Apple Watch will automatically display below the info of your iPhone.</p> <p>At the time of writing, this seems to be documented nowhere, and the error message on the Apple Watch wasn't particularly helpful. So I wish this try-and-error lesson would save you some hassle.</p>
34,742,213
How to design URL to return data from the current user in a REST API?
<p>I have a REST based service where a user can return a list of their own books (this is a private list).</p> <p>The URL is currently <code>../api/users/{userId}/books</code></p> <p>With each call they will also be supplying an authentication token supplied earlier.</p> <p>My question(s) is:</p> <ol> <li><p>Is supplying the <code>userId</code> in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The <code>userId</code> is not strictly required.</p></li> <li><p>Would removing the <code>userId</code> break REST principles as <code>/users/books/</code> looks like it should return all books for all users?</p></li> <li><p>Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same <code>userId</code>?</p></li> </ol>
34,742,877
3
0
null
2016-01-12 11:16:31.26 UTC
8
2016-08-30 22:21:56.67 UTC
2016-01-12 13:45:15.577 UTC
null
1,426,227
null
592,192
null
1
11
rest|restful-authentication
4,367
<h2>Short answer</h2> <p>You could use <code>me</code> in the URL to refer to the <em>current user</em>. With this approach, you would have a URL as following: <code>/users/me/books</code>.</p> <h2>An answer for each question</h2> <blockquote> <p>Is supplying the <code>userId</code> in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The <code>userId</code> is not strictly required.</p> </blockquote> <p>You could consider doing something like this: <code>/users/me/books</code>. Where <code>me</code> refers to the <em>current user</em>. It's easier to understand than <code>/users/books</code>, which can be used to return all books from the users.</p> <p>For some flexibility, besides <code>/users/me/books</code>, you could support <code>/users/{userId}/books</code>.</p> <p>The URL <code>/users/me</code> can be used to return data from the current user. Many APIs, such as <a href="https://api.stackexchange.com/docsa">StackExchange</a>, <a href="https://developer.spotify.com/web-api/get-current-users-profile/" rel="noreferrer">Facebook</a>, <a href="https://developer.spotify.com/web-api/get-current-users-profile/" rel="noreferrer">Spotify</a> and <a href="https://developers.google.com/+/web/api/rest/latest/people/get" rel="noreferrer">Google+</a> adopt this approach. </p> <blockquote> <p>Would removing the <code>userId</code> break REST principles as <code>/users/books/</code> looks like it should return all books for all users?</p> </blockquote> <p>I don't think it will break any REST principles, but I think your resources will not be properly indetified. As I answered above, I would use <code>/users/me/books</code> and also support <code>/users/{userId}/books</code>.</p> <blockquote> <p>Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same <code>userId</code>?</p> </blockquote> <p>When using the <code>userId</code> in the URL to request private information from a user, there's no harm in checking if the token belongs to the user with the <code>userId</code> included in the URL.</p>
63,407,601
How is AutoFac better than Microsoft.Extensions.DependencyInjection?
<p>How is AutoFac better than Microsoft.Extensions.DependencyInjection? Autofac supports Property and Method injection (however I don't really understand where Property and Method injection might be useful).</p> <p>I mean why should I use AutoFac when I can do the same thing by Microsoft.Extensions.DependencyInjection</p>
63,408,113
1
1
null
2020-08-14 06:23:35.227 UTC
10
2022-07-07 07:42:36.473 UTC
null
null
null
null
2,835,926
null
1
32
dependency-injection|autofac
11,664
<p>It's a fair question; fundamentally the difference is in the additional features Autofac can offer you if you need them. For simple applications, the Microsoft DI may offer enough functionality, but I've found as my application grows there's some extra features I find myself wanting/needing.</p> <p>The features that in my mind encouraged me to originally start using Aufofac are:</p> <ul> <li>Tagged lifetime scopes, and scoping services to those tags (<a href="https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope</a>)</li> <li>Resolving a service with some associated Metadata (<a href="https://autofaccn.readthedocs.io/en/latest/advanced/metadata.html" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/advanced/metadata.html</a>)</li> <li>Defining Named/Keyed variants of a service (<a href="https://autofaccn.readthedocs.io/en/latest/advanced/keyed-services.html" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/advanced/keyed-services.html</a>)</li> <li>Resolving a factory function that you can use whenever you want (<a href="https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#dynamic-instantiation-func-b" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#dynamic-instantiation-func-b</a>)</li> <li>Lazy Instantiation (<a href="https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#delayed-instantiation-lazy-b" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#delayed-instantiation-lazy-b</a>)</li> <li>The ability to combine all of these at your leisure (e.g. <code>Meta&lt;Lazy&lt;IMyService&gt;&gt;</code>)</li> </ul> <p>There's plenty more, but those are some of my favourite features. Check the docs for all the goodness.</p> <p>Also, there's no reason you can't start using the built-in DI and then add Autofac later when you realise you need it. The Autofac ASP.NET Core integration (<a href="https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html" rel="nofollow noreferrer">https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html</a>) will just pick up all your existing registrations, and then you can add those extra features on top.</p> <p>In the interest of full disclosure here, I will point out that I am one of the maintainers of Autofac.</p>
36,680,933
Discovering Generic Controllers in ASP.NET Core
<p>I am trying to create a generic controller like this:</p> <pre><code>[Route("api/[controller]")] public class OrdersController&lt;T&gt; : Controller where T : IOrder { [HttpPost("{orderType}")] public async Task&lt;IActionResult&gt; Create( [FromBody] Order&lt;T&gt; order) { //.... } } </code></pre> <p>I intend for the {orderType} URI segment variable to control the generic type of the controller. I'm experimenting with both a custom <code>IControllerFactory</code> and <code>IControllerActivator</code>, but nothing is working. Every time I try to send a request, I get a 404 response. The code for my custom controller factory (and activator) is never executed. </p> <p>Evidently the problem is that ASP.NET Core expects valid controllers to end with the suffix "Controller", but my generic controller instead has the (reflection based) suffix "Controller`1". Thus the attribute-based routes it declares are going unnoticed.</p> <p>In ASP.NET MVC, at least in its early days, <a href="https://msdn.microsoft.com/en-us/magazine/dd695917.aspx" rel="noreferrer">the <code>DefaultControllerFactory</code> was responsible for discovering all the available controllers</a>. It tested for the "Controller" suffix:</p> <blockquote> <p>The MVC framework provides a default controller factory (aptly named DefaultControllerFactory) that will search through all the assemblies in an appdomain looking for all types that implement IController and whose name ends with "Controller."</p> </blockquote> <p>Apparently, in ASP.NET Core, the controller factory no longer has this responsibility. As I stated earlier, my custom controller factory executes for "normal" controllers, but is never invoked for generic controllers. So there is something else, earlier in the evaluation process, which governs the discovery of controllers.</p> <p>Does anyone know what "service" interface is responsible for that discovery? I don't know the customization interface or "hook" point.</p> <p>And does anyone know of a way to make ASP.NET Core "dump" the names of all the controllers it discovered? It would be great to write a unit test that verifies that any custom controller discovery I expect is indeed working.</p> <p>Incidentally, if there is a "hook" which allows generic controller names to be discovered, it implies that route substitutions must also be normalized:</p> <pre><code>[Route("api/[controller]")] public class OrdersController&lt;T&gt; : Controller { } </code></pre> <p>Regardless of what value for <code>T</code> is given, the [controller] name must remain a simple base-generic name. Using the above code as an example, the [controller] value would be "Orders". It would not be "Orders`1" or "OrdersOfSomething".</p> <h2>Note</h2> <p>This problem could also be solved by explicitly declaring the closed-generic types, instead of generating them at run time:</p> <pre><code>public class VanityOrdersController : OrdersController&lt;Vanity&gt; { } public class ExistingOrdersController : OrdersController&lt;Existing&gt; { } </code></pre> <p>The above works, but it produces URI paths that I don't like:</p> <pre><code>~/api/VanityOrders ~/api/ExistingOrders </code></pre> <p>What I had actually wanted was this:</p> <pre><code>~/api/Orders/Vanity ~/api/Orders/Existing </code></pre> <p>Another adjustment gets me the URI's I'm looking for:</p> <pre><code>[Route("api/Orders/Vanity", Name ="VanityLink")] public class VanityOrdersController : OrdersController&lt;Vanity&gt; { } [Route("api/Orders/Existing", Name = "ExistingLink")] public class ExistingOrdersController : OrdersController&lt;Existing&gt; { } </code></pre> <p>However, although this appears to work, it does not really answer my question. I would like to use my generic controller directly at run-time, rather than indirectly (via manual coding) at compile-time. Fundamentally, this means I need ASP.NET Core to be able to "see" or "discover" my generic controller, despite the fact that its run-time reflection name does not end with the expected "Controller" suffix.</p>
36,684,144
4
0
null
2016-04-17 19:05:37 UTC
12
2017-12-05 13:05:48.29 UTC
2017-08-02 19:35:54.54 UTC
null
2,588,374
null
284,758
null
1
28
asp.net-mvc|asp.net-web-api|asp.net-core|url-routing
22,566
<h1>Short Answer</h1> <p>Implement <a href="https://github.com/aspnet/Mvc/blob/0d0aad41f501243f250b77613c015b4267e8c78d/src/Microsoft.AspNetCore.Mvc.Core/Controllers/ControllerFeatureProvider.cs#L15" rel="noreferrer"><code>IApplicationFeatureProvider&lt;ControllerFeature&gt;</code></a>. </p> <h1>Question and Answer</h1> <blockquote> <p>Does anyone know what "service" interface is responsible for [discovering all available controllers]?</p> </blockquote> <p>The <a href="https://github.com/aspnet/Mvc/blob/0d0aad41f501243f250b77613c015b4267e8c78d/src/Microsoft.AspNetCore.Mvc.Core/Controllers/ControllerFeatureProvider.cs#L15" rel="noreferrer"><code>ControllerFeatureProvider</code></a> is responsible for that. </p> <blockquote> <p>And does anyone know of a way to make ASP.NET Core "dump" the names of all the controllers it discovered?</p> </blockquote> <p>Do that within <a href="https://github.com/aspnet/Mvc/blob/0d0aad41f501243f250b77613c015b4267e8c78d/src/Microsoft.AspNetCore.Mvc.Core/Controllers/ControllerFeatureProvider.cs#L41" rel="noreferrer"><code>ControllerFeatureProvider.IsController(TypeInfo typeInfo)</code></a>.</p> <h1>Example</h1> <p>MyControllerFeatureProvider.cs</p> <pre><code>using System; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc.Controllers; namespace CustomControllerNames { public class MyControllerFeatureProvider : ControllerFeatureProvider { protected override bool IsController(TypeInfo typeInfo) { var isController = base.IsController(typeInfo); if (!isController) { string[] validEndings = new[] { "Foobar", "Controller`1" }; isController = validEndings.Any(x =&gt; typeInfo.Name.EndsWith(x, StringComparison.OrdinalIgnoreCase)); } Console.WriteLine($"{typeInfo.Name} IsController: {isController}."); return isController; } } } </code></pre> <p>Register it during startup. </p> <pre><code>public void ConfigureServices(IServiceCollection services) { services .AddMvcCore() .ConfigureApplicationPartManager(manager =&gt; { manager.FeatureProviders.Add(new MyControllerFeatureProvider()); }); } </code></pre> <p>Here is some example output. </p> <pre><code>MyControllerFeatureProvider IsController: False. OrdersFoobar IsController: True. OrdersFoobarController`1 IsController: True. Program IsController: False. &lt;&gt;c__DisplayClass0_0 IsController: False. &lt;&gt;c IsController: False. </code></pre> <p><a href="https://github.com/bigfont/StackOverflow/tree/937b13d1a720b9bc4d1dd3662d09cde8ee8b3c89/AspNetCoreCustomControllerNames" rel="noreferrer">And here is a demo on GitHub</a>. Best of luck.</p> <h1>Edit - Adding Versions</h1> <p>.NET Version</p> <pre><code>&gt; dnvm install "1.0.0-rc2-20221" -runtime coreclr -architecture x64 -os win -unstable </code></pre> <p>NuGet.Config</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;packageSources&gt; &lt;clear/&gt; &lt;add key="AspNetCore" value="https://www.myget.org/F/aspnetvnext/api/v3/index.json" /&gt; &lt;/packageSources&gt; &lt;/configuration&gt; </code></pre> <p>.NET CLI</p> <pre><code>&gt; dotnet --info .NET Command Line Tools (1.0.0-rc2-002429) Product Information: Version: 1.0.0-rc2-002429 Commit Sha: 612088cfa8 Runtime Environment: OS Name: Windows OS Version: 10.0.10586 OS Platform: Windows RID: win10-x64 </code></pre> <p>Restore, Build, and Run</p> <pre><code>&gt; dotnet restore &gt; dotnet build &gt; dotnet run </code></pre> <h1>Edit - Notes on RC1 vs RC2</h1> <p>This might not be possible is RC1, because <a href="https://github.com/aspnet/Mvc/blob/d420e4b8c3ec723392068c8828eaca69b2f862b6/src/Microsoft.AspNet.Mvc.Core/Controllers/DefaultControllerTypeProvider.cs#L49/Controllers/DefaultControllerTypeProvider.cs#L81-L85" rel="noreferrer"><code>DefaultControllerTypeProvider.IsController()</code></a> is marked as <code>internal</code>. </p>
64,201,624
Cannot create a proxy class for abstract class 'GoogleServicesTask'. with 'com.google.gms:google-services:4.3.4'
<p>Upgraded Fabrics crashlytics to Firebase last night.</p> <p>And when I tried to rebuild the app it had many issues, one by one I fixed those but got stuck with this last one:</p> <blockquote> <p>Cannot create a proxy class for abstract class 'GoogleServicesTask'</p> </blockquote> <p>app/build</p> <pre><code>buildscript { ext.kotlin_version = '1.3.41' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.4.2' classpath 'com.google.gms:google-services:4.3.4' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0' classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot; // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } </code></pre> <p>In my app/gradle file I have</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 29 defaultConfig { applicationId &quot;com.xxx.xxxx&quot; minSdkVersion 19 targetSdkVersion 29 versionCode 23 versionName &quot;1.1.2&quot; testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot; multiDexEnabled true vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled true shrinkResources true firebaseCrashlytics { mappingFileUploadEnabled false } proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug { minifyEnabled false shrinkResources false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = '1.8' targetCompatibility = '1.8' } } dependencies { my all dependencies} apply plugin: 'com.google.gms.google-services' </code></pre>
64,205,687
5
0
null
2020-10-05 02:07:11.53 UTC
1
2021-09-16 07:57:24.063 UTC
2020-10-11 11:50:19.713 UTC
null
13,302
null
13,766,626
null
1
29
android|firebase|crashlytics
22,598
<p>Better update this hopelessly outdated Android Gradle Plugin:</p> <pre><code>classpath &quot;com.android.tools.build:gradle:3.4.2&quot; </code></pre> <p>To a version, <em>which matches the version of Android Studio</em> ...</p> <pre><code>classpath &quot;com.android.tools.build:gradle:7.0.2&quot; </code></pre>
28,241,989
Flask app "Restarting with stat"
<p>I've built a few Flask apps, but on my latest project I noticed something a little strange in development mode. The second line of the usual message in the terminal which always reads:</p> <pre><code> * Running on http://127.0.0.1:5000/ * Restarting with reloader </code></pre> <p>has been replaced by:</p> <pre><code> * Restarting with stat </code></pre> <p>I don't think I've done anything different, in fact, I started by cloning a starter-kit project that I have used many times, which itself, does not display this behavior. I also notice that this project consumes about 15% CPU steadily, whereas my other project are barely a blip.</p> <p>Any ideas why this is happening?</p>
28,242,285
4
0
null
2015-01-30 18:05:19.187 UTC
16
2020-04-13 16:22:53.18 UTC
null
null
null
null
2,712,644
null
1
76
python|flask
62,982
<p>Check your version of Werkzeug. Version 0.10 was just released and numerous changes went into the reloader. One change is that a default polling reloader is used; the old pyinotify reloader was apparently inaccurate. If you want more efficient polling, install the <a href="https://pypi.python.org/pypi/watchdog" rel="noreferrer"><code>watchdog</code></a> package. You can see the code related to this <a href="https://github.com/mitsuhiko/werkzeug/blob/4e2c6746e565eaba7b3bd7489337580b62db610b/werkzeug/_reloader.py#L246-L251" rel="noreferrer">here</a>.</p> <p>When Werkzeug can't find watchdog, it uses the <code>stat</code> reloader, otherwise it uses whatever reloader watchdog uses, which can vary by platform. This message is just so you know which one is in use.</p> <hr> <p>Watchdog may not be compatible with gevent. If you're using gevent and having issues with the reloader when using Watchdog, check <a href="https://github.com/gorakhargosh/watchdog/issues/306" rel="noreferrer">this GitHub issue</a>.</p>
27,946,845
Get-AdUser where mail is not null
<p>I am trying to get a list of all users in AD that have an email (mail attribute). I have this command </p> <pre><code>Get-AdUser -filter * -Properties mail | Select SAMAccountName, mail | Export-CSV -Path $userPath -NoTypeInformation </code></pre> <p>The problem is that I do not know how to limit or filter out users where the email is null/blank. I do not care how complex the script is as it will be part of a much larger powershell script. If the solution is to loop through the CSV that is an option but would prefer something quicker. Does anyone know how to do this?</p>
27,947,032
3
0
null
2015-01-14 15:43:06.803 UTC
2
2016-06-20 11:17:33.917 UTC
null
null
null
null
2,113,038
null
1
4
email|powershell|active-directory
75,299
<p>Try this:</p> <pre><code>Get-ADUser -Properties mail -Filter {mail -like '*'} </code></pre>
27,005,819
Can't Delete AVD from AVD Manager in Android Studio
<p>I am running Android Studio on OS X Yosemite. I am trying to simply delete an AVD from Android Studio AVD Manager. Every time I attempt to delete it I get the message "The selected AVD is currently running in the Emulator. Please exit the emulator instance and try deleting again." The problem is that the emulator is NOT running. I even closed down all the studio and rebooted the computer. It still says the same thing. Anybody seen this before? I would really like to remove the AVD.</p> <p>Thanks in Advance!</p>
27,006,483
20
0
null
2014-11-18 23:03:40.737 UTC
7
2022-08-28 07:21:52.1 UTC
null
null
null
null
177,962
null
1
49
android|android-studio|avd
83,258
<p>Search for <code>*.lock</code> folders under <code>.android</code> folder and delete those. This should tell Android studio that the AVD is not running.</p>
40,379,139
Cannot find module 'webpack/bin/config-yargs'
<p>Getting error when running <code>webpack-dev-server --config config/webpack.dev.js --progress --profile --watch --content-base src/</code>. Here is the error log: </p> <pre><code>module.js:442 throw err; ^ Error: Cannot find module 'webpack/bin/config-yargs' at Function.Module._resolveFilename (module.js:440:15) at Function.Module._load (module.js:388:25) at Module.require (module.js:468:17) at require (internal/module.js:20:19) at Module._compile (module.js:541:32) at Object.Module._extensions..js (module.js:550:10) at Module.load (module.js:458:32) at tryModuleLoad (module.js:417:12) at Function.Module._load (module.js:409:3) </code></pre>
41,182,205
31
1
null
2016-11-02 11:43:59.207 UTC
34
2021-12-29 18:18:47.047 UTC
2021-01-30 10:29:10.077 UTC
null
1,323,496
null
5,374,960
null
1
228
webpack|webpack-dev-server
223,221
<p>I've had a similar problem. I think it's related to webpack version. After changing webpack version the latest everything was fine...</p>
57,247,240
Spring Boot JPA MySQL : Failed to determine a suitable driver class
<p>I am creating an application using Spring Boot JPA, I am using MySQL as a database.</p> <p>Following is my application.properties</p> <pre><code>spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect </code></pre> <p>I have added following dependencies</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;8.0.17&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>When I checked in debug logs I can see mysql java connector in my classpath but still I am getting following errors</p> <blockquote> <p>2019-07-29 10:03:00.742 INFO 10356 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-07-29 10:03:00.742 INFO 10356 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1534 ms 2019-07-29 10:03:00.789 WARN 10356 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class 2019-07-29 10:03:00.789 INFO 10356 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2019-07-29 10:03:00.805 INFO 10356 --- [ main] ConditionEvaluationReportLoggingListener : </p> <p>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2019-07-29 10:03:00.805 ERROR 10356 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : </p> <p>*************************** APPLICATION FAILED TO START</p> <hr> <p>Description:</p> <p>Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.</p> <p>Reason: Failed to determine a suitable driver class</p> <p>Action:</p> <p>Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the classpath. If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).</p> </blockquote>
57,271,644
6
0
null
2019-07-29 04:34:33.9 UTC
2
2021-04-20 08:26:45.953 UTC
null
null
null
null
479,020
null
1
3
mysql|hibernate|spring-boot
40,052
<p>It was some mistake in my configuration which I couldn't detect, I re-created same project and things started working</p>
3,172,416
Calculating window dragging and skewing in JavaScript
<p>I am using JavaScript and trying to make a skew effect on a div.</p> <p>First, take a look at this video: <a href="http://www.youtube.com/watch?v=ny5Uy81smpE" rel="noreferrer">http://www.youtube.com/watch?v=ny5Uy81smpE</a> (0:40-0:60 should be enough). The video shows some nice transformations (skew) when you move the window. What I want to do is the same thing: to skew a div when I move it.</p> <p>Currently I just have a plain simple div:</p> <pre><code>&lt;div id="a" style="background: #0f0; position: absolute; left: 0px; top: 0px;"&gt;&lt;/div&gt; </code></pre> <p>I have done a simple skew transformation using the CSS3's transform property, but my implementation is buggy. Are there good tutorials or maths sites or resources that describe the <strong>logic</strong> behind this? I know JavaScript and CSS well enough to implement, if I just knew the logic and maths. I tried reading <a href="http://gitweb.compiz.org/?p=users/warlock/freewins;a=tree" rel="noreferrer">FreeWins</a> source code, but I am not good in C.</p> <p>I am accepting any resourceful answers or pseudo code. My dragging system is part of a bigger system, thus, now that I post some real code, it does not work without giving you the entire system (that I can not do at this point). So, you can't run this code as is. The code I use is this (slightly modified though) to demonstrate my idea:</p> <pre><code>/** * The draggable object. */ Draggable = function(targetElement, options) { this.targetElement = targetElement; // Initialize drag data. this.dragData = { startX: null, startY: null, lastX: null, lastY: null, offsetX: null, offsetY: null, lastTime: null, occuring: false }; // Set the cursor style. targetElement.style.cursor = 'move'; // The element to move. this.applyTo = options.applyTo || targetElement; // Event methods for "mouse down", "up" and "move". // Mouse up and move are binded to window. // We can attach and deattach "move" and "up" events as needed. var me = this; targetElement.addEventListener('mousedown', function(event) { me.onMouseDown.call(me, event); }, false); this.mouseUp = function(event) { me.onMouseUp.call(me, event); }; this.mouseMove = function(event) { me.onMouseMove.call(me, event); }; }; /** * The mouse down event. * @param {Object} event */ Draggable.prototype.onMouseDown = function(event) { // New drag event. if (this.dragData.occuring === false) { this.dragData.occuring = true; this.dragData.startX = this.dragData.lastX = event.clientX; this.dragData.startY = this.dragData.lastY = event.clientY; this.dragData.offsetX = parseInt(this.applyTo.style.left, 10) - event.clientX; this.dragData.offsetY = parseInt(this.applyTo.style.top, 10) - event.clientY; this.dragData.lastTime = (new Date()).getTime(); // Mouse up and move events. var me = this; window.addEventListener('mousemove', this.mouseMove, false); window.addEventListener('mouseup', this.mouseUp, false); } }; /** * The mouse movement event. * @param {Object} event */ Draggable.prototype.onMouseMove = function(event) { if (this.dragData.occuring === true) { // He is dragging me now, we move if there is need for that. var moved = (this.dragData.lastX !== event.clientX || this.dragData.lastY !== event.clientY); if (moved === true) { var element = this.applyTo; // The skew animation. :) var skew = (this.dragData.lastX - event.clientX) * 1; var limit = 25; if (Math.abs(skew) &gt; limit) { skew = limit * (skew &gt; 0 ? 1 : -1); } var transform = 'translateX(' + (event.clientX + this.dragData.offsetX - parseInt(element.style.left, 10)) + 'px)'; transform += 'translateY(' + (event.clientY + this.dragData.offsetY - parseInt(element.style.top, 10)) + 'px)'; transform += 'skew(' + skew + 'deg)'; element.style.MozTransform = transform; element.style.webkitTransform = transform; this.dragData.lastX = event.clientX; this.dragData.lastY = event.clientY; this.dragData.lastTime = (new Date()).getTime(); } } }; /** * The mouse up event. * @param {Object} event */ Draggable.prototype.onMouseUp = function(event) { this.dragData.occuring = false; var element = this.applyTo; // Reset transformations. element.style.MozTransform = ''; element.style.webkitTransform = ''; // Save the new position. element.style.left = (this.dragData.lastX + this.dragData.offsetX) + 'px'; element.style.top = (this.dragData.lastY + this.dragData.offsetY) + 'px'; // Remove useless events. window.removeEventListener('mousemove', this.mouseMove, false); window.removeEventListener('mousemove', this.mouseUp, false); }; </code></pre> <p>Currently my dragging system is buggy and simple. I need more information on the logic that I should be applying.</p>
3,237,135
1
0
null
2010-07-03 18:25:10.983 UTC
16
2010-10-10 07:45:09.933 UTC
2010-07-13 13:43:30.38 UTC
null
378,024
null
283,055
null
1
18
javascript|math|user-interface|draggable|effect
1,245
<p>Wow, the idea <strong>rocks</strong>. :) I've cleaned your code a bit, and solved the problems with initialization. Now it works fine for me on Firefox and Chrome (even though you said it shouldn't).</p> <p>A few notes:</p> <ul> <li>you need to grab the starting <code>top</code> and <code>left</code> positions during initialization (<em>getBoundingClientRect</em>)</li> <li>store references like <code>this.dragData</code> and <code>element.style</code> for shortness and faster execution</li> <li><code>dragData</code> can be initialized as an empty object. It's fine in javascript. You can add properties later.</li> <li><code>options</code> should be conditionally initialized as an empty object, so that you can take zero options</li> <li><code>moved</code> and <code>dragData.occuring</code> were totally useless because of the event management</li> <li><code>preventDefault</code> is needed in order not to select text during dragging</li> <li>you may want to keep track of <code>z-indexes</code> to be the active element always visible</li> </ul> <p>Have fun!</p> <h2>Code [<a href="http://jsbin.com/aviyi3/25/" rel="noreferrer">See it in action</a>]</h2> <pre><code>/** * The draggable object. */ Draggable = function(targetElement, options) { this.targetElement = targetElement; // we can take zero options options = options || {}; // Initialize drag data. // @props: startX, startY, lastX, lastY, // offsetX, offsetY, lastTime, occuring this.dragData = {}; // Set the cursor style. targetElement.style.cursor = 'move'; // The element to move. var el = this.applyTo = options.applyTo || targetElement; // Event methods for "mouse down", "up" and "move". // Mouse up and move are binded to window. // We can attach and deattach "move" and "up" events as needed. var me = this; targetElement.addEventListener('mousedown', function(event) { me.onMouseDown.call(me, event); }, false); this.mouseUp = function(event) { me.onMouseUp.call(me, event); }; this.mouseMove = function(event) { me.onMouseMove.call(me, event); }; // initialize position, so it will // be smooth even on the first drag var position = el.getBoundingClientRect(); el.style.left = position.left + "px"; el.style.top = position.top + "px"; el.style.position = "absolute"; if (el.style.zIndex &gt; Draggable.zindex) Draggable.zindex = el.style.zIndex + 1; }; Draggable.zindex = 0; /** * Sets the skew and saves the position * @param {Number} skew */ Draggable.prototype.setSkew = function(skew) { var data = this.dragData; var style = this.applyTo.style; // Set skew transformations. data.skew = skew; style.MozTransform = skew ? 'skew(' + skew + 'deg)' : ''; style.webkitTransform = skew ? 'skew(' + skew + 'deg)' : ''; // Save the new position. style.left = (data.lastX + data.offsetX) + 'px'; style.top = (data.lastY + data.offsetY) + 'px'; } /** * The mouse down event. * @param {Object} event */ Draggable.prototype.onMouseDown = function(event) { var data = this.dragData; // New drag event. var style = this.applyTo.style; data.startX = data.lastX = event.clientX; data.startY = data.lastY = event.clientY; data.offsetX = parseInt(style.left, 10) - event.clientX; data.offsetY = parseInt(style.top, 10) - event.clientY; style.zIndex = Draggable.zindex++; data.lastTime = (new Date()).getTime(); // Mouse up and move events. window.addEventListener('mousemove', this.mouseMove, false); window.addEventListener('mouseup', this.mouseUp, false); event.preventDefault(); // prevent text selection }; /** * The mouse movement event. * @param {Object} event */ Draggable.prototype.onMouseMove = function(event) { // He is dragging me now var me = this; var data = me.dragData; var element = me.applyTo; var clientX = event.clientX; var clientY = event.clientY; data.moving = true; // The skew animation. :) var skew = (data.lastX - clientX) * 1; var limit = 25; if (Math.abs(skew) &gt; limit) { skew = limit * (skew &gt; 0 ? 1 : -1); } var style = element.style; var left = parseInt(style.left, 10); var top = parseInt(style.top, 10); var transform = 'translateX(' + (clientX + data.offsetX - left) + 'px)' + 'translateY(' + (clientY + data.offsetY - top) + 'px)' + 'skew(' + skew + 'deg)'; style.MozTransform = transform; style.webkitTransform = transform; data.lastX = clientX; data.lastY = clientY; data.lastTime = (new Date()).getTime(); // here is the cooldown part in order // not to stay in disorted state var pre = skew &gt; 0 ? 1 : -1; clearInterval(data.timer); data.timer = setInterval(function() { var skew = data.skew - (pre * 10); skew = pre * skew &lt; 0 ? 0 : skew; me.setSkew(skew); if (data.moving || skew === 0) clearInterval(data.timer); }, 20); data.moving = false; }; /** * The mouse up event. * @param {Object} event */ Draggable.prototype.onMouseUp = function(event) { this.setSkew(''); // Remove useless events. window.removeEventListener('mousemove', this.mouseMove, false); window.removeEventListener('mousemove', this.mouseUp, false); }; </code></pre>
47,776,486
python struct.error: 'i' format requires -2147483648 <= number <= 2147483647
<h3>Problem</h3> <p>I'm willing to do a feature engineering using multiprocessing module <code>(multiprocessing.Pool.starmap()</code>. However, it gives an error message as follows. I guess this error message is about the size of inputs (2147483647 = 2^31 − 1?), since the same code worked smoothly for a fraction<code>(frac=0.05)</code> of input dataframes(train_scala, test, ts). I convert types of data frame as smallest as possible, however it does not get better. </p> <p>The anaconda version is 4.3.30 and the Python version is 3.6 (64 bit). And the memory size of the system is over 128GB with more than 20 cores. Would you like to suggest any pointer or solution to overcome this problem? If this problem is caused by a large data for a multiprocessing module, How much smaller data should I use to utilize the multiprocessing module on Python3?</p> <p><strong>Code:</strong></p> <pre><code>from multiprocessing import Pool, cpu_count from itertools import repeat p = Pool(8) is_train_seq = [True]*len(historyCutoffs)+[False] config_zip = zip(historyCutoffs, repeat(train_scala), repeat(test), repeat(ts), ul_parts_path, repeat(members), is_train_seq) p.starmap(multiprocess_FE, config_zip) </code></pre> <p><strong>Error Message:</strong></p> <pre><code>Traceback (most recent call last): File "main_1210_FE_scala_multiprocessing.py", line 705, in &lt;module&gt; print('----Pool starmap start----') File "/home/dmlab/ksedm1/anaconda3/envs/py36/lib/python3.6/multiprocessing/pool.py", line 274, in starmap return self._map_async(func, iterable, starmapstar, chunksize).get() File "/home/dmlab/ksedm1/anaconda3/envs/py36/lib/python3.6/multiprocessing/pool.py", line 644, in get raise self._value File "/home/dmlab/ksedm1/anaconda3/envs/py36/lib/python3.6/multiprocessing/pool.py", line 424, in _handle_tasks put(task) File "/home/dmlab/ksedm1/anaconda3/envs/py36/lib/python3.6/multiprocessing/connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "/home/dmlab/ksedm1/anaconda3/envs/py36/lib/python3.6/multiprocessing/connection.py", line 393, in _send_bytes header = struct.pack("!i", n) struct.error: 'i' format requires -2147483648 &lt;= number &lt;= 2147483647 </code></pre> <h3>Extra infos</h3> <ul> <li>historyCutoffs is a list of integers</li> <li>train_scala is a pandas DataFrame (377MB)</li> <li>test is a pandas DataFrame (15MB)</li> <li>ts is a pandas DataFrame (547MB)</li> <li>ul_parts_path is a list of directories (string)</li> <li>is_train_seq is a list of booleans</li> </ul> <p><strong>Extra Code: Method multiprocess_FE</strong></p> <pre><code>def multiprocess_FE(historyCutoff, train_scala, test, ts, ul_part_path, members, is_train): train_dict = {} ts_dict = {} msno_dict = {} ul_dict = {} if is_train == True: train_dict[historyCutoff] = train_scala[train_scala.historyCutoff == historyCutoff] else: train_dict[historyCutoff] = test msno_dict[historyCutoff] = set(train_dict[historyCutoff].msno) print('length of msno is {:d} in cutoff {:d}'.format(len(msno_dict[historyCutoff]), historyCutoff)) ts_dict[historyCutoff] = ts[(ts.transaction_date &lt;= historyCutoff) &amp; (ts.msno.isin(msno_dict[historyCutoff]))] print('length of transaction is {:d} in cutoff {:d}'.format(len(ts_dict[historyCutoff]), historyCutoff)) ul_part = pd.read_csv(gzip.open(ul_part_path, mode="rt")) ##.sample(frac=0.01, replace=False) ul_dict[historyCutoff] = ul_part[ul_part.msno.isin(msno_dict[historyCutoff])] train_dict[historyCutoff] = enrich_by_features(historyCutoff, train_dict[historyCutoff], ts_dict[historyCutoff], ul_dict[historyCutoff], members, is_train) </code></pre>
47,776,649
2
0
null
2017-12-12 15:47:35.87 UTC
10
2020-05-09 12:30:02.823 UTC
2017-12-12 15:54:47.893 UTC
null
5,366,046
null
5,366,046
null
1
40
python|python-3.x|struct|multiprocessing|starmap
23,353
<p>The communication protocol between processes uses <em>pickling</em>, and the pickled data is prefixed with the size of the pickled data. For your method, <em>all arguments together</em> are pickled as one object.</p> <p>You produced an object that when pickled is larger than fits in a <code>i</code> struct formatter (a four-byte signed integer), which breaks the assumptions the code has made.</p> <p>You could delegate reading of your dataframes to the child process instead, only sending across the metadata needed to load the dataframe. Their combined size is nearing 1GB, way too much data to share over a pipe between your processes.</p> <p>Quoting from the <a href="https://docs.python.org/3/library/multiprocessing.html#programming-guidelines" rel="noreferrer"><em>Programming guidelines</em> section</a>:</p> <blockquote> <p><em>Better to inherit than pickle/unpickle</em></p> <p>When using the <code>spawn</code> or <code>forkserver</code> start methods many types from <code>multiprocessing</code> need to be picklable so that child processes can use them. <strong>However, one should generally avoid sending shared objects to other processes using pipes or queues. Instead you should arrange the program so that a process which needs access to a shared resource created elsewhere can inherit it from an ancestor process.</strong></p> </blockquote> <p>If you are not running on Windows and use either the <code>spawn</code> or <code>forkserver</code> methods, you could load your dataframes as globals <em>before</em> starting your subprocesses, at which point the child processes will 'inherit' the data via the normal OS copy-on-write memory page sharing mechanisms.</p> <p>Note that this limit was raised for non-Windows systems in Python 3.8, to an unsigned long long (8 bytes), and so you can now send and receive 4 <a href="https://en.wikipedia.org/wiki/Exbibyte" rel="noreferrer">EiB</a> of data. See <a href="https://github.com/python/cpython/commit/bccacd19fa7b56dcf2fbfab15992b6b94ab6666b" rel="noreferrer">this commit</a>, and Python issues <a href="https://bugs.python.org/issue35152" rel="noreferrer">#35152</a> and <a href="https://bugs.python.org/issue17560" rel="noreferrer">#17560</a>.</p> <p>If you can't upgrade and you can't make use of resource inheriting, and are not running on Windows, then use this patch:</p> <pre><code>import functools import logging import struct import sys logger = logging.getLogger() def patch_mp_connection_bpo_17560(): """Apply PR-10305 / bpo-17560 connection send/receive max size update See the original issue at https://bugs.python.org/issue17560 and https://github.com/python/cpython/pull/10305 for the pull request. This only supports Python versions 3.3 - 3.7, this function does nothing for Python versions outside of that range. """ patchname = "Multiprocessing connection patch for bpo-17560" if not (3, 3) &lt; sys.version_info &lt; (3, 8): logger.info( patchname + " not applied, not an applicable Python version: %s", sys.version ) return from multiprocessing.connection import Connection orig_send_bytes = Connection._send_bytes orig_recv_bytes = Connection._recv_bytes if ( orig_send_bytes.__code__.co_filename == __file__ and orig_recv_bytes.__code__.co_filename == __file__ ): logger.info(patchname + " already applied, skipping") return @functools.wraps(orig_send_bytes) def send_bytes(self, buf): n = len(buf) if n &gt; 0x7fffffff: pre_header = struct.pack("!i", -1) header = struct.pack("!Q", n) self._send(pre_header) self._send(header) self._send(buf) else: orig_send_bytes(self, buf) @functools.wraps(orig_recv_bytes) def recv_bytes(self, maxsize=None): buf = self._recv(4) size, = struct.unpack("!i", buf.getvalue()) if size == -1: buf = self._recv(8) size, = struct.unpack("!Q", buf.getvalue()) if maxsize is not None and size &gt; maxsize: return None return self._recv(size) Connection._send_bytes = send_bytes Connection._recv_bytes = recv_bytes logger.info(patchname + " applied") </code></pre>
47,803,081
Certbot Apache error "Name duplicates previous WSGI daemon definition."
<p>On my Ubuntu 16.04 server, I have an Apache conf file at <code>/etc/apache2/sites-enabled/000-default.conf</code>, which looks like this (abbreviated):</p> <pre><code>WSGIApplicationGroup %{GLOBAL} &lt;VirtualHost *:80&gt; ServerName example.com WSGIDaemonProcess myprocess user=ubuntu group=ubuntu threads=10 home=/home/ubuntu/myapp WSGIProcessGroup myprocess ... &lt;/VirtualHost&gt; </code></pre> <p>It works fine in HTTP mode, but when I run <code>$ sudo certbot --apache</code> to set up HTTPS, it fails with the error <code>Syntax error on line 7 of /etc/apache2/sites-enabled/000-default.conf: Name duplicates previous WSGI daemon definition.</code> Line 7 is the line beginning with <code>WSGIDaemonProcess</code>.</p>
47,803,231
3
0
null
2017-12-13 22:30:42.573 UTC
9
2019-11-12 12:48:47.51 UTC
2017-12-13 22:44:24.577 UTC
null
1,789,466
null
1,789,466
null
1
36
apache|ubuntu-16.04|mod-wsgi|lets-encrypt|certbot
8,286
<p>It turns out that if my Apache conf file <code>000-default.conf</code> <em>only</em> declares <code>&lt;VirtualHost *:80&gt;...&lt;/VirtualHost&gt;</code>, then Certbot duplicates it and creates a <em>second</em> Apache conf file called <code>000-default-le-ssl.conf</code> to define <code>&lt;VirtualHost *:443&gt;...&lt;/VirtualHost&gt;</code>.</p> <p>The <code>Name duplicates previous WSGI daemon definition</code> error appears because <em>both</em> Apache conf files have the same line defining <code>WSGIDaemonProcess myprocess...</code>. This appears to be a <a href="https://github.com/certbot/certbot/issues/4797" rel="noreferrer">known Certbot bug</a>.</p> <p>The workaround I've found is to <strong>define both VirtualHosts (80 and 443) in the <em>same</em> Apache conf file</strong> (so that Certbot doesn't create a second file), and to define <code>WSGIDaemonProcess</code> outside both VirtualHosts, like this:</p> <pre><code>WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess myprocess user=ubuntu group=ubuntu threads=10 home=/home/ubuntu/myapp WSGIProcessGroup myprocess &lt;VirtualHost *:80&gt; ServerName example.com ... &lt;/VirtualHost&gt; &lt;VirtualHost *:443&gt; ServerName example.com ... &lt;/VirtualHost&gt; </code></pre>
37,453,283
Filter options for sniff function in scapy
<p>I'm working on a scapy based tool where at a point I need to sniff a packet based on protocol and the ip address of the destination</p> <p>I'd like to know about the ways in which filter option in sniff() function can be used. I tried using format in documentation but most of the times it results in problems like this. <a href="https://stackoverflow.com/questions/30095701/the-filter-of-sniff-function-in-scapy-does-not-work-properly">the filter of sniff function in scapy does not work properly</a> .</p> <p>The one which I used was </p> <pre><code>a=sniff(filter="host 172.16.18.69 and tcp port 80",prn = comp_pkt,count = 1) </code></pre> <p>Thanks in advance!</p>
37,453,842
1
0
null
2016-05-26 06:37:23.073 UTC
3
2017-10-31 17:16:22.433 UTC
2017-05-23 10:30:59.047 UTC
null
-1
null
5,725,669
null
1
12
python|linux|networking|ethernet|scapy
41,274
<p><code>sniff()</code> uses Berkeley Packet Filter (BPF) <a href="http://biot.com/capstats/bpf.html" rel="noreferrer">syntax</a> (the same one as <code>tcpdump</code>), here are some examples:</p> <p>Packets from or to host:</p> <pre><code>host x.x.x.x </code></pre> <p>Only TCP SYN segments:</p> <pre><code>tcp[tcpflags] &amp; tcp-syn != 0 </code></pre> <p>Everything ICMP but echo requests/replies:</p> <pre><code>icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply </code></pre>
31,584,207
How to divide a web in 2 columns using bootstrap?
<p>I want to divide a web page made with JSF in two columns, but I'm having problems as it's not displayed as I want. I'll show you what I have.</p> <pre><code>&lt;h:panelGrid id="panelPpal" columns="2" style="width: 100%"&gt; &lt;h:panelGrid style="width: 100%"&gt; &lt;h:form id="projectForm" class="form-horizontal"&gt; &lt;div class="form-group"&gt; &lt;h:outputLabel id="lblProjectName" value="#{rDisenyo['seccion.crea.nombre']}" for="projectName" class="col-md-3 control-label"/&gt; &lt;div class="col-md-6"&gt; &lt;h:inputText id="projectName" label="Nombre" value="#{newProjectBacking.nombreProyecto}" class="form-control"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;h:outputLabel for="grosorCristal" value="#{rDisenyo['dialog.avanzadas.grosorCristal']}" class="col-md-3 control-label"/&gt; &lt;div class="col-md-6"&gt; &lt;h:selectOneMenu id="grosorCristal" class="form-control" label="Grosor del Cristal" value="#{newProjectBacking.grosorCristal}" required="true" &gt; &lt;f:selectItem itemLabel="----------" itemValue="0"/&gt; &lt;f:selectItem itemLabel="8 #{rDisenyo['grosor.cristal.milimetro']}" itemValue="8"/&gt; &lt;f:selectItem itemLabel="10 #{rDisenyo['grosor.cristal.milimetro']}" itemValue="10"/&gt; &lt;f:selectItem itemLabel="12 #{rDisenyo['grosor.cristal.milimetro']}" itemValue="12"/&gt; &lt;/h:selectOneMenu&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;h:outputLabel for="ralMenu" id="ralLbl" value="#{rDisenyo['proyecto.opcionesprevias.ral']}" class="col-md-3 control-label"/&gt; &lt;div class="col-md-6"&gt; &lt;h:selectOneMenu id="ralMenu" class="form-control" value="#{newProjectBacking.ral}" &gt; &lt;f:selectItem itemLabel="" itemValue="0"/&gt; &lt;f:selectItem itemLabel="#{rDisenyo['proyecto.opcionesprevias.ral.blanco']}" itemValue="1"/&gt; &lt;f:selectItem itemLabel="#{rDisenyo['proyecto.opcionesprevias.ral.crudo']}" itemValue="2"/&gt; &lt;f:selectItem itemLabel="#{rDisenyo['proyecto.opcionesprevias.ral.anodizado']}" itemValue="3"/&gt; &lt;/h:selectOneMenu&gt; &lt;/div&gt; &lt;/div&gt; &lt;/h:form&gt; &lt;/h:panelGrid&gt; &lt;h:panelGrid style="width: 100%"&gt; &lt;div class="col-md-8"&gt; &lt;div class="panel panel-primary"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;#{rDisenyo['instrucciones.title']}&lt;/h3&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="subtitulo-instruciones"&gt; #{rDisenyo['instrucciones.angulos.grados']} &lt;/div&gt; #{rDisenyo['instrucciones.angulos.linea1']}&lt;br/&gt; #{rDisenyo['instrucciones.angulos.linea2']}&lt;br/&gt; &lt;div class="subtitulo-instruciones"&gt; #{rDisenyo['instrucciones.longitud.title']} &lt;/div&gt; #{rDisenyo['instrucciones.longitud.linea1']}&lt;br/&gt; &lt;div class="subtitulo-instruciones"&gt; #{rDisenyo['instrucciones.altura.title']} &lt;/div&gt; #{rDisenyo['instrucciones.altura.linea1']}&lt;br/&gt; &lt;div class="subtitulo-instruciones"&gt; #{rDisenyo['instrucciones.recogenizq.title']} &lt;/div&gt; #{rDisenyo['instrucciones.recogenizq.linea1']}&lt;br/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-8"&gt; Eliga el tipo de proyecto: &lt;h:selectOneRadio id="tipoProyectoRadioButton" value="#{newProjectBacking.tipoProyecto}"&gt; &lt;div class="radio"&gt; &lt;f:selectItem itemValue="1" itemLabel="Proyecto A" /&gt; &lt;/div&gt; &lt;div class="radio"&gt; &lt;f:selectItem itemValue="2" itemLabel="Proyecto B" /&gt; &lt;/div&gt; &lt;div class="radio"&gt; &lt;f:selectItem itemValue="3" itemLabel="Proyecto C" /&gt; &lt;/div&gt; &lt;/h:selectOneRadio&gt; &lt;/div&gt; &lt;/h:panelGrid&gt; &lt;/h:panelGrid&gt; </code></pre> <p>As you can see, there are two parts in my app: the left one is a form and the right one has instructions and a different form (I know that it isn't yet inside a h:form). I want the right panel to start in the center of the window, but I don't know how to do it. Thank you!</p> <p><a href="https://i.stack.imgur.com/lqRVi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lqRVi.png" alt="enter image description here"></a></p>
31,591,260
2
0
null
2015-07-23 10:05:52.443 UTC
3
2017-04-05 08:11:19.113 UTC
null
null
null
null
4,104,764
null
1
12
html|css|twitter-bootstrap|twitter-bootstrap-3
72,700
<p>I've found a solution here: <a href="https://stackoverflow.com/questions/14961932/how-to-divide-a-twitter-bootstrap-modal-into-2-parts">How to divide a Twitter bootstrap modal into 2 parts</a></p> <pre><code>&lt;div class="modal-body row"&gt; &lt;div class="col-md-6"&gt; &lt;!-- Your first column here --&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;!-- Your second column here --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
18,600,761
creating proxy using wsdl programmatically and wsdl parsing
<p>I am working on XML web services. My client web service "Client" has the url of the wsdl of server web service "Service" at run time. In order for the "Client" to use "Service" i need to do the following thing "programmatically":</p> <p>1) Get the wsdl file on the fly from "Service" or from a location on the disk. 2) Create a proxy programmatically i.e not using wsdl.exe or Add web reference. 3)Invoke methods on the created proxy.</p> <p>Is it possible to do it? If some one has done it would be greatful to take any suggestions how to accomplish.</p>
18,600,928
1
4
null
2013-09-03 20:17:16.087 UTC
10
2021-11-23 15:27:53.937 UTC
null
null
null
null
633,224
null
1
10
c#|web-services|wsdl
7,473
<p>If you want the proxy to be created at runtime checkout this post</p> <p><a href="https://netmatze.wordpress.com/2012/05/14/building-a-webservice-proxy-at-runtime/" rel="nofollow noreferrer">https://netmatze.wordpress.com/2012/05/14/building-a-webservice-proxy-at-runtime/</a></p> <p>Here is the original answer</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.Security.Permissions; using System.Web.Services.Description; namespace ConnectionLib { public class WSProxy { [SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] public static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args) { System.Net.WebClient client = new System.Net.WebClient(); // Connect To the web service System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + &quot;?wsdl&quot;); // Now read the WSDL file describing a service. ServiceDescription description = ServiceDescription.Read(stream); ///// LOAD THE DOM ///////// // Initialize a service description importer. ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = &quot;Soap12&quot;; // Use SOAP 1.2. importer.AddServiceDescription(description, null, null); // Generate a proxy client. importer.Style = ServiceDescriptionImportStyle.Client; // Generate properties to represent primitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; // Initialize a Code-DOM tree into which we will import the service. CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); // Import the service into the Code-DOM tree. This creates proxy code that uses the service. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); if (warning == 0) // If zero then we are good to go { // Generate the proxy code CodeDomProvider provider1 = CodeDomProvider.CreateProvider(&quot;CSharp&quot;); // Compile the assembly proxy with the appropriate references string[] assemblyReferences = new string[5] { &quot;System.dll&quot;, &quot;System.Web.Services.dll&quot;, &quot;System.Web.dll&quot;, &quot;System.Xml.dll&quot;, &quot;System.Data.dll&quot; }; CompilerParameters parms = new CompilerParameters(assemblyReferences); CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); // Check For Errors if (results.Errors.Count &gt; 0) { foreach (CompilerError oops in results.Errors) { System.Diagnostics.Debug.WriteLine(&quot;========Compiler error============&quot;); System.Diagnostics.Debug.WriteLine(oops.ErrorText); } throw new System.Exception(&quot;Compile Error Occured calling webservice. Check Debug ouput window.&quot;); } // Finally, Invoke the web service method object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName); MethodInfo mi = wsvcClass.GetType().GetMethod(methodName); return mi.Invoke(wsvcClass, args); } else { return null; } } } } </code></pre>
23,661,447
What's the default OAuth AccessTokenFormat implementation in OWIN for IIS host?
<p><a href="https://stackoverflow.com/questions/19938947/web-api-2-owin-bearer-token-authentication-accesstokenformat-null">Web API 2 OWIN Bearer token authentication - AccessTokenFormat null?</a></p> <p>The default /Token endpoints works fine and I could get token from there, but I need to use the AccessTokenFormat.Protect method on a ticket to generate accessToken for externalLogin.</p> <p>Basically my implementation is pretty much the same as this one, and I encountered the same problem of the AccessTokenFormat is null. From the <a href="http://msdn.microsoft.com/en-us/library/microsoft.owin.security.oauth.oauthauthorizationserveroptions%28v=vs.113%29.aspx" rel="nofollow noreferrer">documentation</a> it says:</p> <blockquote> <p>The data format used to protect the information contained in the access token. If not provided by the application the default data protection provider depends on the host server. The SystemWeb host on IIS will use ASP.NET machine key data protection, and HttpListener and other self-hosted servers will use DPAPI data protection. If a different access token provider or format is assigned, a compatible instance must be assigned to the OAuthBearerAuthenticationOptions.AccessTokenProvider or OAuthBearerAuthenticationOptions.AccessTokenFormat property of the resource server.</p> </blockquote> <p>It looks to me that if the AccessTokenFormat is not assigned, the host would provide a basic implementation for it. But I don't see it works here. Is there a way I could find the default implementation of the ISecureDataFormatAccessTokenFormat and assign it to the variable manually?</p> <p>Or does anyone have other ideas how to solves this?</p> <p>UPDATE: I get the source code for katana and find the OAuthAuthorizationServerMiddleware class, from the source code I could see the following code:</p> <pre><code>if (Options.AccessTokenFormat == null) { IDataProtector dataProtecter = app.CreateDataProtector( typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1"); Options.AccessTokenFormat = new TicketDataFormat(dataProtecter); } </code></pre> <p>In my Startup.Auth, here is my code:</p> <pre><code> static Startup() { PublicClientId = "self"; UserManagerFactory = () =&gt; new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext())); OAuthOptions = new OAuthAuthorizationServerOptions() { TokenEndpointPath = new PathString("/Token"), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat; OAuthBearerOptions.AccessTokenProvider = OAuthOptions.AccessTokenProvider; OAuthBearerOptions.AuthenticationMode = OAuthOptions.AuthenticationMode; OAuthBearerOptions.AuthenticationType = OAuthOptions.AuthenticationType; OAuthBearerOptions.Description = OAuthOptions.Description; OAuthBearerOptions.Provider = new CustomBearerAuthenticationProvider(); OAuthBearerOptions.SystemClock = OAuthOptions.SystemClock; } public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create); app.UseOAuthAuthorizationServer(OAuthOptions); // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager)) } }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); </code></pre> <p>}</p> <p>I also have the following in WebApiConfig</p> <pre><code>// Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); </code></pre> <p>I'm not sure why <code>app.UseOAuthAuthorizationServer(OAuthOptions);</code> is not setting the accessTokenFormat</p>
23,664,980
1
0
null
2014-05-14 17:37:08.897 UTC
8
2014-05-14 20:57:44.62 UTC
2017-05-23 12:25:42.387 UTC
null
-1
null
1,505,480
null
1
11
c#|oauth|owin|bearer-token
15,897
<p>I'm not sure why it's not setting it correctly, but I pull out the code and assign to it my self. Here's my final working code looks like:</p> <pre><code> public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create); OAuthOptions = new OAuthAuthorizationServerOptions() { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector( typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1")), RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector( typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1")), AccessTokenProvider = new AuthenticationTokenProvider(), RefreshTokenProvider = new AuthenticationTokenProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat; OAuthBearerOptions.AccessTokenProvider = OAuthOptions.AccessTokenProvider; OAuthBearerOptions.AuthenticationMode = OAuthOptions.AuthenticationMode; OAuthBearerOptions.AuthenticationType = OAuthOptions.AuthenticationType; OAuthBearerOptions.Description = OAuthOptions.Description; OAuthBearerOptions.Provider = new CustomBearerAuthenticationProvider(); OAuthBearerOptions.SystemClock = OAuthOptions.SystemClock; app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager)) } }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); } </code></pre>
43,315,349
How to resize frame's from video with aspect ratio
<p>I am using Python 2.7, OpenCV. I have written this code. </p> <pre><code>import cv2 vidcap = cv2.VideoCapture('myvid2.mp4') success,image = vidcap.read() count = 0; print "I am in success" while success: success,image = vidcap.read() resize = cv2.resize(image, (640, 480)) cv2.imwrite("%03d.jpg" % count, resize) if cv2.waitKey(10) == 27: break count += 1 </code></pre> <p>I am working with video and am dividing the video into individual frames, as a .jpg images. I am also at the same time resizing the frames to dimension 640x480. The order of the frames is also being preserved. The only issue with the code is that it does not save the previous image-ratio.</p> <p>For example how it look's like, resize from 1920x1080: <a href="https://i.stack.imgur.com/FeO0E.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FeO0E.jpg" alt="Resized image by pure code"></a></p> <p>There is a problem in ratio, as you can see. 1920x1080 16:9, but 640:480 4:3</p> <p>How I ideally want it to be: <a href="https://i.stack.imgur.com/7TimO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7TimO.png" alt="Resized image in ideal code"></a></p> <p>Thank you for your taking the time for reading the question. I will be very glad if you can help me solve this issue~ Have a good day, my friend.</p>
43,336,428
3
0
null
2017-04-10 05:09:19.56 UTC
2
2020-10-15 18:08:19.003 UTC
2019-11-11 21:17:06.427 UTC
null
6,527,292
null
7,509,001
null
1
7
python|image|opencv|video|resize
46,183
<p>Instead of using hard-coded values 640 and 480, you can divide the original frame height and width by a value and supply that as an argument, like so:</p> <pre class="lang-py prettyprint-override"><code>import cv2 vidcap = cv2.VideoCapture(&quot;/path/to/video&quot;) success, image = vidcap.read() count = 0 while success: height, width, layers = image.shape new_h = height / 2 new_w = width / 2 resize = cv2.resize(image, (new_w, new_h)) cv2.imwrite(&quot;%03d.jpg&quot; % count, resize) success, image = vidcap.read() count += 1 </code></pre>
481,845
WCF Authentication
<p>Is there some sort of "built-in" authentication in WCF? I need to expose a web service to our clients so they can check status of their transactions. </p> <p>My initial thought was they would just use their normal Username and Password passed in as method properties. It would be over SSL, of course, but is this method of authentication not secure? </p> <p>Does WCF have some better way of allowing authentication with the request other than passing through method parameters?</p>
481,857
2
0
null
2009-01-26 23:39:11.973 UTC
11
2009-01-26 23:52:22.18 UTC
null
null
null
EdenMachine
47,167
null
1
13
.net|wcf|security|authentication
7,446
<p>check these pages:</p> <p><a href="http://blogs.msdn.com/pedram/archive/2007/10/05/wcf-authentication-custom-username-and-password-validator.aspx" rel="noreferrer">Pedram Razei's Ramblings</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/bb398990.aspx" rel="noreferrer">Microsoft Howto</a></p>
1,061,922
jQuery should I use multiple ajaxStart/ajaxStop handling
<p>Maybe there is no difference, but is either way better than the other (or perhaps a mysterious 'third' way better than both!)...</p> <hr> <h1>first:</h1> <pre><code>var startTime; $(document).ready(function() { $("#lbl_ajaxInProgress").ajaxStart(function() { // store the current date/time... startTime = new Date(); // update labels $(this).text('Yes'); $("#lbl_ajaxCallTime").text("-"); }); $("#lbl_ajaxInProgress").ajaxStop(function() { // update labels $(this).text('No'); $("#lbl_ajaxCallTime").text(myFunctionThatCalculatesTime(startTime)); }); }); </code></pre> <hr> <h1>second:</h1> <pre><code>var startTime; $(document).ready(function() { $("#lbl_ajaxInProgress").ajaxStart(function() { // update labels $(this).text('Yes'); }); $("#lbl_ajaxInProgress").ajaxStop(function() { // update labels $(this).text('No'); }); $("#lbl_ajaxCallTime").ajaxStart(function() { // store the current date/time... startTime = new Date(); // update labels $(this).text("-"); }); $("#lbl_ajaxCallTime").ajaxStop(function() { // update labels $(this).text(myFunctionThatCalculatesTime(startTime)); }); }); </code></pre>
1,062,007
2
2
null
2009-06-30 05:52:13.807 UTC
16
2017-09-13 12:26:47.607 UTC
2011-11-01 14:09:24.847 UTC
null
248,129
null
51,507
null
1
18
jquery
23,658
<p>An interesting fact is that ajaxStart, etc. are actually just jQuery events. For instance:</p> <pre><code>$("#lbl_ajaxInProgress").ajaxStart(function() { // update labels $(this).text('Yes'); }); </code></pre> <p>is equivalent to:</p> <pre><code>$("#lbl_ajaxInProgress").bind("ajaxStart", function() { // update labels $(this).text('Yes'); }); </code></pre> <p>This means that you can also attach namespaces to ajaxStart/ajaxStop, etc. Which also means that you can do:</p> <pre><code>$("#lbl_ajaxInProgress").unbind("ajaxStart ajaxStop"); </code></pre> <p>You could also do:</p> <pre><code>$("#lbl_ajaxInProgress").bind("ajaxStart.label", function() { // update labels $(this).text('Yes'); }); $("#lbl_ajaxInProgress").bind("ajaxStop.label", function() { // update labels $(this).text('No'); }); </code></pre> <p>And then:</p> <pre><code>$("#lbl_ajaxInProgress").unbind(".label"); </code></pre> <p>Cool, huh?</p>
711,184
ASP.NET MVC example of editing multiple child records
<p>Does anyone know of any examples or tutorials of an MVC view that shows parent/child data all on one form, and allows all the child records to be editable?</p> <p>For example, say I have a table of people and another containing the vehicles they own. One one form, I want to show every vehicle for a given person, and make the data elements editable (i.e. license plate number, car color, etc.) in case there are mistakes. I don't want to jump to a separate edit form for each vehicle.</p> <p>My attempts thus far have gotten me to the point where I can display the data, but I can't get it to post back to the controller. I've tried to narrow down the problem as far as I could <a href="https://stackoverflow.com/questions/709933/child-records-not-posting-on-asp-net-mvc-form">here</a>, but I'm still not getting it, and I think a broader example may be in order. Any ideas?</p>
712,817
2
0
null
2009-04-02 19:12:27.723 UTC
26
2012-10-27 19:00:30.993 UTC
2017-05-23 12:15:20.423 UTC
gfrizzle
-1
gfrizzle
23,935
null
1
23
asp.net-mvc|master-detail
11,404
<p>You can try something like this.</p> <p>Suppose you have this object :</p> <pre><code>public class Vehicle { public int VehicleID { get; set; } public string LicencePlate { get; set; } public string Color { get; set; } } </code></pre> <p>And this is your controller action that you'll use to edit vehicle details (where you'll post the form) :</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult EditVehicles(int Owner, Vehicle[] vehicles) { //manipulate the data, then return back to the list return RedirectToAction("YourAction"); } </code></pre> <p>Then you should set your form this way : </p> <pre><code>&lt;!--have a form for each person, listing their vehicles--&gt; &lt;form action="/EditVehicles" method="post"&gt; &lt;input type="hidden" name="Owner" value="25" /&gt; &lt;input type="hidden" name="Vehicles[0].VehicleID" value="10" /&gt; &lt;input type="text" name="Vehicles[0].LicencePlate" value="111-111" /&gt; &lt;input type="text" name="Vehicles[0].Color" value="Red" /&gt; &lt;input type="hidden" name="Vehicles[1].VehicleID" value="20" /&gt; &lt;input type="text" name="Vehicles[1].LicencePlate" value="222-222" /&gt; &lt;input type="text" name="Vehicles[1].Color" value="Blue" /&gt; &lt;input type="submit" value="Edit" /&gt; &lt;/form&gt; </code></pre> <p>This will help the DefaultModelBinder to correctly bind the form data to your model in your controller. Thus <code>Response.Write(vehicles[1].Color);</code> on your controller, will print "Blue".</p> <p>This is a very simple example, but I'm sure you get the idea. For more examples about binding forms to arrays, lists, collections, dictionaries, take a look at <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="noreferrer">here</a>.</p>
2,724,871
How to bring up list of available notification sounds on Android
<p>I'm creating notifications in my Android application, and would like to have an option in my preferences to set what sound is used for the notification. I know that in the Settings application you can choose a default notification sound from a list. Where does that list come from, and is there a way for me to display the same list in my application?</p>
2,726,008
5
0
null
2010-04-27 20:32:17.92 UTC
39
2020-07-09 04:49:27.177 UTC
null
null
null
null
1,912
null
1
70
java|android|audio|notifications
36,325
<p>Just copy/pasting some code from one of my apps that does what you are looking for.</p> <p>This is in an onClick handler of a button labeled &quot;set ringtone&quot; or something similar:</p> <pre><code>Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, &quot;Select Tone&quot;); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null); this.startActivityForResult(intent, 5); </code></pre> <p>And this code captures the choice made by the user:</p> <pre><code>@Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (resultCode == Activity.RESULT_OK &amp;&amp; requestCode == 5) { Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (uri != null) { this.chosenRingtone = uri.toString(); } else { this.chosenRingtone = null; } } } </code></pre> <p>Also, I advise my users to install the &quot;Rings Extended&quot; app from the Android Market. Then whenever this dialog is opened on their device, such as from my app or from the phone's settings menu, the user will have the additional choice of picking any of the mp3s stored on their device, not just the built in ringtones.</p>
2,364,581
binary vs text protocols
<p>I am wondering what the differences are between binary and text based protocols. I read that binary protocols are more compacts/faster to process. How does that work out? Since you have to send the same amount of data? No?</p> <p>E.g how would the string "hello" differ in size in binary format?</p>
2,364,614
7
4
null
2010-03-02 16:06:53.67 UTC
10
2020-05-04 10:45:42.023 UTC
2018-12-11 17:04:12.88 UTC
null
165,071
null
284,554
null
1
24
binary|protocols
14,736
<p>If all you are doing is transmitting text, then yes, the difference between the two isn't very significant. But consider trying to transmit things like:</p> <ul> <li>Numbers - do you use a string representation of a number, or the binary? Especially for large numbers, the binary will be more compact.</li> <li>Data Structures - How do you denote the beginning and ending of a field in a text protocol? Sometimes a binary protocol with fixed length fields is more compact.</li> </ul>
2,670,121
Using CMake with GNU Make: How can I see the exact commands?
<p>I use CMake with GNU Make and would like to see all commands exactly (for example how the compiler is executed, all the flags etc.).</p> <p>GNU make has <code>--debug</code>, but it does not seem to be that helpful are there any other options? Does CMake provide additional flags in the generated Makefile for debugging purpose?</p>
2,673,355
8
3
null
2010-04-19 19:19:06.747 UTC
79
2022-08-17 19:11:24.587 UTC
2016-08-23 21:32:48.517 UTC
null
2,799,037
null
44,232
null
1
334
cmake|gnu-make
217,583
<p>When you run make, add <code>VERBOSE=1</code> to see the full command output. For example:</p> <pre><code>cmake . make VERBOSE=1 </code></pre> <p>Or you can add <code>-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON</code> to the cmake command for permanent verbose command output from the generated Makefiles.</p> <pre><code>cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON . make </code></pre> <p>To reduce some possibly less-interesting output you might like to use the following options. The option <code>CMAKE_RULE_MESSAGES=OFF</code> removes lines like <em>[ 33%] Building C object...</em>, while <code>--no-print-directory</code> tells make to not print out the current directory filtering out lines like <code>make[1]: Entering directory</code> and <code>make[1]: Leaving directory</code>.</p> <pre><code>cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON . make --no-print-directory </code></pre>
2,661,818
Javascript get XPath of a node
<p>Is there anyway to return an XPath string of a DOM element in Javascript?</p>
2,661,890
9
0
null
2010-04-18 09:55:13.96 UTC
29
2022-09-20 13:36:14.127 UTC
null
null
null
null
233,427
null
1
72
javascript|dom|xpath
85,088
<p>There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?</p> <p>See <code>getPathTo()</code> in <a href="https://stackoverflow.com/questions/2631820/im-storing-click-coordinates-in-my-db-and-then-reloading-them-later-and-showing/2631931#2631931">this answer</a> for one possible approach.</p>
2,346,920
SQL SELECT speed int vs varchar
<p>I'm in the process of creating a table and it made me wonder.</p> <p>If I store, say cars that has a make (fx BMW, Audi ect.), will it make any difference on the query speed if I store the make as an int or varchar.</p> <p>So is</p> <pre><code>SELECT * FROM table WHERE make = 5 AND ...; </code></pre> <p>Faster/slower than</p> <pre><code>SELECT * FROM table WHERE make = 'audi' AND ...; </code></pre> <p>or will the speed be more or less the same?</p>
2,346,973
9
0
null
2010-02-27 10:02:53.54 UTC
27
2017-05-29 07:56:11.81 UTC
null
null
null
null
127,549
null
1
124
sql|performance|postgresql|select
102,814
<p>Int comparisons are faster than varchar comparisons, for the simple fact that ints take up much less space than varchars.</p> <p>This holds true both for unindexed and indexed access. The fastest way to go is an indexed int column.</p> <hr> <p>As I see you've tagged the question postgreql, you might be interested in the space usage of different date types:</p> <ul> <li><code>int</code> fields occupy <a href="http://www.postgresql.org/docs/7.4/interactive/datatype.html#DATATYPE-NUMERIC" rel="noreferrer">between 2 and 8 bytes</a>, with 4 being usually more than enough ( -2147483648 to +2147483647 )</li> <li>character types occupy <a href="http://www.postgresql.org/docs/7.4/interactive/datatype-character.html" rel="noreferrer">4 bytes plus the actual strings</a>.</li> </ul>
2,447,696
Overloading assignment operator in C++
<p>As I've understand, when overloading operator=, the return value should should be a non-const reference.</p> <pre><code> A& A::operator=( const A& ) { // check for self-assignment, do assignment return *this; } </code></pre> <p>It is non-const to allow non-const member functions to be called in cases like:</p> <pre><code> ( a = b ).f(); </code></pre> <p>But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?</p> <p>It's assumed that copy constructor is implemented correctly.</p>
2,447,716
10
2
null
2010-03-15 14:08:18.793 UTC
9
2016-04-27 20:53:31.527 UTC
2010-03-15 14:26:32.923 UTC
null
223,465
null
223,465
null
1
18
c++|operator-overloading|assignment-operator
9,211
<p>Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?</p> <pre><code>a = b; // huh, why does this create an unnecessary copy? </code></pre> <p>In addition, it would be surprising to users of your class, since the built-in assignment operator doesn't copy likewise</p> <pre><code>int &amp;a = (some_int = 0); // works </code></pre>
2,819,535
Unable to free const pointers in C
<p>How can I free a <code>const char*</code>? I allocated new memory using <code>malloc</code>, and when I'm trying to free it I always receive the error "incompatible pointer type"</p> <p>The code that causes this is something like:</p> <pre><code>char* name="Arnold"; const char* str=(const char*)malloc(strlen(name)+1); free(str); // error here </code></pre>
2,819,594
12
9
null
2010-05-12 14:08:13.433 UTC
17
2018-08-24 05:20:09.453 UTC
2015-11-19 22:37:06.273 UTC
null
1,486,275
null
326,585
null
1
82
c|constants|free
59,955
<p>Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer; <code>free</code> takes a <code>void*</code>, not a <code>const void*</code>:</p> <pre><code>free((char*)str); </code></pre>
10,349,337
Creating tables in sqlite database on android
<pre> @Override public void onCreate(SQLiteDatabase db) { try{ db.execSQL("create table " + NotificationManager.getUserStatic(context) + "log ("+ KEY_TIME +" INTEGER primary key, "+ KEY_TEXT +" TEXT not null);"); } catch (SQLException e) { e.printStackTrace(); } } /** * onOpen method called when app is opening. */ @Override public void onOpen(SQLiteDatabase db) { try{ System.out.println("tophere"); db.execSQL("create table if not exists "+DATABASE_NAME+"." + NotificationManager.getUserStatic(context) + "log ("+ KEY_TIME +" INTEGER primary key, "+ KEY_TEXT +" TEXT not null);"); System.out.println("downhere"); } catch (SQLException e){ e.printStackTrace(); } } </pre> <p>We have this code for creating a database for an app. problem is, as far as we can tell, it doesn't create the tables, so when we try to insert into the tables and read from them, it crashes. we have tried everything, the System.out.println's are there to see where it fails. we get the tophere out, but it never gets to the downhere part in the log, so we are guessing something is causing it to fail there. we have checked with DDMS that the database is in the correct folder, so the database should be there, but for some reason it cant find it(line 2 and 3 in the log). </p> <p>Any thoughts?</p> <p>this is the error log:</p> <pre> 04-27 10:45:46.768: I/System.out(6441): tophere 04-27 10:45:46.772: I/SqliteDatabaseCpp(6441): sqlite returned: error code = 1, msg = unknown database NOPO, db=/data/data/dmri.nopo/databases/NOPO 04-27 10:45:46.772: W/System.err(6441): android.database.sqlite.SQLiteException: unknown database NOPO: , while compiling: create table if not exists NOPO.log (time INTEGER primary key, text TEXT not null); 04-27 10:45:46.792: W/System.err(6441): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method) 04-27 10:45:46.792: W/System.err(6441): at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:68) 04-27 10:45:46.811: W/System.err(6441): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:134) 04-27 10:45:46.811: W/System.err(6441): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361) 04-27 10:45:46.811: W/System.err(6441): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:260) 04-27 10:45:46.811: W/System.err(6441): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:84) 04-27 10:45:46.811: W/System.err(6441): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1899) 04-27 10:45:46.823: W/System.err(6441): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1839) 04-27 10:45:46.823: W/System.err(6441): at dmri.nopo.DBAdapter$DatabaseHelper.onOpen(DBAdapter.java:67) 04-27 10:45:46.823: W/System.err(6441): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:180) 04-27 10:45:46.902: W/System.err(6441): at dmri.nopo.DBAdapter.open(DBAdapter.java:86) 04-27 10:45:46.912: W/System.err(6441): at dmri.nopo.LogManager.readLogFile(LogManager.java:32) 04-27 10:45:46.912: W/System.err(6441): at dmri.nopo.LogActivity.onCreate(LogActivity.java:25) 04-27 10:45:46.921: W/System.err(6441): at android.app.Activity.performCreate(Activity.java:4465) 04-27 10:45:46.921: W/System.err(6441): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 04-27 10:45:46.931: W/System.err(6441): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 04-27 10:45:46.931: W/System.err(6441): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 04-27 10:45:46.941: W/System.err(6441): at android.app.ActivityThread.access$600(ActivityThread.java:123) 04-27 10:45:46.941: W/System.err(6441): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 04-27 10:45:46.953: W/System.err(6441): at android.os.Handler.dispatchMessage(Handler.java:99) 04-27 10:45:46.953: W/System.err(6441): at android.os.Looper.loop(Looper.java:137) 04-27 10:45:46.972: W/System.err(6441): at android.app.ActivityThread.main(ActivityThread.java:4424) 04-27 10:45:46.972: W/System.err(6441): at java.lang.reflect.Method.invokeNative(Native Method) 04-27 10:45:46.972: W/System.err(6441): at java.lang.reflect.Method.invoke(Method.java:511) 04-27 10:45:46.982: W/System.err(6441): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-27 10:45:46.982: W/System.err(6441): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-27 10:45:46.992: W/System.err(6441): at dalvik.system.NativeStart.main(Native Method) 04-27 10:45:47.002: I/SqliteDatabaseCpp(6441): sqlite returned: error code = 1, msg = no such table: log, db=/data/data/dmri.nopo/databases/NOPO 04-27 10:45:47.012: D/AndroidRuntime(6441): Shutting down VM 04-27 10:45:47.012: W/dalvikvm(6441): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 04-27 10:45:47.181: E/AndroidRuntime(6441): FATAL EXCEPTION: main 04-27 10:45:47.181: E/AndroidRuntime(6441): java.lang.RuntimeException: Unable to start activity ComponentInfo{dmri.nopo/dmri.nopo.LogActivity}: android.database.sqlite.SQLiteException: no such table: log: , while compiling: SELECT time, text FROM log 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread.access$600(ActivityThread.java:123) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.os.Handler.dispatchMessage(Handler.java:99) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.os.Looper.loop(Looper.java:137) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread.main(ActivityThread.java:4424) 04-27 10:45:47.181: E/AndroidRuntime(6441): at java.lang.reflect.Method.invokeNative(Native Method) 04-27 10:45:47.181: E/AndroidRuntime(6441): at java.lang.reflect.Method.invoke(Method.java:511) 04-27 10:45:47.181: E/AndroidRuntime(6441): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-27 10:45:47.181: E/AndroidRuntime(6441): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-27 10:45:47.181: E/AndroidRuntime(6441): at dalvik.system.NativeStart.main(Native Method) 04-27 10:45:47.181: E/AndroidRuntime(6441): Caused by: android.database.sqlite.SQLiteException: no such table: log: , while compiling: SELECT time, text FROM log 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:68) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:127) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:94) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:53) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1449) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1405) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1485) 04-27 10:45:47.181: E/AndroidRuntime(6441): at dmri.nopo.DBAdapter.getAllSMS(DBAdapter.java:116) 04-27 10:45:47.181: E/AndroidRuntime(6441): at dmri.nopo.LogManager.readLogFile(LogManager.java:34) 04-27 10:45:47.181: E/AndroidRuntime(6441): at dmri.nopo.LogActivity.onCreate(LogActivity.java:25) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.Activity.performCreate(Activity.java:4465) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 04-27 10:45:47.181: E/AndroidRuntime(6441): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 04-27 10:45:47.181: E/AndroidRuntime(6441): ... 11 more </pre>
10,349,688
5
0
null
2012-04-27 10:55:04.987 UTC
3
2020-12-15 08:45:48.317 UTC
null
null
null
null
1,360,921
null
1
8
android|sqlite|android-logcat
82,888
<p>First of all I would recommend using android.util.Log for logging exceptions in Android.</p> <p>Second - I suspect you have tables with wrong names created. Your error says query can't find "log", but I see you make some concatenation in "CREATE" statement. That may be the reason.</p> <p>You can check what is actually created for you. By viewing the sqlite base created.</p> <p>You can try:</p> <ol> <li><code>adb shell</code></li> <li><code>cd /data/data/&lt;your.package.name&gt;/databases</code></li> <li><code>sqlite3 &lt;yourdbname&gt;</code></li> <li><code>.tables</code></li> </ol>
10,678,441
Flipping the boolean values in a list Python
<p>I have a boolean list in Python</p> <pre><code>mylist = [True , True, False,...] </code></pre> <p>which I want to change to the logical opposite <code>[False, False, True , ...]</code> Is there an inbuilt way to do this in Python (something like a call <code>not(mylist)</code> ) without a hand-written loop to reverse the elements? </p>
10,678,448
8
0
null
2012-05-21 00:42:44.5 UTC
15
2020-09-18 20:12:27.007 UTC
null
null
null
null
505,306
null
1
84
python
113,411
<p>It's easy with list comprehension:</p> <pre><code>mylist = [True , True, False] [not elem for elem in mylist] </code></pre> <p>yields</p> <pre><code>[False, False, True] </code></pre>
6,265,731
Do Java sockets support full duplex?
<p>Is it possible to have one thread write to the <code>OutputStream</code> of a Java <code>Socket</code>, while another reads from the socket's <code>InputStream</code>, without the threads having to synchronize on the socket?</p>
6,265,813
2
4
null
2011-06-07 13:14:01.69 UTC
9
2011-06-07 22:22:22.8 UTC
2011-06-07 13:46:51.55 UTC
null
318,174
null
67,063
null
1
56
java|multithreading|sockets
14,879
<p>Sure. The exact situation you're describing shouldn't be a problem (reading and writing simultaneously).</p> <p>Generally, the reading thread will block if there's nothing to read, and might timeout on the read operation if you've got a timeout specified.</p> <p>Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.</p>
18,445,551
Uploading a file with AngularJS and bluimp on success callback of another form
<p>I have followed the <a href="http://code-like-a-poem.blogspot.co.il/2013/05/angularjs-tutorial-4-file-upload-using.html" rel="noreferrer">following</a> tutorial in order to integrate the notorious bluimp jQuery file uploader in my AngularJS project.</p> <p>After some research I found that in the options array, witihn the jquery.fileuploader.js file, there is an option called autoUpload, which when set to true upload the file automatically. I tried to disable it(false, undefined), but quickly I learned out that this causes the upload not to function at all, not even on the form submit.</p> <p>I need to trigger the upload manually, say within another callback, or by a click event. can that be done?.</p> <p>code:</p> <pre><code>app.directive("fileupload", function() { return { restrict: "A", scope: { done: "&amp;", progress: "&amp;", fail: "&amp;", uploadurl: "=", customdata: "&amp;" }, link: function(scope, elem, attrs) { var uploadOptions; uploadOptions = { url: scope.uploadurl, dataType: "json" }; if (scope.done) { uploadOptions.done = function(e, data) { return scope.$apply(function() { return scope.done({ e: e, data: data }); }); }; } if (scope.fail) { uploadOptions.fail = function(e, data) { return scope.$apply(function() { return scope.fail({ e: e, data: data }); }); }; } if (scope.progress) { uploadOptions.progress = function(e, data) { return scope.$apply(function() { return scope.progress({ e: e, data: data }); }); }; } return elem.fileupload(uploadOptions).bind("fileuploadsubmit", function(e, data) { return data.formData = { JSON.stringify(scope.customdata()) }; }); } }; }); app.service('uploadService', function(authService) { var initializeFn, processFn; initializeFn = function(e, data, process) { var upload; return upload = { message: '', uploadurl: authService.getBaseUrl() + '/applications/', status: false }; }; processFn = function(e, data, process) { var file, upload; upload = {}; upload.successData = []; upload.status = true; upload.error = false; if (process === 'done') { upload.message = data.result.result; console.log(data); file = data.result.resume; upload.successData = { // name: file.name, // fullUrl: file.url, // thumbUrl: file.thumbnail_url }; } else if (process === 'progress') { upload.message = 'Uploading....!!!'; } else { upload.error = true; upload.message = 'Please try again'; console.log(e, data); } return upload; }; return { process: processFn, initialize: initializeFn }; }); app.controller('applyCtrl', function($scope, $routeParams, uploadService){ $scope.model.formData = {}; $scope.model.formData.job = $routeParams.jobId; $scope.uploadLayer = function(e, data, process) { return $scope.uploadReturn = uploadService.process(e, data, process); }; $scope.customData = function() { return $scope.model.formData; }; return $scope.uploadReturn = uploadService.initialize(); }); </code></pre> <p>view:</p> <pre><code> &lt;form class="applyForm" ng-submit="uploadLayer(e, data, 'progress')"&gt; &lt;fieldset&gt; &lt;div class="formLine"&gt; &lt;div class="wideFieldContainer"&gt; &lt;input id="testUpload" type="file" fileupload customdata="customData()" name="resume" uploadurl="uploadReturn.uploadurl" done="uploadLayer(e, data, 'done')" fail="uploadLayer(e, data, 'fail')" progress="uploadLayer(e, data, 'progress')" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>scripts loading order:</p> <pre><code>... &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="lib/angular/angular.js"&gt;&lt;/script&gt; &lt;script src="lib/angular/angular-resource.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;script src="js/services.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/filters.js"&gt;&lt;/script&gt; &lt;script src="js/directives.js"&gt;&lt;/script&gt; &lt;script src="lib/bluimp/js/vendor/jquery.ui.widget.js"&gt;&lt;/script&gt; &lt;script src="lib/bluimp/js/jquery.piframe-transport.js"&gt;&lt;/script&gt; &lt;script src="lib/bluimp/js/jquery.fileupload.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
18,580,266
1
0
null
2013-08-26 13:38:22.743 UTC
10
2013-09-09 07:55:45.163 UTC
null
null
null
null
1,922,258
null
1
5
angularjs|angularjs-directive|angularjs-service|ajax-upload
21,096
<p>Blueimp has an AngularJS version of jQuery File Upload available.</p> <p>It includes a <code>fileUpload</code> directive and a <code>FileUploadController</code> with a <code>submit()</code> method that you can call manually.</p> <p>You can see a working version at <a href="http://blueimp.github.io/jQuery-File-Upload/angularjs.html">http://blueimp.github.io/jQuery-File-Upload/angularjs.html</a>.</p> <p>One thing you should pay attention to: make sure you load all .js files from the example in the correct order to avoid problems (cf. source of the example page).</p> <p>Hope that helps!</p> <hr> <p>UPDATE AFTER YOUR COMMENT:</p> <p>When using the AngularJS version of jQuery File Upload, you create a form tag with the <code>file-upload</code> attribute like this:</p> <pre><code>&lt;!-- Create a file upload form with options passed in from your scope --&gt; &lt;form data-file-upload="options" data-ng-controller="YourController"&gt; &lt;!-- This button will trigger a file selection dialog --&gt; &lt;span class="btn btn-success fileinput-button" ng-class="{disabled: disabled}"&gt; &lt;span&gt;Add files...&lt;/span&gt; &lt;input type="file" name="files[]" multiple="" ng-disabled="disabled"&gt; &lt;/span&gt; &lt;!-- This button will start the upload --&gt; &lt;button type="button" class="btn btn-primary start" data-ng-click="submit()"&gt; &lt;span&gt;Start upload&lt;/span&gt; &lt;/button&gt; &lt;form&gt; </code></pre> <p>Then in your controller you can assign the options for the jQuery File Upload like this:</p> <pre><code>angular.module('yourModule') .controller('YourController', [$scope, function($scope){ // Options you want to pass to jQuery File Upload e.g.: $scope.options = { maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }; }]); </code></pre> <p>You can assign the <code>submit()</code> handler to any <code>ng-click</code> attribute as long as it is inside the form (and thus can access the method).</p> <p>Let me know if you need further help...</p> <hr> <p>EXTRA SAMPLE CODE FOR SUCCESS CALLBACK:</p> <p>If you need to run a callback function after <strong>all</strong> uploads have been completed, you can listen to the <code>fileuploadstop</code> event that is broadcasted by Blueimp:</p> <pre><code>// Listen to fileuploadstop event $scope.$on('fileuploadstop', function(){ // Your code here console.log('All uploads have finished'); }); </code></pre> <p>Hope that helps!</p>
33,503,993
Read in all csv files from a directory using Python
<p>I hope this is not trivial but I am wondering the following:</p> <p>If I have a specific folder with <em>n</em> <code>csv</code> files, how could I iteratively read all of them, one at a time, and perform some calculations on their values?</p> <p>For a single file, for example, I do something like this and perform some calculations on the <code>x</code> array:</p> <pre><code>import csv import os directoryPath=raw_input('Directory path for native csv file: ') csvfile = numpy.genfromtxt(directoryPath, delimiter=",") x=csvfile[:,2] #Creates the array that will undergo a set of calculations </code></pre> <p>I know that I can check how many <code>csv</code> files there are in a given folder (check <a href="https://stackoverflow.com/questions/9234560/find-all-csv-files-in-a-directory-using-python">here</a>):</p> <pre><code>import glob for files in glob.glob("*.csv"): print files </code></pre> <p>But I failed to figure out how to possibly nest the <code>numpy.genfromtxt()</code> function in a for loop, so that I read in all the csv files of a directory that it is up to me to specify. </p> <p><strong>EDIT</strong></p> <p>The folder I have only has <code>jpg</code> and <code>csv</code> files. The latter are named <code>eventX.csv</code>, where <em>X</em> ranges from 1 to 50. The <code>for</code> loop I am referring to should therefore consider the file names the way they are.</p>
33,504,072
8
0
null
2015-11-03 16:17:04.547 UTC
15
2022-05-24 19:37:45.31 UTC
2017-05-23 10:30:58.84 UTC
null
-1
null
5,110,870
null
1
27
python|csv|for-loop|numpy|genfromtxt
126,678
<p>That's how I'd do it:</p> <pre><code>import os directory = os.path.join("c:\\","path") for root,dirs,files in os.walk(directory): for file in files: if file.endswith(".csv"): f=open(file, 'r') # perform calculation f.close() </code></pre>
32,578,224
Cloning a branch : Remote branch branch-99 not found in upstream origin
<p>How can I clone a branch from git with a specific Branch name?</p> <p>I have a branch named <code>branch-99</code> and my user name is <code>Istiak</code>.</p> <p>I try to clone my branch like:</p> <pre><code>git clone -b branch-99 [email protected]/admin.git </code></pre> <p>I am receiving this error.</p> <blockquote> <p>fatal: Remote branch branch-99 not found in upstream origin</p> </blockquote> <p>What I am doing wrong here?</p>
32,578,409
2
1
null
2015-09-15 05:18:22.127 UTC
2
2022-02-01 18:00:28.487 UTC
2021-08-04 09:23:17.357 UTC
null
4,843,744
null
4,843,744
null
1
25
git|github|git-clone
110,604
<p><code>branch-99</code> does not exist on the remote repository. You probably misspelled the branch name or the repository.</p> <p>To check which branches exist, use <a href="https://git-scm.com/docs/git-ls-remote.html" rel="nofollow noreferrer"><code>ls-remote</code></a>. You can use it on the remote...</p> <pre><code>git ls-remote --heads origin </code></pre> <p>Or if you haven't already cloned the repository, on a URL.</p> <pre><code>git ls-remote --heads [email protected]:Christoffer/admin.git </code></pre> <p>You'll get the commit IDs and branch names, but they'll be full references like <code>refs/heads/&lt;branch&gt;</code>.</p> <pre><code>8c2ac78ceba9c5265daeab1519b84664127c0e7d refs/heads/fix/that 6bc88ec7c9c7ce680f8d69ced2e09f18c1747393 refs/heads/master 83f062226716bb9cebf10779834db1ace5578c50 refs/heads/branch-42 </code></pre> <p>See <a href="https://git-scm.com/docs/gitrevisions#_specifying_revisions" rel="nofollow noreferrer"><code>gitrevisions</code></a> for more.</p> <hr /> <p>To be clear, <code>git clone -b branch-99 [email protected]:Christoffer/admin.git</code> clones the entire repository. It just checks out <code>branch-99</code> rather than <code>master</code>. It's the same as...</p> <pre><code>git clone [email protected]:Christoffer/admin.git git checkout branch-99 </code></pre> <p>That bit of syntax sugar isn't worth the bother. I guess it might save you a tiny bit of time not having to checkout master.</p> <p>If you want to clone just the history of one branch to save some network and disk space use <code>--single-branch</code>.</p> <pre><code>git clone --single-branch -b branch-99 [email protected]:Christoffer/admin.git </code></pre> <p>However it's usually not worth the trouble. Git is very disk and network efficient. And the whole history of that branch has to be cloned which usually includes most of the repository anyway.</p>
34,382,356
Passing arguments to process.crawl in Scrapy python
<p>I would like to get the same result as this command line : scrapy crawl linkedin_anonymous -a first=James -a last=Bond -o output.json</p> <p>My script is as follows :</p> <pre><code>import scrapy from linkedin_anonymous_spider import LinkedInAnonymousSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings spider = LinkedInAnonymousSpider(None, "James", "Bond") process = CrawlerProcess(get_project_settings()) process.crawl(spider) ## &lt;-------------- (1) process.start() </code></pre> <p>I found out that process.crawl() in (1) is creating another LinkedInAnonymousSpider where first and last are None (printed in (2)), if so, then there is no point of creating the object spider and how is it possible to pass the arguments first and last to process.crawl()?</p> <p>linkedin_anonymous :</p> <pre><code>from logging import INFO import scrapy class LinkedInAnonymousSpider(scrapy.Spider): name = "linkedin_anonymous" allowed_domains = ["linkedin.com"] start_urls = [] base_url = "https://www.linkedin.com/pub/dir/?first=%s&amp;last=%s&amp;search=Search" def __init__(self, input = None, first= None, last=None): self.input = input # source file name self.first = first self.last = last def start_requests(self): print self.first ## &lt;------------- (2) if self.first and self.last: # taking input from command line parameters url = self.base_url % (self.first, self.last) yield self.make_requests_from_url(url) def parse(self, response): . . . </code></pre>
34,383,962
3
0
null
2015-12-20 15:06:10.207 UTC
9
2020-11-10 08:31:16.65 UTC
2015-12-20 15:33:42.42 UTC
null
4,393,898
null
4,393,898
null
1
35
python|web-crawler|scrapy|scrapy-spider|google-crawlers
13,807
<p>pass the spider arguments on the <code>process.crawl</code> method:</p> <pre><code>process.crawl(spider, input='inputargument', first='James', last='Bond') </code></pre>
18,024,406
error: return-statement with no value, in function returning ‘void*’ [-fpermissive]
<p>When trying to "make" a file I keep getting the following error:</p> <pre><code> error: return-statement with no value, in function returning ‘void*’ [-fpermissive] </code></pre> <p>I can show the code to people who would like to see, but I would rather send it over a message. </p> <p>I've searched some and some people suggest it's a compiling error that is common in "newer" compilers... and yes, I updated mine yesterday. Horrid idea.</p>
18,024,461
1
6
null
2013-08-02 19:07:00.947 UTC
null
2013-08-02 19:09:49.337 UTC
null
null
null
null
2,529,727
null
1
-3
c++|compilation
44,665
<p>The error means that in your function:</p> <pre><code>void* foo(...); </code></pre> <p>You have a statement:</p> <pre><code>return; </code></pre> <p>But the compiler expects a value to be provided:</p> <pre><code>return myVoidPtr; </code></pre>
32,635,785
List directory contents of an S3 bucket using Python and Boto3?
<p>I am trying to list all directories within an S3 bucket using Python and Boto3.</p> <p>I am using the following code:</p> <pre><code>s3 = session.resource('s3') # I already have a boto3 Session object bucket_names = [ 'this/bucket/', 'that/bucket/' ] for name in bucket_names: bucket = s3.Bucket(name) for obj in bucket.objects.all(): # this raises an exception # handle obj </code></pre> <p>When I run this I get the following exception stack trace:</p> <pre><code>File "botolist.py", line 67, in &lt;module&gt; for obj in bucket.objects.all(): File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 82, in __iter__ for page in self.pages(): File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 165, in pages for page in pages: File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 83, in __iter__ response = self._make_request(current_kwargs) File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 155, in _make_request return self._method(**current_kwargs) File "/Library/Python/2.7/site-packages/botocore/client.py", line 270, in _api_call return self._make_api_call(operation_name, kwargs) File "/Library/Python/2.7/site-packages/botocore/client.py", line 335, in _make_api_call raise ClientError(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (NoSuchKey) when calling the ListObjects operation: The specified key does not exist. </code></pre> <p>What is the correct way to list directories inside a bucket?</p>
56,990,512
6
0
null
2015-09-17 16:49:07.92 UTC
7
2021-05-11 21:54:14.41 UTC
2019-10-04 00:06:41.297 UTC
null
1,127,428
null
4,755,187
null
1
18
python|amazon-web-services|amazon-s3|boto3
47,868
<p>All these other responses leave things to be desired. Using</p> <pre><code>client.list_objects() </code></pre> <p>Limits you to 1k results max. The rest of the answers are either wrong or too complex.</p> <p>Dealing with the continuation token yourself is a terrible idea. Just use paginator, which deals with that logic for you</p> <p>The solution you want is:</p> <pre><code>[e['Key'] for p in client.get_paginator(&quot;list_objects_v2&quot;)\ .paginate(Bucket='my_bucket') for e in p['Contents']] </code></pre>
21,271,935
NSString boundingRectWithSize returning unnecessarily tall height
<p>When using <code>[NSString boundingRectWithSize:options:attributes]</code> the size of the rect that is returned is taller than I would expect for certain strings. The height returned appears to represent the maximum possible height of a string with the given attributes, rather than the height of the string itself. </p> <p>Assuming the same attributes and options, the height returned for the string "<code>cars</code>" is the same height returned for the string "<code>ÉTAS-UNIS</code>" (note the accent on the E). </p> <p>I would have expected <code>boundingRectWithSize</code> to only consider the characters in the given string, which in my opinion would have it return a shorter height for the string "<code>cars</code>". </p> <p>In the attached screenshots, I've filled the rect returned from <code>boundingRectWithSize</code> and outlined in red what I would have assumed the bounding rect should have been. The width of the rect is pretty much as I would expect but the height is considerably taller than I would have expected. Why is that? </p> <p><img src="https://i.stack.imgur.com/c0i5A.png" alt="Bounding Rect Example"></p> <p>Sample code: </p> <pre><code>NSRect boundingRect = NSZeroRect; NSSize constraintSize = NSMakeSize(CGFLOAT_MAX, 0); NSString *lowercaseString = @"cars"; NSString *uppercaseString = @"ÉTAS-UNIS"; NSString *capitalizedString = @"Japan"; NSFont *drawingFont = [NSFont fontWithName:@"Georgia" size:24.0]; NSDictionary *attributes = @{NSFontAttributeName : drawingFont, NSForegroundColorAttributeName : [NSColor blackColor]}; boundingRect = [lowercaseString boundingRectWithSize:constraintSize options:0 attributes:attributes]; NSLog(@"Lowercase rect: %@", NSStringFromRect(boundingRect)); boundingRect = [uppercaseString boundingRectWithSize:constraintSize options:0 attributes:attributes]; NSLog(@"Uppercase rect: %@", NSStringFromRect(boundingRect)); boundingRect = [capitalizedString boundingRectWithSize:constraintSize options:0 attributes:attributes]; NSLog(@"Capitalized rect: %@", NSStringFromRect(boundingRect)); </code></pre> <p>Output: </p> <pre><code>Lowercase rect: {{0, -6}, {43.1953125, 33}} Uppercase rect: {{0, -6}, {128.44921875, 33}} Capitalized rect: {{0, -6}, {64.5, 33}} </code></pre>
21,273,065
4
1
null
2014-01-22 00:31:32.503 UTC
13
2019-04-04 19:33:00.713 UTC
2019-04-04 19:33:00.713 UTC
null
3,151,675
null
48,321
null
1
20
ios|objective-c|macos|cocoa|nsstring
17,082
<p>You might want to use <code>NSStringDrawingUsesDeviceMetrics</code> in the options. From the <a href="http://nathanmock.com/files/com.apple.adc.documentation.AppleiOS6.0.iOSLibrary.docset/Contents/Resources/Documents/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/Reference/Reference.html#//apple_ref/doc/c_ref/NSStringDrawingUsesDeviceMetrics" rel="noreferrer">docs</a>:</p> <blockquote> <p><code>NSStringDrawingUsesDeviceMetrics</code></p> <p>Use the image glyph bounds (instead of the typographic bounds) when computing layout.</p> </blockquote>
35,640,369
React Native - NSNumber cannot be converted to NSString
<p>Below is part of my react component. I have a props named daysUntil coming into this component which contains a number. In this example it is being pass the number 0 which results in the fontWeight function returning 700</p> <pre><code>render: function() { return ( &lt;Text style={this.style()}&gt; {this.props.day} &lt;/Text&gt; ) }, style: function() { return { fontWeight: this.fontWeight() } }, fontWeight: function() { var weight = 7 - this.props.daysUntil; return weight * 100; } </code></pre> <p>I get the following error:</p> <blockquote> <p>JSON value '700' of type NSNumber cannot be converted to NSSTring.</p> </blockquote> <p>I'm assuming this is because font-weight expects the value to be in string format. What's the proper fix for this?</p> <p>Thank you in advance!</p>
35,640,441
5
0
null
2016-02-25 23:16:32.323 UTC
1
2018-09-12 23:56:37.793 UTC
null
null
null
null
348,036
null
1
17
ios|reactjs|nsstring|react-native|nsnumber
39,315
<p>In your fontWeight() function </p> <pre><code>return weight * 100; </code></pre> <p>maybe becomes:</p> <pre><code>var val= weight * 100; return val.toString(); </code></pre>
35,608,861
UnrecognizedPropertyException: Unrecognized field not marked as ignorable at Source: org.apache.catalina.connector.CoyoteInputStream@14ec141
<p>I am making rest web-services my code is:</p> <pre><code>@Path("/add") @POST @Produces(MediaType.APPLICATION_JSON) public Response addMembers(List&lt;GroupMemberMap&gt; groupMemberMaps){ String message = ""; System.out.println("Inside addMembers of class "+this.toString()); try { DBConnection.insertMembers(groupMemberMaps); message = "Member(s) added"; return Response.status(Status.CREATED) .entity(message) .type(MediaType.TEXT_PLAIN) .build(); } catch(SQLException sqle){ System.out.println("addMembers catch sqle"); message = "A problem occured while adding members : "+sqle.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(message) .type(MediaType.TEXT_PLAIN) .build(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Inside addMembers catch "+e.getMessage()); message = "A problem occured while adding members : "+e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(message) .type(MediaType.TEXT_PLAIN) .build(); } } </code></pre> <p>but when i call it with this Json :</p> <pre><code>[ { "userId":"3", "groupId":"4" } ] </code></pre> <p>I'm getting following Exception:</p> <blockquote> <p>javax.servlet.ServletException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "userId" (Class com.tazligen.model.GroupMemberMap), not marked as ignorable at [Source: org.apache.catalina.connector.CoyoteInputStream@14ec141; line: 2, column: 15] (through reference chain: com.tazligen.model.GroupMemberMap["userId"])</p> </blockquote> <p>My GrouMemberMap model class is :</p> <pre><code>package com.tazligen.model; @XmlRootElement public class GroupMemberMap { private String userId; private String groupId; public String getUserid() { return userId; } public void setUserid(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } } </code></pre> <p>I have tried another method just like this :</p> <pre><code>@Path("/membertest") @POST public String test(List&lt;User&gt; members){ return "Test subresource members working"; } </code></pre> <p>with json </p> <pre><code>[{ "userId":"3", "userName":"John"}] </code></pre> <p>but this works alright :/</p> <p>Need Someone help.</p>
35,609,042
4
0
null
2016-02-24 17:21:56.593 UTC
2
2022-04-04 17:09:32.567 UTC
2020-08-04 17:50:19.987 UTC
null
7,232,295
null
5,901,482
null
1
9
java|json|jackson|jackson-databind
38,817
<p>I can make following observations after looking at <code>GroupMemberMap</code> Class:</p> <ol> <li>Constructor is missing.</li> <li>Getter-Setter for the <code>UserId</code> is incorrect.</li> </ol> <p>Also, you can add optional <code>@JsonIgnoreProperties</code> to ignore all other unknown fields.</p> <p>Here is the corrected code snippet:</p> <pre><code>package com.tazligen.model; @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class GroupMemberMap { @JsonProperty("userId") private String userId; @JsonProperty("groupId") private String groupId; /* Add Constructor */ public GroupMemberMap() {} /* Corrected Name */ public String getUserId() { return userId; } /* Corrected Name */ public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } } </code></pre>
25,480,598
How to build dependent project when building a module in maven
<p>How can I build the dependent projects when a child project is getting build by maven. As an example, I have 2 projects call A,B. Project B is depending on project A. I want to build the project A when I am building project B with maven. How should I do it?</p>
25,480,741
1
0
null
2014-08-25 07:05:24.863 UTC
9
2018-11-09 07:13:28.903 UTC
2014-08-25 12:31:52.853 UTC
null
1,747,018
null
3,956,150
null
1
23
maven|build|dependencies
19,121
<p>Take a look at these options that can be passed to mvn:</p> <pre><code>Options: -am,--also-make If project list is specified, also build projects required by the list -amd,--also-make-dependents If project list is specified, also build projects that depend on projects on the list </code></pre> <p>I believe in your case you have to use -amd</p> <p>Edit: In case you need to do it through a pom. You just need to create another module say C, that just lists the sub modules A and B. And when you build C, the maven reactor will automatically build both.</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.test&lt;/groupId&gt; &lt;artifactId&gt;ParentModuleC&lt;/artifactId&gt; &lt;packaging&gt;pm&lt;/packaging&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;name&gt;ParentModuleC&lt;/name&gt; &lt;dependencies&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;/build&gt; &lt;modules&gt; &lt;module&gt;ModuleA&lt;/module&gt; &lt;module&gt;ModuleB&lt;/module&gt; &lt;/modules&gt; &lt;/project&gt; </code></pre> <p>In the ModuleA and B you need to add this:</p> <pre><code>&lt;parent&gt; &lt;groupId&gt;com.test&lt;/groupId&gt; &lt;artifactId&gt;ParentModuleC&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; </code></pre> <p>And your directory structure will look like this:</p> <pre><code>ParentModuleC |-pom.xml |-----------&gt;ModuleA | |-&gt;pom.xml |-----------&gt;ModuleB | |-&gt;pom.xml </code></pre> <p>Have a look at this for a simple example: <a href="http://books.sonatype.com/mvnex-book/reference/multimodule.html" rel="noreferrer">http://books.sonatype.com/mvnex-book/reference/multimodule.html</a></p>
8,485,081
How do you stop a Windows Batch file from exiting early?
<p>I have a windows batch file that looks similar to:</p> <pre><code>C:\DoStuff.cmd move output.bak C:\newfolder\output.bak </code></pre> <p>The problem i have is that DoStuff.cmd executes a java program that once complete exits the batch run back to the command prompt. Line 2 never gets hit.</p> <p>i have tried the following instead to execute the command in a new window:</p> <pre><code>start "My program" /WAIT C:\DoStuff.cmd move output.bak C:\newfolder\output.bak </code></pre> <p>What happens with the above is that the new command window spawns the cmd file runs and exits back to a waiting command prompt and the window never closes, leaving the first command window waiting and the second doing nothing stuck after finishing step one.</p> <p>How do i execute the first command without it having control of the batch run somehow?</p> <p>many thanks in advance</p>
8,486,990
1
0
null
2011-12-13 06:11:36.99 UTC
1
2011-12-13 09:38:32.597 UTC
null
null
null
null
115,749
null
1
28
command-line|batch-file|windows-console
12,517
<p>You can use <a href="http://www.computerhope.com/call.htm" rel="noreferrer">DOS call command</a>:</p> <pre><code>@echo off call C:\DoStuff.cmd echo Exit Code = %ERRORLEVEL% </code></pre> <p>After getting error code you can proceed for example with:</p> <pre><code>if "%ERRORLEVEL%" == "1" exit /B 1 </code></pre>
8,905,832
jQuery scrollRight?
<p>I have the following code that seems to scroll a div on click all the way to the left. I am wondering if:</p> <ol> <li>there is a way to get it to get it to scroll only 200px at a time. </li> <li>I can get it to scroll to the right as well. Tried to look at the jQuery documentations but could not find a scrollToRight function.</li> </ol> <p>Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(".leftArrow").click(function () { $(".innerWrapper").animate({scrollLeft: 250}, 800); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.innerWrapper { float: left; margin-right:-32767px; } .outerWrapper { width: 780px; height: 180px; overflow: hidden; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type='button' class='leftArrow' value='left'&gt; &lt;input type='button' class='rightArrow' value='right'&gt; &lt;div class='outerWrapper'&gt; &lt;div class='innerWrapper'&gt; Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Any help would be greatly appreciated.</p>
8,906,007
4
0
null
2012-01-18 06:00:11.69 UTC
15
2021-12-31 11:08:50.483 UTC
2015-12-18 14:32:21.993 UTC
null
4,551,041
null
527,505
null
1
44
jquery
108,551
<p>scrollLeft IS scrollRight. Sort of. All it does is set the amount of horizontal scroll. If you set it to zero then it will be all the way left. If you set it to something greater than zero then it will move to the right! </p> <p>As far as making it go in increments, you would have to get the current scrollLeft distance and then subtract 200. </p> <pre><code>$(".leftArrow").click(function () { var leftPos = $('.innerWrapper').scrollLeft(); $(".innerWrapper").animate({scrollLeft: leftPos - 200}, 800); }); $(".rightArrow").click(function () { var leftPos = $('.innerWrapper').scrollLeft(); $(".innerWrapper").animate({scrollLeft: leftPos + 200}, 800); }); </code></pre>
8,598,163
split title of a figure in matplotlib
<p>I use matplotlib to create a figure with 4 sub-plots in it.</p> <p>I would like to split one of my title of a subplot, such that each line would be in the centered with respect to subplot.</p> <p>I tried </p> <pre><code>import matplotlib.pylab as plt fig = plt.figure(num=0,figsize=(8.27, 11.69), dpi=300) ax = fig.add_subplot(2, 2, 1) ax.set_title(r'Normalized occupied \\ Neighbors') </code></pre> <p>and what i get is that <code>Neighbors</code> is indent to left side.</p> <p>How could i correct this?</p>
8,599,086
5
0
null
2011-12-22 00:40:43.197 UTC
13
2019-07-31 17:38:21.567 UTC
null
null
null
null
230,270
null
1
49
matplotlib
101,481
<p>I get the correct alignment when I format the string this way:</p> <pre><code>import matplotlib.pylab as plt fig = plt.figure()#num=0,figsize=(8.27, 11.69), dpi=300) ax = fig.add_subplot(2, 2, 1) ax.set_title('Normalized occupied \n Neighbors') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/V3I1a.png" alt="enter image description here"></p>
47,947,659
How to join multiple documents in a Cloud Firestore query?
<p>I have a Cloud Firestore DB with the following structure:</p> <ul> <li>users <ul> <li>[uid] <ul> <li>name: "Test User"</li> </ul></li> </ul></li> <li>posts <ul> <li>[id] <ul> <li>content: "Just some test post."</li> <li>timestamp: (Dec. 22, 2017)</li> <li>uid: [uid]</li> </ul></li> </ul></li> </ul> <p>There is more data present in the actual DB, the above just illustrates the collection/document/field structure.</p> <p>I have a view in my web app where I'm displaying posts and would like to display the name of the user who posted. I'm using the below query to fetch the posts:</p> <pre><code>let loadedPosts = {}; posts = db.collection('posts') .orderBy('timestamp', 'desc') .limit(3); posts.get() .then((docSnaps) =&gt; { const postDocs = docSnaps.docs; for (let i in postDocs) { loadedPosts[postDocs[i].id] = postDocs[i].data(); } }); // Render loadedPosts later </code></pre> <p>What I want to do is query the user object by the uid stored in the post's uid field, and add the user's name field into the corresponding loadedPosts object. If I was only loading one post at a time this would be no problem, just wait for the query to come back with an object and in the <code>.then()</code> function make another query to the user document, and so on.</p> <p>However because I'm getting multiple post documents at once, I'm having a hard time figuring out how to map the correct user to the correct post after calling <code>.get()</code> on each post's <code>user/[uid]</code> document due to the asynchronous way they return.</p> <p>Can anyone think of an elegant solution to this issue?</p>
47,948,390
5
2
null
2017-12-22 21:36:02.67 UTC
14
2021-07-13 03:38:04.173 UTC
null
null
null
null
1,705,378
null
1
21
javascript|firebase|google-cloud-firestore
29,932
<p>I would do 1 user doc call and the needed posts call.</p> <pre><code>let users = {} ; let loadedPosts = {}; db.collection('users').get().then((results) =&gt; { results.forEach((doc) =&gt; { users[doc.id] = doc.data(); }); posts = db.collection('posts').orderBy('timestamp', 'desc').limit(3); posts.get().then((docSnaps) =&gt; { docSnaps.forEach((doc) =&gt; { loadedPosts[doc.id] = doc.data(); loadedPosts[doc.id].userName = users[doc.data().uid].name; }); }); </code></pre>
2,311
File size differences after copying a file to a server vía FTP
<p>I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p> <p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put.</p> <pre><code>from ftplib import FTP ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd" locfile = "g:/test/style.css" ftpfile = "/temp/style.css" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect") f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() </code></pre> <p>Any suggestions?</p>
2,316
3
0
null
2008-08-05 13:40:47.47 UTC
3
2020-07-11 07:06:47.05 UTC
2019-06-04 09:28:15.763 UTC
null
6,556,397
PabloG
394
null
1
46
php|python|ftp|webserver|ftplib
5,154
<p>Do you need to open the locfile in binary using <code>rb</code>?</p> <pre><code>f = open (locfile, "rb") </code></pre>
820,219
How to find slowest queries
<p>Using Sql Server 2005 Profiler, what events, columns, and filters do you trace to find your slowest queries and stored procedures?</p> <p>Slow = greater than N seconds, 10 for sake of argument.</p>
820,252
3
1
null
2009-05-04 13:57:39.917 UTC
41
2018-11-15 12:11:54.81 UTC
null
null
null
null
65,223
null
1
57
sql-server|sql-server-2005|profiling
83,970
<p>In SQL 2005 you can use management views to find slow running queries. A good script i found a while ago on <a href="http://www.sql-server-performance.com/articles/per/tsql_statement_performance_p1.aspx" rel="noreferrer">SQL server performance</a> will help get you started; it lists data with the slowest performing first.</p> <pre><code>SELECT creation_time ,last_execution_time ,total_physical_reads ,total_logical_reads ,total_logical_writes , execution_count , total_worker_time , total_elapsed_time , total_elapsed_time / execution_count avg_elapsed_time ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1, ((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS statement_text FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st ORDER BY total_elapsed_time / execution_count DESC; </code></pre>
755,796
How to create a LINQ to SQL Transaction?
<p>I have a piece of code that involves multiple inserts but need to execute submitchanges method before I finish inserting in other tables so that I can aquire an Id. I have been searching through the internet and couldnt find how to create a transaction in linq to sql. I have put comments in the code where I want the transaction to take place.</p> <pre><code> var created = false; try { var newCharacter = new Character(); newCharacter.characterName = chracterName; newCharacter.characterLevel = 1; newCharacter.characterExperience = 0; newCharacter.userUsername = userUsername; newCharacter.characterClassID = ccslst[0].characterClassID; //Open transaction ydc.Characters.InsertOnSubmit(newCharacter); ydc.SubmitChanges(); foreach (var ccs in ccslst) { var cs = new CharacterStat(); cs.statId = ccs.statID; cs.statValue = ccs.statValue; cs.characterID = newCharacter.characterID; ydc.CharacterStats.InsertOnSubmit(cs); } var ccblst = ydc.ClassBodies.Where(cb =&gt; cb.characterClassID == newCharacter.characterClassID); foreach (var ccb in ccblst) { var charBody = new CharacterBody(); charBody.bodyId = ccb.bodyId; charBody.bodyPartId = ccb.bodyPartId; charBody.characterID = newCharacter.characterID; ydc.CharacterBodies.InsertOnSubmit(charBody); } ydc.SubmitChanges(); created = true; //Commit transaction } catch (Exception ex) { created = false; //transaction Rollback; } return created; </code></pre> <p>EDIT: Forgot to mention that ydc is my datacontext</p>
755,804
3
0
null
2009-04-16 11:54:49.81 UTC
20
2021-09-25 15:09:29.93 UTC
2009-05-02 02:00:29.02 UTC
null
67
null
45,471
null
1
69
.net|linq-to-sql|transactions
74,178
<p>Wrap the whole thing in a <code>TransactionScope</code>. Call <code>transaction.Complete()</code> at the point where you want to commit. If the code exits the block without <code>Complete()</code> being called, the transaction will be rolled back. However, after looking at @s_ruchit's answer and re-examining your code, you could probably rewrite this to not require a <code>TransactionScope</code>. The first example uses the <code>TransactionScope</code> with your code as is. The second example makes some minor changes, but accomplishes the same purpose.</p> <p>A place where you would need to use the <code>TransactionScope</code> is when you are reading a value from the database and using it to set a new value on an object being added. In this case the LINQ transaction won't cover the first read, just the later submit of the new value. Since you are using the value from the read to calculate a new value for the write, you need the read to be wrapped in the same transaction to ensure that another reader doesn't calculate the same value and obviate your change. In your case you are only doing writes so the standard LINQ transaction should work.</p> <p>Example 1:</p> <pre><code>var created = false; using (var transaction = new TransactionScope()) { try { var newCharacter = new Character(); newCharacter.characterName = chracterName; newCharacter.characterLevel = 1; newCharacter.characterExperience = 0; newCharacter.userUsername = userUsername; newCharacter.characterClassID = ccslst[0].characterClassID; ydc.Characters.InsertOnSubmit(newCharacter); ydc.SubmitChanges(); foreach (var ccs in ccslst) { var cs = new CharacterStat(); cs.statId = ccs.statID; cs.statValue = ccs.statValue; cs.characterID = newCharacter.characterID; ydc.CharacterStats.InsertOnSubmit(cs); } var ccblst = ydc.ClassBodies.Where(cb =&gt; cb.characterClassID == newCharacter.characterClassID); foreach (var ccb in ccblst) { var charBody = new CharacterBody(); charBody.bodyId = ccb.bodyId; charBody.bodyPartId = ccb.bodyPartId; charBody.characterID = newCharacter.characterID; ydc.CharacterBodies.InsertOnSubmit(charBody); } ydc.SubmitChanges(); created = true; transaction.Complete(); } catch (Exception ex) { created = false; } } return created; </code></pre> <p>Example 2:</p> <pre><code> try { var newCharacter = new Character(); newCharacter.characterName = chracterName; newCharacter.characterLevel = 1; newCharacter.characterExperience = 0; newCharacter.userUsername = userUsername; newCharacter.characterClassID = ccslst[0].characterClassID; ydc.Characters.InsertOnSubmit(newCharacter); foreach (var ccs in ccslst) { var cs = new CharacterStat(); cs.statId = ccs.statID; cs.statValue = ccs.statValue; newCharacter.CharacterStats.Add(cs); } var ccblst = ydc.ClassBodies.Where(cb =&gt; cb.characterClassID == newCharacter.characterClassID); foreach (var ccb in ccblst) { var charBody = new CharacterBody(); charBody.bodyId = ccb.bodyId; charBody.bodyPartId = ccb.bodyPartId; newCharacter.CharacterBodies.Add(charBody); } ydc.SubmitChanges(); created = true; } catch (Exception ex) { created = false; } </code></pre>
22,123,368
How to set Cell value of DataGridViewRow by column name?
<p>In windows forms, I'm trying to fill a <code>DataGridView</code> manually by inserting <code>DataGridViewRows</code> to it, so my code looks like this:</p> <pre><code>DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dgvArticles); row.Cells[0].Value = product.Id; row.Cells[1].Value = product.Description; . . . dgvArticles.Rows.Add(row); </code></pre> <p>However, I would like to add the Cell value by column name instead of doing it by the index, something like this:</p> <pre><code>row.Cells["code"].Value = product.Id; row.Cells["description"].Value = product.Description; </code></pre> <p>But doing it like that throws an error saying it couldn't find the column named "code". I'm setting the DataGridView columns from the designer like this: <img src="https://i.stack.imgur.com/f2s5e.png" alt="Columns from DataGridViewDesigner"></p> <p>Am I doing something wrong? How can I accomplish what I want to do?</p>
22,123,944
5
0
null
2014-03-02 03:08:28.17 UTC
4
2018-12-14 04:28:36.98 UTC
2014-03-02 03:35:42.207 UTC
null
301,857
user2612401
null
null
1
19
c#|winforms|datagridview|datagridviewrow
63,896
<p>So in order to accomplish the approach you desire it would need to be done this way:</p> <pre><code>//Create the new row first and get the index of the new row int rowIndex = this.dataGridView1.Rows.Add(); //Obtain a reference to the newly created DataGridViewRow var row = this.dataGridView1.Rows[rowIndex]; //Now this won't fail since the row and columns exist row.Cells["code"].Value = product.Id; row.Cells["description"].Value = product.Description; </code></pre>
36,523,282
AWS ECS Error when running task: No Container Instances were found in your cluster
<p>Im trying to deploy a <code>docker</code> container image to <code>AWS</code> using <code>ECS</code>, but the EC2 instance is not being created. I have scoured the internet looking for an explanation as to why I'm receiving the following error: </p> <blockquote> <p>"A client error (InvalidParameterException) occurred when calling the RunTask operation: No Container Instances were found in your cluster."</p> </blockquote> <p><strong>Here are my steps:</strong> </p> <p>1. Pushed a docker image FROM Ubuntu to my Amazon ECS repo.</p> <p>2. Registered an ECS Task Definition:</p> <pre><code>aws ecs register-task-definition --cli-input-json file://path/to/my-task.json </code></pre> <p>3. Ran the task: </p> <pre><code>aws ecs run-task --task-definition my-task </code></pre> <p>Yet, it fails.</p> <p><strong>Here is my task:</strong></p> <pre><code>{ "family": "my-task", "containerDefinitions": [ { "environment": [], "name": "my-container", "image": "my-namespace/my-image", "cpu": 10, "memory": 500, "portMappings": [ { "containerPort": 8080, "hostPort": 80 } ], "entryPoint": [ "java", "-jar", "my-jar.jar" ], "essential": true } ] } </code></pre> <p>I have also tried using the management console to configure a cluster and services, yet I get the same error. How do I configure the cluster to have ec2 instances, and what kind of container instances do I need to use? <em>I thought this whole process was to create the EC2 instances to begin with!!</em></p>
36,533,601
11
2
null
2016-04-09 22:04:53.813 UTC
31
2022-08-05 02:13:29.61 UTC
2018-08-01 06:04:00.753 UTC
null
4,122,849
null
1,380,406
null
1
153
amazon-web-services|docker|aws-cli|amazon-ecs
95,614
<p>I figured this out after a few more hours of investigating. Amazon, if you are listening, you should state this somewhere in your management console when creating a cluster or adding instances to the cluster:</p> <blockquote> <p><em>&quot;Before you can add ECS instances to a cluster you must first go to the EC2 Management Console and create <code>ecs-optimized</code> instances with an IAM role that has the <code>AmazonEC2ContainerServiceforEC2Role</code> policy attached&quot;</em></p> </blockquote> <p><strong>Here is the rigmarole:</strong></p> <p>1. Go to your <a href="https://console.aws.amazon.com/ec2" rel="noreferrer">EC2 Dashboard</a>, and click the <code>Launch Instance</code> button.</p> <p>2. Under <code>Community AMIs</code>, Search for <code>ecs-optimized</code>, and select the one that best fits your project needs. Any will work. Click next.</p> <p>3. When you get to Configure Instance Details, click on the <code>create new IAM role link</code> and create a new role called <code>ecsInstanceRole</code>.</p> <p>4. Attach the <code>AmazonEC2ContainerServiceforEC2Role</code> policy to that role.</p> <p>5. Then, finish configuring your ECS Instance. <br /><strong>NOTE:</strong> If you are creating a web server you will want to create a securityGroup to allow access to port 80.</p> <p>After a few minutes, when the instance is initialized and running you can refresh the ECS Instances tab you are trying to add instances too.</p>
35,022,473
Difference between first() and take(1)
<p>I am trying to understand the details of <code>RxJava</code>.</p> <p>Intuitively I expected <code>first()</code> and <code>take(1)</code> to be equal and do the same. However by digging in the source code <code>first()</code> is defined as <code>take(1).single()</code>.</p> <p>What is the <code>single()</code> here good for? Doesn't <code>take(1)</code> already guarantee to output a single item?</p>
35,031,814
2
2
null
2016-01-26 19:41:40.443 UTC
8
2019-11-18 17:29:05.273 UTC
2016-01-26 19:58:03.95 UTC
null
3,256,506
null
3,761,545
null
1
36
java|reactive-programming|rx-java
15,292
<p>The difference is that <code>take(1)</code> will relay 0..1 items from upstream whereas <code>first</code> will relay the very first element or emits an error (NoSuchElementException) if the upstream is empty. Neither of them is blocking.</p> <p>It is true <code>first == take(1).single()</code> where <code>take(1)</code> limits the number of upstream items to 1 and <code>single()</code> makes sure upstream isn't empty.</p> <p>This example prints "Done" only</p> <pre><code>Observable.empty().take(1) .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example prints "1" followed by "Done":</p> <pre><code>Observable.just(1).take(1) .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example also prints "1" followed by "Done":</p> <pre><code>Observable.just(1, 2, 3).take(1) .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example fails with <code>NoSuchElementException</code></p> <pre><code>Observable.empty().first() .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example, again, prints "1" followed by "Done":</p> <pre><code>Observable.just(1).first() .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example, again, prints "1" followed by "Done":</p> <pre><code>Observable.just(1, 2, 3).first() .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example prints a stacktrace of <code>NoSuchElementException</code> because the source contained too few elements:</p> <pre><code>Observable.empty().single() .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre> <p>This example prints a stacktrace of <code>IllegalArgumentException</code> because the source contained too many elements:</p> <pre><code>Observable.just(1, 2, 3).single() .subscribe(System.out::println, Throwable::printStackTrace, () -&gt; System.out.println("Done")); </code></pre>
20,389,088
Gitk lower panel cannot resize
<p>In gitk there are two panel, the top panel which display mostly the list of commits, and the bottom panel which shows changes in this commit. Somehow, since this week I cannot adjust the height of these two panels, like making one of them bigger/smaller. Any idea why?</p>
20,390,044
4
0
null
2013-12-05 00:32:40.777 UTC
2
2021-08-04 18:25:17.02 UTC
null
null
null
null
2,613,667
null
1
32
git|gitk
2,747
<p>Maybe you don't see thin resize widget? It's between searchbars:</p> <p><a href="https://i.stack.imgur.com/XhyeQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XhyeQ.png" alt="The specific spot highlighted"></a></p> <p>Try to change "Edit - Preferences - Use themed widgets" option and restart gitk.</p>
24,127,032
Proper usage of intrinsicContentSize and sizeThatFits: on UIView Subclass with autolayout
<p>I'm asking this (somehow) simple question just to be finicky, because sometimes I'm worried about a misuse I might be doing of many UIView's APIs, especially when it comes to autolayout.</p> <p>To make it super simple I'll go with an example, let's assume I need an UIView subclass that has an image icon and a multiline label; the behaviour I want is that the height of my view changes with the height of the label (to fit the text inside), also, I'm laying it out with Interface builder, so I have something like this:</p> <p><img src="https://i.stack.imgur.com/P5GvC.png" alt="simple view image"></p> <p>with some constraints that give fixed width and height to the image view, and fixed width and position (relative to the image view) to the label:</p> <p><img src="https://i.stack.imgur.com/XsKSt.png" alt="simple view image, constraints shown"></p> <p>Now, if I set some text to the label, I want the view to be resized in height to fit it properly, or remain with the same height it has in the xib. Before autolayout I would have done always something like this:</p> <p>In the CustoView subclass file I would have overridden <code>sizeThatFits:</code> like so:</p> <pre><code>- (CGSize) sizeThatFits:(CGSize)size{ //this stands for whichever method I would have used //to calculate the height needed to display the text based on the font CGSize labelSize = [self.titleLabel intrinsicContentSize]; //check if we're bigger than what's in ib, otherwise resize CGFloat newHeight = (labelSize.height &lt;= 21) ? 51: labelSize.height+20; size.height = newHeight; return size; } </code></pre> <p>And than I would have called something like:</p> <pre><code>myView.titleLabel.text = @"a big text to display that should be more than a line"; [myView sizeToFit]; </code></pre> <p>Now, thinking in constraints, I know that autolayout systems calls <code>intrinsicContentSize</code> on the view tree elements to know what their size is and make its calculations, therefore I should override <code>intrinsicContentSize</code> in my subview to return the exact same things it returns in the <code>sizeThatFits:</code> method previously shown, except for the fact that, previously, when calling <code>sizeToFit</code> I had my view properly resized, but now with autolayout, in combination with a xib, this is not going to happen.</p> <p>Of course I might be calling <code>sizeToFit</code> every time I edit text in my subclass, along with an overridden <code>intrinsicContentSize</code> that returns the exact same size of <code>sizeThatFits:</code>, but somehow I don't think this is the proper way of doing it.</p> <p>I was thinking about overriding <code>needsUpdateConstraints</code> and <code>updateConstraints</code>, but still makes not much sense since my view's width and height are inferred and translated from autoresizing mask from the xib.</p> <p>So long, what do you think is the cleanest and most correct way to make exactly what I show here and support fully autolayout? </p>
26,353,000
1
0
null
2014-06-09 18:57:41.15 UTC
32
2015-07-21 04:41:14.953 UTC
null
null
null
null
671,997
null
1
67
ios|objective-c|uiview|autolayout|cgsize
48,244
<p>I don't think you need to define an intrinsicContentSize.</p> <p>Here's two reasons to think that:</p> <ol> <li><p>When the Auto Layout documentation discusses <code>intrinsicContentSize</code>, it refers to it as relevant to "leaf-views" like buttons or labels where a size can be computed purely based on their content. The idea is that they are the leafs in the view hierarchy tree, not branches, because they are not composed of other views.</p></li> <li><p>IntrinsicContentSize is not really a "fundamental" concept in Auto Layout. The fundamental concepts are just constraints and the attributes bound by constraints. The intrinsicContentSize, the content-hugging priorities, and the compression-resistance priorities are really just conveniences to be used to generate internal constraints concerning size. The final size is just the result of those constraints interacting with all other constraints in the usual way.</p></li> </ol> <p>So what? So if your "custom view" is really just an assembly of a couple other views, then you don't need to define an intrinsicContentSize. You can just define the constraints that create the layout you want, and those constraints will also produce the size you want.</p> <p>In the particular case that you describe, I'd set a >=0 bottom space constraint from the label to the superview, another one from the image to the superview, and then also a <em>low priority</em> constraint of height zero for the view as a whole. The low priority constraint will try to shrink the assembly, while the other constraints stop it from shrinking so far that it clips its subviews.</p> <p>If you never define the intrinsicContentSize explicitly, how do you see the size resulting from these constraints? One way is to force layout and then observe the results.</p> <p>Another way is to use <code>systemLayoutSizeFittingSize:</code> (and in iOS8, the little-heralded <code>systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority:</code>). This is a closer cousin to <code>sizeThatFits:</code> than is <code>intrinsicContentSize</code>. It's what the system will use to calculate your view's appropriate size, taking into account all constraints it contains, including intrinsic content size constraints as well as all the others.</p> <p>Unfortunately, if you have a multi-line label, you'll likely also need to configure <code>preferredMaxLayoutWidth</code> to get a good result, but that's another story...</p>
24,279,948
Rails: Validate only on create, or on update when field is not blank
<p>How can I restrict a Rails validation to check only on create OR when the field isn't blank? I'm creating a user settings page for an app I'm working on and the problem is that, when updating using the parameters provided by the form, the settings will only save when both a password and password confirmation are present. I would like these password fields to validate on create no matter what, but only on update when they are provided.</p>
24,280,141
5
0
null
2014-06-18 07:54:32.423 UTC
13
2021-10-20 07:54:56.723 UTC
null
null
null
null
507,164
null
1
46
ruby-on-rails|ruby|rails-activerecord
59,889
<p>If you want to allow blank values use: <a href="http://guides.rubyonrails.org/active_record_validations.html#allow-blank">allow_blank</a> with validates.</p> <pre><code>class Topic &lt; ActiveRecord::Base validates :title, length: { is: 5 }, allow_blank: true end </code></pre> <p>If you want to validate only on create, use <a href="http://guides.rubyonrails.org/active_record_validations.html#on">on</a> with validates.</p> <pre><code>class Topic &lt; ActiveRecord::Base validates :email, uniqueness: true, on: :create end </code></pre> <p>To cover your case:</p> <pre><code>class Topic validates :email, presence: true, if: :should_validate? def should_validate? new_record? || email.present? end end </code></pre>
6,253,256
Setting processData to false in jQuery breaks my AJAX request
<p>I've googled for a while now and can only find what <code>processData: false</code> does. I can't find anyone who has experienced this same issue.</p> <p>I'm passing JSON back to the server and do not want jQuery to automatically convert the data to a query string so I'm setting processData to false. I can see the request firing if I take out processData, but as soon as I put it in I do not see any requests being made (using Firebug &amp; Chrome dev tools).</p> <pre><code>$.ajax({ url: myUrl, type: "POST", data: {foo: "bar"}, processData: false, contentType: 'application/json' }); </code></pre> <p>The request I was initially making was a bit more complex than this but I've simplified it to try to narrow down the problem but this simple piece of code does not work either (again, it does work if I comment out processData). Also, I am not seeing any JavaScript errors in the console.</p> <h2>Edit</h2> <p>For future web searchers: As lonesomeday pointed out, jQuery will not throw any errors if you supply either a JS object or an incorrectly formatted JSON string. It will simply not fire the request.</p>
6,253,318
3
0
null
2011-06-06 14:07:42.003 UTC
9
2019-04-04 00:38:28.977 UTC
2018-03-13 18:11:33.737 UTC
null
472,495
null
786,052
null
1
19
ajax|json|jquery
57,983
<p>You want to pass the data as JSON. You are passing a Javascript object. JSON is a way of serializing Javascript objects to strings so that they can be passed around without compatibility issues.</p> <p>You actually want to pass the JSON in a string:</p> <pre><code>$.ajax({ url: myUrl, type: "POST", data: '{"foo": "bar"}', processData: false, contentType: 'application/json' }); </code></pre>
5,959,194
How does jQuery's "document ready" function work?
<p>How is jQuery checking if the document is loaded? How it is checking that the document load is finished?</p>
5,959,237
3
0
null
2011-05-11 04:18:02.397 UTC
11
2012-07-17 12:10:01.017 UTC
2011-05-11 04:25:23.717 UTC
null
62,082
null
735,490
null
1
34
jquery
12,210
<p>Check out the function bindReady in the <a href="http://code.jquery.com/jquery-1.6.js">source code</a>.</p> <p>They bind to the DOMContentLoaded event (or onreadystatechange on some browsers). They also have a fallback to the regular load event, in case the DOMContentLoaded isn't supported or not fired for other reasons. On browsers supporting it, they use this call:</p> <pre><code>document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); </code></pre> <p>On IE &lt;9:</p> <pre><code>document.attachEvent( "onreadystatechange", DOMContentLoaded); </code></pre> <p>The second instance of <code>DOMContentLoaded</code> in these calls is their own function - actually a reference to the <code>ready</code> function right above <code>bindReady</code> in the source code. This function will check that the DOM tree is actually done by checking for <code>document.body</code>. If it doesn't exist yet, they wait a millisecond (using setTimeout) and check again. When document.body exists, they traverse the list of callbacks you've set.</p>
6,273,607
Windows Azure - Serve unknown (mp4) MIME types in Windows Azure IIS storage
<p>I have a windows azure deployment (a web-role) that on request pulls in a pair of video files (mov and mp4) from azure storage into it's own local IIS storage, which I then access through the browser. </p> <p>It may sound silly, but I have good reasons for doing this. </p> <p>Unfortunately, I am unable to access the mp4 files. The mov are fine, but the mp4 give me "404 - File or directory not found."</p> <p>I've looked into this, and it seems to be because IIS will not return unknown file types, and mp4 must fall under this category. If it was a normal IIS server I would be able to register the mp4 mime type, but I don't know how to go about this in Windows Azure.</p> <p>I could RDP in and do it manually, but this would not be practical as the role is replaced frequently and would mean I would need to re-do it manually every time. It must be done through one of the config files or in code. </p> <p>Can anyone help?</p> <p>Thanks!!</p> <p>Steven</p>
6,274,043
4
0
null
2011-06-08 02:32:30.147 UTC
9
2019-04-12 16:24:24.333 UTC
null
null
null
null
629,438
null
1
18
c#|iis|azure|mime-types
14,117
<p>Can you not add custom mime type in web.config? I just ran into this link: </p> <p><a href="http://www.iis.net/ConfigReference/system.webServer/staticContent/mimeMap">http://www.iis.net/ConfigReference/system.webServer/staticContent/mimeMap</a></p> <p>The relevant web.config xml is:</p> <pre><code>&lt;configuration&gt; &lt;system.webServer&gt; &lt;staticContent&gt; &lt;mimeMap fileExtension=".syx" mimeType="application/octet-stream" /&gt; &lt;mimeMap fileExtension=".tab" mimeType="text/plain" /&gt; &lt;/staticContent&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Hope this helps.</p>
52,701,665
TypeScript React Native Flatlist: How to give renderItem the correct type of it's item?
<p>I'm building a React Native app with TypeScript. <code>renderItem</code> complains that the destructured item implicitly has an <code>any</code> type. I googled and found <a href="https://stackoverflow.com/questions/50743606/how-to-use-generic-component-in-react-native-with-typescript">this question</a> and tried to implement what they teach here combined with the types in <code>index.d.ts</code> of the <code>@types</code> package for React Native.</p> <pre><code>export interface Props { emotions: Emotion[]; } class EmotionsPicker extends PureComponent&lt;Props&gt; { keyExtractor = (item, index) =&gt; index; renderItem = ({ item }) =&gt; ( &lt;ListItem title={item.name} checkmark={item.checked} /&gt; ); render() { return ( &lt;FlatList&lt;Emotion&gt; keyExtractor={this.keyExtractor} renderItem={this.renderItem} data={this.props.emotions} /&gt; ); } } </code></pre> <p>Unfortunately this does not work. How can I give item the type <code>Emotion</code>?</p>
57,531,385
9
1
null
2018-10-08 11:52:32.21 UTC
11
2022-09-15 09:43:55.173 UTC
null
null
null
null
8,331,756
null
1
49
typescript|object|react-native|typescript-typings|react-native-flatlist
46,984
<p>I know it's an old question but people googling it might still appreciate it.</p> <pre><code>import { FlatList, ListRenderItem } from 'react-native' /* . . . */ renderItem: ListRenderItem&lt;Emoticon&gt; = ({ item }) =&gt; ( &lt;ListItem title={item.name} checkmark={item.checked} /&gt; ); </code></pre>
28,923,716
Getting Resolve error while importing project in android studio, Unable to load class 'org.codehaus.groovy.runtime.typehandling.ShortTypeHandling'
<p>I am not able to import a project in AndroidStudio because of following error:</p> <pre><code>Unable to load class 'org.codehaus.groovy.runtime.typehandling.ShortTypeHandling'. </code></pre> <p>I have no idea about the project. Why I am getting this error and how do I fix it.</p>
29,695,756
4
1
null
2015-03-08 06:21:32.42 UTC
12
2015-09-16 05:57:02.583 UTC
2015-09-16 05:57:02.583 UTC
null
2,245,895
null
2,245,895
null
1
37
android|groovy|android-studio|gradle
16,750
<p>I have had a same problem. And I have found a solution.</p> <p><strong>Cause</strong></p> <p>This problem is caused by <strong>android gradle plugin does not match for gradle version</strong>. </p> <p><strong>Solution</strong></p> <p>Edit build.gradle in project. gradle plugin version must be satisfied requirements for android studio.</p> <pre><code>dependencies { classpath 'com.android.tools.build:gradle:1.1.0' } </code></pre> <p>And edit distrubutionUrl in gradle/wrapper/gradle-wrapper.properties. version of gradle must be satisfied requirements for gradle plugin.</p> <pre><code>distributionUrl=http\://services.gradle.org/distributions/gradle-2.2.1-all.zip </code></pre> <p>You can find version compatibilities between android studio, android gradle plugin and gradle in <a href="http://tools.android.com/tech-docs/new-build-system/version-compatibility">this page</a></p>
5,653,114
Display image in Qt to fit label size
<p>I already tried several methods on displaying an image on a form, but none of them works how I would like. </p> <p>I've read many places that the easiest way is to create a label and use that to display the image. I have a label, which size is specified by the layout, but if I load an image into it with a pixmap, the label is resized to the size of the image. If I use img tag as text or css background property, it won't display the whole image. What I would like to do is to load the image and fit into the label, not changing the label's size, but when I resize my window, and by that resizing the label as well, the image should be resized too so it will always fit into it.</p> <p>If the only method is to get the label's size, and resize the pixmap so it would fit, and handle the resize event (signal), how could I resize the pixmap? I hope I won't need to save the whole thing into a QImage and create a pixmap from it each time.</p> <p>Also, how can I center it? If it can't fit both the width and the height, I would like the smaller dimension to be centered.</p> <p>Oh, and I don't want to use sliders to handle overflows.</p>
5,653,467
9
0
null
2011-04-13 17:24:43.96 UTC
10
2022-02-04 04:28:26.977 UTC
2014-06-19 13:54:53.113 UTC
null
93,922
null
421,009
null
1
38
image|qt|autoresize
79,469
<p>Does <a href="http://qt-project.org/doc/qt-4.8/qlabel.html#scaledContents-prop" rel="noreferrer">QLabel::setScaledContents(bool)</a> help? There may also be some useful information in the <a href="http://doc.qt.io/qt-5/qtwidgets-widgets-imageviewer-example.html" rel="noreferrer">image viewer example</a> too.</p>
5,787,809
Get spinner selected items text?
<p>How to get spinner selected item's text?</p> <p>I have to get the text on the item selected in my spinner when i click on the save button. i need the text not the Index.</p>
5,787,902
13
0
null
2011-04-26 08:31:25.28 UTC
70
2020-10-11 20:52:38.117 UTC
2015-06-29 19:18:33.117 UTC
null
1,908,328
null
689,853
null
1
417
android|android-spinner
461,165
<pre><code>Spinner spinner = (Spinner)findViewById(R.id.spinner); String text = spinner.getSelectedItem().toString(); </code></pre>
17,959,728
Annotation Processor, generating a compiler error
<p>I'm trying to create a custom annotation that, for example, ensures that a field or method is both <code>public</code> and <code>final</code>, and would generate a compile time error if the field or method is not both <code>public</code> and <code>final</code>, as in these examples:</p> <pre><code>// Compiles @PublicFinal public final int var = 2; // Compiles @PublicFinal public final void myMethod {} // Compile time error @PublicFinal private final int fail = 2; </code></pre> <p>So far, I've made both the custom annotation interface:</p> <pre><code>import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface PublicFinal { } </code></pre> <p>and <code>Processor</code>:</p> <pre><code>import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import java.util.Set; @SupportedAnnotationTypes("PublicFinal") public class PubicFinalProcessor extends AbstractProcessor { @Override public boolean process( Set&lt;? extends TypeElement&gt; annotations, RoundEnvironment roundEnv) { for (TypeElement typeElement : annotations) { Set&lt;Modifier&gt; modifiers = typeElement.getModifiers(); if (!modifiers.contains(Modifier.FINAL) || !modifiers.contains(Modifier.PUBLIC)) { // Compile time error. // TODO How do I raise an error? } } // All PublicFinal annotations are handled by this Processor. return true; } } </code></pre> <p>As hinted by the <code>TODO</code>, I do not know how to generate the compile time error. The <a href="http://docs.oracle.com/javase/6/docs/api/javax/annotation/processing/Processor.html">documentation</a> of Processor makes it clear that I should not be throwing an exception,</p> <blockquote> <p>If a processor throws an uncaught exception, the tool may cease other active annotation processors.</p> </blockquote> <p>It goes on to describe what happens when an error condition is raised, but now <em>how</em> to raise an error condition.</p> <p>Question: how do I raise an error condition such that it generates a compile time error?</p>
17,959,831
1
0
null
2013-07-31 00:33:56.083 UTC
9
2013-07-31 00:49:51.207 UTC
null
null
null
null
1,354,590
null
1
25
java|annotations|javac
8,433
<p>You probably want <code>processingEnv.getMessager().printMessage(Kind.ERROR, "method wasn't public and final", element)</code>.</p> <p><a href="http://docs.oracle.com/javase/6/docs/api/javax/annotation/processing/Messager.html">Messager:</a> "Printing a message with an error kind will raise an error."</p>
5,209,149
What is Inject Method in Groovy?
<p>What does the <code>inject</code> method in Groovy actually do? I googled it, and have not found the exact answer. Can anyone specify its use with a simple example?</p>
5,209,286
1
0
null
2011-03-06 06:46:47.53 UTC
11
2014-07-16 18:01:17.263 UTC
2014-07-16 18:01:17.263 UTC
null
119,509
null
576,682
null
1
42
groovy
20,472
<p>It applies an operation to a collection and keeps track of an intermediate value. Take this example: <code>[1, 2, 3, 4].inject(0, { sum, value -&gt; sum + value })</code>. This says use 0 as the initial value and apply the addition operation to the intermediate result and each element in sequence. Each application of the operation generates a new intermediate result. In this case, the closure adds up the numbers, so it generates the sum of the list. You can imagine it like:</p> <pre><code>&lt;initial value&gt; &lt;operation&gt; &lt;element1&gt; &lt;operation&gt; ... &lt;elementn&gt; </code></pre> <p>Or, in the case of <code>[1, 2, 3, 4].inject(0, { sum, value -&gt; sum + value })</code>:</p> <pre><code>0 + 1 + 2 + 3 + 4 </code></pre> <p>To find the product of a list, you can use <code>[1, 2, 3, 4].inject(1, { product, value -&gt; product * value})</code>. In this case, 1 is used as the initial value, since it is the identity value for mulitplication.</p> <p>Here's an example that splits a list of multi-word strings into a flat list of words:</p> <pre><code>strings = ["", "this", "is a", "test of inject!"] words = strings.inject([], { list, value -&gt; list + value.tokenize() }) assert words == ["this", "is", "a", "test", "of", "inject!"] </code></pre> <p>Other terms that are sometimes used to describe this operation are "reduce", as in <a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer">MapReduce</a>, or a "fold" (specifically a <a href="http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29" rel="noreferrer">foldl</a>).</p>
24,706,267
Error : Cannot read property 'map' of undefined
<p>I'm following the <code>reactjs</code> tutorial, and I keep running into an issue when<br/> <strong>passing the value from the state of one component into another component</strong>.<br/></p> <p>The error <code>Cannot read property 'map' of undefined'</code> is thrown when the <code>map</code> function in the <code>CommentList</code> component is executed.</p> <blockquote> <p>What would cause the <code>prop</code> to be <code>undefined</code> when passing from <code>CommentBox</code> into the <code>CommentList</code>? </p> </blockquote> <pre class="lang-js prettyprint-override"><code>// First component var CommentList = React.createClass({ render: function() { var commentNodes = this.props.data.map(function (comment){ return &lt;div&gt;&lt;h1&gt;{comment.author}&lt;/h1&gt;&lt;/div&gt;; }); return &lt;div className="commentList"&gt;{commentNodes}&lt;/div&gt;; } }); // Second component var CommentBox = React.createClass({ getInitialState: function(){ return {data: []}; }, getComments: function(){ $.ajax({ url: this.props.url, dataType: 'json', success: function(data){ this.setState({data: data}) }.bind(this), error: function(xhr, status, err){ console.error(url, status, err.toString()) }.bind(this) }); }, componentWillMount: function(){ this.getComments() }, render: function(){ return &lt;div className="commentBox"&gt;{&lt;CommentList data={this.state.data.comments}/&gt;}&lt;/div&gt;; } }); React.renderComponent( &lt;CommentBox url="comments.json" /&gt;, document.getElementById('content')); </code></pre>
24,706,849
11
1
null
2014-07-11 20:44:48.38 UTC
21
2022-08-19 16:21:09.533 UTC
2021-05-04 03:34:47.03 UTC
null
-1
null
152,533
null
1
93
reactjs
518,327
<p>First of all, set more safe initial data:</p> <pre><code>getInitialState : function() { return {data: {comments:[]}}; }, </code></pre> <p>And ensure your ajax data.</p> <p>It should work if you follow above two instructions like <a href="http://jsbin.com/hozamejo/1/edit">Demo.</a></p> <p>Updated: you can just wrap the .map block with conditional statement.</p> <pre><code>if (this.props.data) { var commentNodes = this.props.data.map(function (comment){ return ( &lt;div&gt; &lt;h1&gt;{comment.author}&lt;/h1&gt; &lt;/div&gt; ); }); } </code></pre>
44,480,761
Android Room compile-time warning about column in foreign key not part of an index. What does it mean?
<p>I'm using Android's Room Persistence Library from the Android Architecture Components recently announced at Google I/O. Things seem to be working, but I'm getting the following error:</p> <blockquote> <p>Warning:tagId column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column.</p> </blockquote> <p>My database has 3 tables: <code>Note</code>, <code>Tag</code>, and <code>JoinNotesTags</code>. Notes to Tags is a many-to-many relationship, hence the JoinNotesTags table to handle the mapping. The tables are straightforward:</p> <ul> <li><code>Note.id</code> and <code>Tag.id</code> are both primary keys</li> <li><code>JoinNotesTags.noteId</code> references <code>Note.id</code></li> <li><code>JoinNotesTags.tagId</code> references <code>Tag.id</code></li> </ul> <p>The foreign key constraints are defined on the <code>JoinNotesTags</code> table. For reference, here is the <code>CREATE TABLE</code> statement for the <code>JoinNotesTags</code> table:</p> <pre><code>"CREATE TABLE IF NOT EXISTS `JoinNotesTags` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `noteId` INTEGER, `tagId` INTEGER, FOREIGN KEY(`noteId`) REFERENCES `Note`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`tagId`) REFERENCES `Tag`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )" </code></pre> <p>And here is the corresponding <code>@Entity</code> annotation for that class:</p> <pre><code>@Entity( indices = arrayOf(Index(value = *arrayOf("noteId", "tagId"), unique = true)), foreignKeys = arrayOf( ForeignKey( entity = Note::class, parentColumns = arrayOf("id"), childColumns = arrayOf("noteId"), onDelete = ForeignKey.CASCADE), ForeignKey( entity = Tag::class, parentColumns = arrayOf("id"), childColumns = arrayOf("tagId")) ) ) </code></pre> <p>As you can see from the <code>@Entity</code> annotation, <code>tagId</code> <em>is</em> included in a composite unique index along with <code>noteId</code>. I've confirmed that this index is correctly defined in the auto-generated json schema file as well:</p> <pre><code>"CREATE UNIQUE INDEX `index_JoinNotesTags_noteId_tagId` ON `JoinNotesTags` (`noteId`, `tagId`)" </code></pre> <p>So, my question: Is this warning just a bug in the (still-alpha-release) Room Library -- i.e. the compile-time analysis is missing the fact that <code>tagId</code> is part of this composite index? Or do I really have an indexing problem that I need to resolve in order to avoid full table scans?</p>
44,481,303
4
2
null
2017-06-11 05:44:39.913 UTC
7
2020-04-28 11:40:12.16 UTC
2017-06-11 06:37:11.107 UTC
null
1,363,731
null
1,363,731
null
1
55
android|sqlite|android-sqlite|android-room
29,710
<p>When you modify the <code>Tag</code> table, the database might need to lookup corresponding rows in the <code>JoinNotesTags</code> table. To be efficient, this <a href="http://www.sqlite.org/foreignkeys.html#fk_indexes" rel="noreferrer">requires an index</a> on the <code>tagId</code> column.</p> <p>Your composite index is not useful for that; because of the <a href="http://www.sqlite.org/queryplanner.html" rel="noreferrer">way how indexes work</a>, the column(s) to be searched must be the leftmost column(s) in the index.</p> <p>You should add an index on only the <code>tagId</code> column. (You could swap the order of the columns in the composite index, but then you'd have the same problem with <code>noteId</code>.)</p>
21,929,226
Bind events on AngularJS element directives using jQuery
<p>I have a directive in AngularJS:</p> <pre><code>module = angular.module("demoApp", [], null); module.directive('sample', function () { return { restrict: "E", transclude: true, replace: true, template: "&lt;div ng-transclude&gt;&lt;/div&gt;", controller: function ($scope, $element) { this.act = function (something) { //problematic line HERE $element.trigger("myEvent.sample", [something]); }; } }; }) .directive('item', function () { return { restrict: "E", require: "^sample", transclude: true, replace: true, template: "&lt;a ng-transclude style='display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;'&gt;&lt;/a&gt;", link: function (scope, element, attributes, parentController) { element.on("click", function () { parentController.act(this.innerText); }); } } }); </code></pre> <p>And in my HTML I use it thus:</p> <pre><code>&lt;sample id="myElement"&gt; &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt; &lt;/sample&gt; </code></pre> <p>Which will be rendered as:</p> <pre><code>&lt;div ng-transclude="" id="myElement"&gt; &lt;a ng-transclude="" style="display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;;display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;" class="ng-scope"&gt;&lt;span class="ng-scope"&gt;1&lt;/span&gt;&lt;/a&gt; &lt;a ng-transclude="" style="display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;;display: inline-block; border: 1px solid crimson; margin: 2px; padding: 5px; color: crimson; text-decoration: none; background: #f5d0d0; cursor: pointer;" class="ng-scope"&gt;&lt;span class="ng-scope"&gt;2&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I want to be able to listen to events triggered manually through jQuery:</p> <pre><code>$("#myElement").on("myEvent.sample", function (e, something) { alert("click: " + something); }); </code></pre> <p>I want this event to be triggered whenever the link is clicked.</p> <p>If I set the <code>replace</code> property to <code>false</code> on the <code>sample</code> directive, it works. I guess it is because at the point where the event is fired, the element <code>sample</code> no longer exists, and as such it will have been replaced by the inner template.</p> <p>So, how do I accomplish this?</p> <p>Doing this, as suggested in the answer below, will not accomplish my purpose:</p> <pre><code>$($element).trigger("myEvent.sample", [something]); </code></pre>
21,997,532
2
1
null
2014-02-21 08:35:15.743 UTC
2
2020-01-02 23:35:14.537 UTC
2020-01-02 23:35:14.537 UTC
null
4,370,109
null
1,048,157
null
1
7
jquery|angularjs|events|angularjs-directive|jquery-events
44,096
<p>Please find below the fiddle</p> <p><a href="http://jsfiddle.net/sb_satchitanand/h49nz/">fiddle</a></p> <p>Trigger is a jquery function which will work on proper handler. </p> <pre><code>$(element).trigger("myEvent.sample"); </code></pre> <p>Hope this helps</p>
9,527,378
Should <sections> have <articles> or should <articles> have <sections>?
<p>I'm reading Mark Pilgirm's "<a href="http://www.diveintohtml5.net/semantics.html" rel="noreferrer">Dive into HTML5</a>" and in the <a href="http://www.diveintohtml5.net/semantics.html#new-elements" rel="noreferrer">semantics section</a>, it talks about how HTML5 introduces the <code>&lt;article&gt;</code> and <code>&lt;section&gt;</code> elements. It says that <code>&lt;section&gt;</code>s represent a generic document or section, while <code>&lt;article&gt;</code>s represent a self-contained composition. I don't see a logically semantic parent-child relationship either way.</p> <p>I tried running the following code through the <a href="http://gsnedders.html5.org/outliner/" rel="noreferrer">HTML5 Outliner</a> and it seemed to indicate that the document outline comes out the same, no matter how they were nested. </p> <p>So my question is: should <code>&lt;section&gt;</code>s be nested inside <code>&lt;article&gt;</code>s, should <code>&lt;article&gt;</code>s be nested inside <code>&lt;secion&gt;</code>s, or does it not matter from a semantic view point? </p> <pre><code>&lt;section&gt;&lt;h1&gt;section article?&lt;/h1&gt; &lt;article&gt;&lt;h1&gt;art 1&lt;/h1&gt;&lt;/article&gt; &lt;article&gt;&lt;h1&gt;art 2&lt;/h1&gt;&lt;/article&gt; &lt;article&gt;&lt;h1&gt;art 3&lt;/h1&gt;&lt;/article&gt; &lt;/section&gt; &lt;article&gt;&lt;h1&gt;article section?&lt;/h1&gt; &lt;section&gt;&lt;h1&gt;sec 1&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 2&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 3&lt;/h1&gt;&lt;/section&gt; &lt;/article&gt; </code></pre>
9,527,412
3
0
null
2012-03-02 03:00:03.99 UTC
10
2022-02-01 14:28:26.493 UTC
2012-03-15 21:02:28.713 UTC
null
106,224
null
625,840
null
1
12
html|semantic-markup
12,017
<p>It's entirely acceptable to nest them either way. Although the document outline does not distinguish between a <code>&lt;section&gt;</code> and an <code>&lt;article&gt;</code>, from a semantic point of view they are two different things. That's the whole point of introducing them as two distinct semantic elements.</p> <p>Use the first snippet if your page consists of multiple articles.</p> <p>Use the second snippet when you have an article that's comprehensive enough to contain multiple sections.</p> <p>You can even combine them both if using both fits your content, such that your markup looks like this:</p> <pre><code>&lt;section&gt;&lt;h1&gt;section article?&lt;/h1&gt; &lt;article&gt;&lt;h1&gt;art 1&lt;/h1&gt; &lt;section&gt;&lt;h1&gt;sec 1.1&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 1.2&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 1.3&lt;/h1&gt;&lt;/section&gt; &lt;/article&gt; &lt;article&gt;&lt;h1&gt;art 2&lt;/h1&gt; &lt;section&gt;&lt;h1&gt;sec 2.1&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 2.2&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 2.3&lt;/h1&gt;&lt;/section&gt; &lt;/article&gt; &lt;article&gt;&lt;h1&gt;art 3&lt;/h1&gt; &lt;section&gt;&lt;h1&gt;sec 3.1&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 3.2&lt;/h1&gt;&lt;/section&gt; &lt;section&gt;&lt;h1&gt;sec 3.3&lt;/h1&gt;&lt;/section&gt; &lt;/article&gt; &lt;/section&gt; </code></pre>
9,497,223
How to upgrade a running Elasticsearch older instance to a newer version?
<p>Essentially I cannot find documents or resources that explains the procedure of upgrading a running Elasticsearch instance into the current version. </p> <p>Please help me out in a few scenarios:</p> <ol> <li><p>If I am running an Elasticsearch instance in a single server, how do I upgrade the instance and not lose data?</p></li> <li><p>If I am running multiple Elasticsearch instances in a number of servers, how do I keep my operations running, while I upgrade my Elasticsearch instances without losing data?</p></li> </ol> <p>If there are proper procedures or explanations on this it will greatly help my understanding and work. Thanks!</p>
9,501,950
6
0
null
2012-02-29 10:16:35.337 UTC
13
2020-07-16 16:02:14.323 UTC
null
null
null
null
1,239,936
null
1
41
elasticsearch
45,820
<ol> <li><p>All node data is stored in elasticsearch data directory. It's data/cluster_name/nodes by default in elasticsearch home. So, in general, as long as data directory is preserved and config files in the new version are compatible with the old version, the new instance should have the same data as the old one. Please note that some releases have special additional requirements outlined in <a href="http://www.elasticsearch.org/download/2012/02/21/0.19.0.RC3.html" rel="nofollow noreferrer">release notes</a>. For example, upgrade to 0.19 from 0.18 requires issuing a full flush of all the indices in the cluster.</p></li> <li><p>There is really no good way to accomplish this. Nodes are communicating using binary protocol that is not backward compatible. So, if protocol in the new version changes, old nodes and new nodes are unable to understand each other. Sometimes it's possible to mix nodes with different minor versions within the same cluster and do rolling upgrade. However, as far as I understand, there is no explicit guarantee on compatibility between nodes even within minor releases and major releases always require require full cluster restart. If downtime during full cluster restart is not an option, a <a href="http://elasticsearch-users.115913.n3.nabble.com/SImple-question-Is-elasticsearch-production-use-ready-td3430946.html#a3453676" rel="nofollow noreferrer">nice technique</a> by <a href="https://stackoverflow.com/users/819598/drtech">DrTech</a> might be a solution.</p></li> </ol>
9,032,919
Set decimal(16, 3) for a column in Code First Approach in EF4.3
<p>How can I do this : </p> <pre><code>private decimal _SnachCount; [Required] [DataType("decimal(16 ,3)")] public decimal SnachCount { get { return _SnachCount; } set { _SnachCount = value; } } private decimal _MinimumStock; [Required] [DataType("decimal(16 ,3)")] public decimal MinimumStock { get { return _MinimumStock; } set { _MinimumStock = value; } } private decimal _MaximumStock; [Required] [DataType("decimal(16 ,3)")] public decimal MaximumStock { get { return _MaximumStock; } set { _MaximumStock = value; } } </code></pre> <p>After generating the database by this part of my model , these three columns type are decimal(18,2),why? what is this code error? how can i do that ?</p>
9,033,029
5
0
null
2012-01-27 11:55:03.493 UTC
9
2020-05-21 18:32:57.933 UTC
2020-05-21 18:32:57.933 UTC
null
763,246
null
985,084
null
1
51
entity-framework|ef-code-first|sql-types
71,110
<p>The <code>DataType</code> Attribute is a Validation Attribute. You need to do that using the ModelBuilder.</p> <pre><code>public class MyContext : DbContext { public DbSet&lt;MyClass&gt; MyClass; protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;MyClass&gt;().Property(x =&gt; x.SnachCount).HasPrecision(16, 3); modelBuilder.Entity&lt;MyClass&gt;().Property(x =&gt; x.MinimumStock).HasPrecision(16, 3); modelBuilder.Entity&lt;MyClass&gt;().Property(x =&gt; x.MaximumStock).HasPrecision(16, 3); } } </code></pre>
9,053,791
Why does adb install <same-packagename-always-release> fail?
<p>I know that <code>adb install</code> will not replace an existing package if it's of a different build <em>type</em> (i.e. debug vs. release).</p> <p>Eclipse also successfully replaces the debug apks whenever I run a debug session.</p> <p>But when I attempt <code>adb install</code> for replacing an existing <em>release</em> apk with another release apk (same package name!), I get a failure message:</p> <pre><code>adb install myapp-release.apk pkg: /data/local/tmp/myapp-release.apk Failure [INSTALL_FAILED_ALREADY_EXISTS] 745 KB/s (34310 bytes in 0.044s) </code></pre> <p>Wasn't that supposed to work? What am I missing?</p>
9,053,822
1
0
null
2012-01-29 14:10:09.807 UTC
9
2012-01-29 14:14:33.757 UTC
null
null
null
null
636,571
null
1
72
android|apk|adb
31,010
<p>I suppose if the app is already installed, you need to supply the <code>-r</code> key:</p> <pre><code>adb install -r myapp-release.apk </code></pre> <p>From the <code>adb</code> help:</p> <pre><code>'-r' means reinstall the app, keeping its data </code></pre>
9,532,668
List rows after specific date
<p>I have a column in my database called "dob" of type datetime. How do I select all the rows after a specific DoB in SQL Server 2005?</p>
9,532,719
2
0
null
2012-03-02 11:40:18.277 UTC
7
2021-10-14 17:54:52.99 UTC
2016-07-15 22:33:44.623 UTC
null
684,869
null
607,846
null
1
79
sql|sql-server|sql-server-2008|sql-server-2005
262,733
<p>Simply put:</p> <pre><code>SELECT * FROM TABLE_NAME WHERE dob &gt; '1/21/2012' </code></pre> <p>Where 1/21/2012 is the date and you want all data, including that date.</p> <pre><code>SELECT * FROM TABLE_NAME WHERE dob BETWEEN '1/21/2012' AND '2/22/2012' </code></pre> <p>Use a between if you're selecting time between two dates</p>
9,146,907
git: abort commit in the middle of typing message
<p>I am in the middle of committing. I have typed up my commit message in vim. I now remembered I needed to change something. I realize that there are other options to accomplish what I want, but I want to know if there is a way to abort the commit but still save the commit message I've typed up so far.</p>
9,146,945
8
0
null
2012-02-05 04:26:03.2 UTC
26
2022-07-21 16:08:13.367 UTC
null
null
null
null
10,608
null
1
158
git
63,872
<p>Yes. Write the commit message to a different file (<code>:w /some/other/path.txt</code>). Then exit the editor without saving (<code>:q!</code>). If you previously saved the file to its original path, delete everything and write the empty file first (an empty commit message will abort the commit).</p> <p>Now, when you're ready to commit "for reals", use the message file you saved at the alternate path.</p> <p>Alternately, copy the commit message into one of vim's buffers.</p> <p>It's worth noting that you <em>really don't have to do this at all</em>: <code>commit --amend</code> lets you alter the commit after it's made, so the easy solution is to produce the commit with what you've got and then fix it before pushing. You can even just finish the commit in its broken state, <code>reset HEAD~</code> (resets you to the state your working copy was in before the commit), fix your working copy, and then <code>commit -a -c HEAD@{1}</code> to use the old commit message.</p>
9,217,185
How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?
<p>How do I use grep to search the current directory for any and all files containing the string "hello" and display only .h and .cc files?</p>
9,217,351
8
0
null
2012-02-09 19:10:40.39 UTC
39
2018-07-27 08:58:51.193 UTC
null
null
null
null
745,835
null
1
177
linux|bash|unix|grep
311,469
<pre><code>grep -r --include=*.{cc,h} "hello" . </code></pre> <p>This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this <code>.</code> (current) directory </p> <p><a href="https://stackoverflow.com/questions/221921/grep-exclude-include-syntax-do-not-grep-through-certain-files">From another stackoverflow question</a></p>
9,456,138
How can I get seconds since epoch in Javascript?
<p>On Unix, I can run <code>date '+%s'</code> to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.</p> <p>Is there a way to find out seconds since Epoch in JavaScript?</p>
9,456,144
10
0
null
2012-02-26 19:02:53.307 UTC
8
2020-07-12 04:10:57.597 UTC
null
null
null
null
284,806
null
1
177
javascript|datetime
135,350
<pre><code>var seconds = new Date() / 1000; </code></pre> <p>Or, for a less hacky version:</p> <pre><code>var d = new Date(); var seconds = d.getTime() / 1000; </code></pre> <p>Don't forget to <code>Math.floor()</code> or <code>Math.round()</code> to round to nearest whole number or you might get a very odd decimal that you don't want:</p> <pre><code>var d = new Date(); var seconds = Math.round(d.getTime() / 1000); </code></pre>
52,398,435
CocoaPods could not find compatible versions for pod "Firebase/Core” | cloud_firestore, Flutter
<p>I am having some issues in the pod, see below</p> <p>Launching lib/main.dart on iPhone X in debug mode... Running pod install... CocoaPods' output: ↳ Preparing</p> <pre><code>Analyzing dependencies Inspecting targets to integrate Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``) Fetching external sources -&gt; Fetching podspec for `Flutter` from `.symlinks/flutter/ios` -&gt; Fetching podspec for `cloud_firestore` from `.symlinks/plugins/cloud_firestore/ios` -&gt; Fetching podspec for `firebase_core` from `.symlinks/plugins/firebase_core/ios` -&gt; Fetching podspec for `shared_preferences` from `.symlinks/plugins/shared_preferences/ios` -&gt; Fetching podspec for `url_launcher` from `.symlinks/plugins/url_launcher/ios` Resolving dependencies of `Podfile` [!] CocoaPods could not find compatible versions for pod "Firebase/Core": In Podfile: cloud_firestore (from `.symlinks/plugins/cloud_firestore/ios`) was resolved to 0.0.1, which depends on Firebase/Core Specs satisfying the `Firebase/Core` dependency were found, but they required a higher minimum deployment target. CocoaPods could not find compatible versions for pod "GoogleUtilities/MethodSwizzler": In Podfile: cloud_firestore (from `.symlinks/plugins/cloud_firestore/ios`) was resolved to 0.0.1, which depends on Firebase/Core was resolved to 5.8.0, which depends on FirebaseAnalytics (= 5.1.2) was resolved to 5.1.2, which depends on GoogleUtilities/MethodSwizzler (~&gt; 5.2.0) Specs satisfying the `GoogleUtilities/MethodSwizzler (~&gt; 5.2.0)` dependency were found, but they required a higher minimum deployment target. CocoaPods could not find compatible versions for pod "gRPC-Core": In Podfile: cloud_firestore (from `.symlinks/plugins/cloud_firestore/ios`) was resolved to 0.0.1, which depends on Firebase/Firestore was resolved to 5.8.0, which depends on FirebaseFirestore (= 0.13.3) was resolved to 0.13.3, which depends on gRPC-C++ (~&gt; 0.0.3) was resolved to 0.0.3, which depends on gRPC-C++/Implementation (= 0.0.3) was resolved to 0.0.3, which depends on gRPC-Core (= 1.14.0) cloud_firestore (from `.symlinks/plugins/cloud_firestore/ios`) was resolved to 0.0.1, which depends on Firebase/Firestore was resolved to 5.8.0, which depends on FirebaseFirestore (= 0.13.3) was resolved to 0.13.3, which depends on gRPC-ProtoRPC (~&gt; 1.0) was resolved to 1.14.1, which depends on gRPC-ProtoRPC/Main (= 1.14.1) was resolved to 1.14.1, which depends on gRPC (= 1.14.1) was resolved to 1.14.1, which depends on gRPC/Main (= 1.14.1) was resolved to 1.14.1, which depends on gRPC-Core (= 1.14.1) /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:328:in `raise_error_unless_state' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:308:in `tap' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:308:in `unwind_for_conflict' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:684:in `attempt_to_activate' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:254:in `process_topmost_state' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolution.rb:182:in `resolve' /Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.5/lib/molinillo/resolver.rb:43:in `resolve' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/resolver.rb:123:in `resolve' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer/analyzer.rb:781:in `block in resolve_dependencies' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/user_interface.rb:64:in `section' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer/analyzer.rb:779:in `resolve_dependencies' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer/analyzer.rb:88:in `analyze' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:243:in `analyze' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:154:in `block in resolve_dependencies' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/user_interface.rb:64:in `section' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:153:in `resolve_dependencies' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:116:in `install!' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/command/install.rb:41:in `run' /Library/Ruby/Gems/2.3.0/gems/claide-1.0.2/lib/claide/command.rb:334:in `run' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/lib/cocoapods/command.rb:52:in `run' /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.5.3/bin/pod:55:in `&lt;top (required)&gt;' /usr/local/bin/pod:22:in `load' /usr/local/bin/pod:22:in `&lt;main&gt;' </code></pre> <p>Error output from CocoaPods: ↳ [33mWARNING: CocoaPods requires your terminal to be using UTF-8 encoding. Consider adding the following to ~/.profile:</p> <pre><code> export LANG=en_US.UTF-8 [0m [!] Automatically assigning platform `ios` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`. </code></pre> <p>Error running pod install Error launching application on iPhone X.</p>
65,808,257
20
2
null
2018-09-19 05:04:51.433 UTC
20
2022-09-08 16:26:00.883 UTC
2020-11-27 05:14:44.84 UTC
user10563627
null
null
1,127,516
null
1
87
ios|firebase|flutter|cocoapods|podfile
86,327
<p>My setup: VS Code, Flutter</p> <p>If you don't have <code>Podfile.lock</code> file and <code>pod update</code> doesn't help, try this:</p> <ol> <li>Go to <code>ios/Pods/Local Podspecs</code> directory in your project</li> <li>Check every <code>json</code> file to find highest required ios version. Mine was <code>&quot;ios&quot;: &quot;10.0&quot;</code> in some of them</li> <li>Go back to <code>ios/</code> directory</li> <li>Open <code>Podfile</code> file</li> <li>Uncomment <code># platform :ios, '9.0'</code> and replace <code>9.0</code> with version from 2. step, for example <code>10.0</code>. <ul> <li><code># platform :ios, '9.0'</code> &gt; <code>platform :ios, '10.0'</code></li> </ul> </li> <li>Run <code>pod install</code> and the error should be gone</li> </ol>
30,069,643
Remote monitoring with visualvm and JMX
<p>I would like to monitor a remotely running java (spring boot) application with jvisualvm (or jconsole). When running locally, I can see the managed beans in both jvisualvm and jconsole. When running remotely I cannot connect. I tried it with several different java processes (e.g. with spring xd). Looking for answers here on SO and on Google did not help. </p> <p>These are my JAVA_OPTS (on the remote host):</p> <pre><code>$ echo $JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=192.168.59.99 </code></pre> <p>Then I simply start the program as follows (this is for spring xd, but I experience the same problem with other java programs). </p> <pre><code>$ bin/xd/xd-singlenode </code></pre> <p>The server process seems to pick up the options:</p> <pre><code>$ ps -ef | grep single vagrant 22938 19917 99 06:38 pts/2 00:00:03 /usr/lib/jvm/java-8- oracle/jre/bin/java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=192.168.59.99 -Dspring.application.name=admin -Dlogging.config=file:/home/vagrant/spring-xd-1.1.0.RELEASE/xd/config///xd-singlenode-logger.properties -Dxd.home=/home/vagrant/spring-xd-1.1.0.RELEASE/xd -Dspring.config.location=file:/home/vagrant/spring-xd-1.1.0.RELEASE/xd/config// -Dxd.config.home=file:/home/vagrant/spring-xd-1.1.0.RELEASE/xd/config// -Dspring.config.name=servers,application -Dxd.module.config.location=file:/home/vagrant/spring-xd-1.1.0.RELEASE/xd/config//modules/ -Dxd.module.config.name=modules -classpath (...) </code></pre> <p>The java version on the remote host (ubuntu linux vm) is:</p> <pre><code>$ java -version java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode) </code></pre> <p>The java version on the local machine (Mac OS) is slightly different: </p> <pre><code>$ java -version java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b25) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode) </code></pre> <p>In jvisualvm I add the remote connection as follows (tried both with ssl connection and without): </p> <p><img src="https://i.stack.imgur.com/c1Z3n.png" alt="enter image description here"></p> <p>This is the error message jvisualvm gives me:</p> <p><img src="https://i.stack.imgur.com/AxLUl.png" alt="Error Message given by jvisualvm"></p> <p>I can connect from the local host to the remote host with the command <code>telnet 192.168.59.99:9010</code>, when the remote process is running -- so this does not seem to be a firewall problem.</p> <p>Any help is highly appreciated. </p>
30,070,070
3
3
null
2015-05-06 06:58:02.52 UTC
16
2022-07-28 10:58:44.483 UTC
2015-05-06 07:27:56.163 UTC
null
2,069,922
null
2,069,922
null
1
27
java|spring-boot|monitoring|jmx
63,163
<p>Please use the following JVM options : </p> <pre><code>-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=192.168.59.99 </code></pre> <p>In the Jconsole use the following to connect: </p> <pre><code>service:jmx:rmi:///jndi/rmi://192.168.59.99:9010/jmxrmi </code></pre>
72,449,482
f-string representation different than str()
<p>I had always thought that f-strings invoked the <code>__str__</code> method. That is, <code>f'{x}'</code> was always the same as <code>str(x)</code>. However, with this class</p> <pre class="lang-py prettyprint-override"><code>class Thing(enum.IntEnum): A = 0 </code></pre> <p><code>f'{Thing.A}'</code> is <code>'0'</code> while <code>str(Thing.A)</code> is <code>'Thing.A'</code>. This example doesn't work if I use <code>enum.Enum</code> as the base class.</p> <p>What functionality do f-strings invoke?</p>
72,449,614
2
1
null
2022-05-31 14:17:57.613 UTC
7
2022-08-11 21:59:16.257 UTC
2022-08-11 21:59:16.257 UTC
null
8,075,540
null
8,075,540
null
1
67
python|enums|f-string
6,039
<p>From <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">&quot;Formatted string literals&quot; in the Python reference</a>: f-strings are invoke the &quot;<code>format</code> protocol&quot;, same as the <code>format</code> built-in function. It means that the <a href="https://docs.python.org/3/reference/datamodel.html#object.__format__" rel="noreferrer"><code>__format__</code></a> magic method is called instead of <code>__str__</code>.</p> <pre class="lang-py prettyprint-override"><code>class Foo: def __repr__(self): return &quot;Foo()&quot; def __str__(self): return &quot;A wild Foo&quot; def __format__(self, format_spec): if not format_spec: return &quot;A formatted Foo&quot; return f&quot;A formatted Foo, but also {format_spec}!&quot; &gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; repr(foo) 'Foo()' &gt;&gt;&gt; str(foo) 'A wild Foo' &gt;&gt;&gt; format(foo) 'A formatted Foo' &gt;&gt;&gt; f&quot;{foo}&quot; 'A formatted Foo' &gt;&gt;&gt; format(foo, &quot;Bar&quot;) 'A formatted Foo, but also Bar!' &gt;&gt;&gt; f&quot;{foo:Bar}&quot; 'A formatted Foo, but also Bar!' </code></pre> <p>If you don't want <code>__format__</code> to be called, you can specify <code>!s</code> (for <code>str</code>), <code>!r</code> (for <code>repr</code>) or <code>!a</code> (for <a href="https://docs.python.org/3/library/functions.html#ascii" rel="noreferrer"><code>ascii</code></a>) after the expression:</p> <pre><code>&gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; f&quot;{foo}&quot; 'A formatted Foo' &gt;&gt;&gt; f&quot;{foo!s}&quot; 'A wild Foo' &gt;&gt;&gt; f&quot;{foo!r}&quot; 'Foo()' </code></pre> <p>This is occasionally useful with strings:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; key = 'something\n nasty!' &gt;&gt;&gt; error_message = f&quot;Key not found: {key!r}&quot; &gt;&gt;&gt; error_message &quot;Key not found: 'something\\n nasty!'&quot; </code></pre>
10,298,483
Spring and hibernate: No Session found for current thread
<p>im gettting the following error</p> <pre><code>org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1024) at com.fexco.shoptaxfreemobile.service.ProfileService.registerVisitor(ProfileService.java:57) at com.fexco.shoptaxfreemobile.controller.ProfileController.registerVisitor(ProfileController.java:91) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:668) at javax.servlet.http.HttpServlet.service(HttpServlet.java:770) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.fexco.shoptaxfreemobile.jsonp.JsonpCallbackFilter.doFilter(JsonpCallbackFilter.java:33) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) </code></pre> <p>Service class</p> <pre><code>@Service public class ProfileService { @Resource(name = "mySessionFactory") private SessionFactory sessionFactory; @Autowired private ProfileDao profileDao; private class CountrySorter implements Comparator&lt;Country&gt; { @Override public int compare(Country country1, Country country2) { if ( country1.getId().compareTo(new Long (3)) &lt; 0){ return country1.getId().compareTo(country2.getId()); } return country1.getName().compareToIgnoreCase(country2.getName()); } } public List&lt;Country&gt; getCountries() { List&lt;VisitorCountry&gt; visitorCountries = profileDao.getAllCountries(); List&lt;Country&gt; countries = new ArrayList&lt;Country&gt;(); for ( VisitorCountry country : visitorCountries){ countries.add(country.getCountry()); } Comparator&lt;Country&gt; comparator = new CountrySorter(); Collections.sort(countries, comparator); return countries; } public RegisterResponse registerVisitor(JsonVisitor visitorDetails){ Visitor storedVisitor = (Visitor) sessionFactory.getCurrentSession().get(Visitor.class, visitorDetails.getTfscNumber(), LockMode.NONE); if ( storedVisitor == null){ storedVisitor = new Visitor(visitorDetails); }else{ storedVisitor.setVisitorDetails(visitorDetails); } try{ sessionFactory.getCurrentSession().saveOrUpdate(storedVisitor); }catch(Exception ex){ return new RegisterResponse(false, "Failed To Register Card. Please Try Again Later.", visitorDetails); } return new RegisterResponse(true, "", visitorDetails); } } </code></pre> <p>bit of DAO class</p> <pre><code>@Service @Transactional public class ProfileDao { @Resource(name = "mySessionFactory") private SessionFactory sessionFactory; public List getAllCountries(){ List&lt;VisitorCountry&gt; visitorCountries = sessionFactory.getCurrentSession() .getNamedQuery("GET_ALL_COUNTRIES").list(); return visitorCountries; } public List&lt;Retailer&gt; getRetailerByRetailerNumber(String retailerNo) { List&lt;Retailer&gt; retailerByRetailerNumber = sessionFactory.getCurrentSession() .getNamedQuery("FindRetailerByRetailerNo").setString("retailerNo", retailerNo).list(); return retailerByRetailerNumber; } </code></pre> <p>and i have this in my application-context.xml</p> <pre><code>&lt;tx:annotation-driven transaction-manager="transactionManager"/&gt; &lt;bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="myDataSource" /&gt; &lt;property name="configLocation" value="classpath:hibernate.cfg.xml" /&gt; &lt;property name="hibernateProperties"&gt; &lt;value&gt; &lt;![CDATA[ hibernate.show_sql=true hibernate.format_sql=true hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider ]]&gt; &lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>can anyone spot why i am getting the following error?</p>
10,298,645
6
1
null
2012-04-24 13:08:08.587 UTC
7
2017-01-02 20:24:45.567 UTC
2016-07-01 18:54:03.96 UTC
null
179,850
null
670,994
null
1
25
spring|hibernate|sessionfactory
67,177
<p>You annotated your Dao class with @Transactional, but not your service class. The line:</p> <pre><code>Visitor storedVisitor = (Visitor) sessionFactory.getCurrentSession().get(Visitor.class, visitorDetails.getTfscNumber(), LockMode.NONE); </code></pre> <p>requires you to be in a transaction.</p> <p>You can fix this by adding the @Transactional annotation to your ProfileService class, or just the registerVisitor() method.</p>
10,828,294
C and C++ : Partial initialization of automatic structure
<p>For example, if <code>somestruct</code> has three integer members, I had always thought that it was OK to do this in C (or C++) function:</p> <pre><code>somestruct s = {123,}; </code></pre> <p>The first member would be initialized to 123 and the last two would be initialized to 0. I often do the same thing with automatic arrays, writing <code>int arr[100] = {0,};</code> so that all integers in an array are initialized to zero. </p> <p><br> Recently I read in the <a href="http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Initializing-Structure-Members">GNU C Reference Manual</a> that:</p> <blockquote> <p>If you do not initialize a structure variable, the effect depends on whether it is has static storage (see Storage Class Specifiers) or not. If it is, members with integral types are initialized with 0 and pointer members are initialized to NULL; otherwise, the value of the structure's members is indeterminate.</p> </blockquote> <p><br> Can someone please tell me what the C and C++ standards say regarding partial automatic structure and automatic array initialization? I do the above code in Visual Studio without a problem but I want to be compatible with gcc/g++, and maybe other compilers as well. Thanks</p>
10,828,333
3
1
null
2012-05-31 06:10:44.227 UTC
50
2017-11-04 08:13:30.727 UTC
null
null
null
null
4,704,515
null
1
79
c++|c
65,890
<p>The linked gcc documentation does not talk of <strong>Partial Initialization</strong> it just talks of <strong>(Complete)Initialization</strong> or <strong>No Initialization</strong>. </p> <blockquote> <p><strong>What is partial Initialization?</strong> </p> </blockquote> <p>The standards do not define Partial initialization of objects, either there is Complete initialization or No-initialization. Partial Initialization is a non-standard terminology which commonly refers a situation where you provide some initializers but not all i.e: Fewer initializers than the size of the array or the number of structure elements being initialized. </p> <p>Example: </p> <pre><code>int array[10] = {1,2}; //Case 1:Partial Initialization </code></pre> <blockquote> <p><strong>What is (Complete)Initialization or No Initialization?</strong> </p> </blockquote> <p>Initialization means providing some initial value to the variable being created at the same time when it is being created. ie: in the same code statement.</p> <p>Example: </p> <pre><code>int array[10] = {0,1,2,3,4,5,6,7,8,9}; //Case 2:Complete Initialization int array[10]; //Case 3:No Initialization </code></pre> <p>The quoted paragraph describes the behavior for <code>Case 3</code>.</p> <p>The rules regarding Partial Initialization(<code>Case 1</code>) are well defined by the standard and these rules do not depend on the storage type of the variable being initialized.<br> AFAIK, All mainstream compilers have 100% compliance to these rules.</p> <hr> <blockquote> <p><strong>Can someone please tell me what the C and C++ standards say regarding partial automatic structure and automatic array initialization?</strong></p> </blockquote> <p>The C and C++ standards guarantee that even if an integer array is located on automatic storage and if there are fewer initializers in a brace-enclosed list then the uninitialized elements <strong>must</strong> be initialized to <code>0</code>.</p> <p><strong>C99 Standard 6.7.8.21</strong> </p> <blockquote> <p>If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.</p> </blockquote> <hr> <p>In C++ the rules are stated with a little difference. </p> <p><strong>C++03 Standard 8.5.1 Aggregates</strong><br> <strong>Para 7:</strong> </p> <blockquote> <p>If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be <strong>value-initialized</strong> (8.5). [Example:</p> <pre><code> struct S { int a; char* b; int c; }; S ss = { 1, "asdf" }; </code></pre> <p>initializes <code>ss.a</code> with <code>1</code>, <code>ss.b</code> with <code>"asdf"</code>, and <code>ss.c</code> with the value of an expression of the form <code>int()</code>, that is,<code>0</code>. ]</p> </blockquote> <p>While Value Initialization is defined in,<br> <strong>C++03 8.5 Initializers</strong><br> <strong>Para 5:</strong> </p> <blockquote> <p>To <strong>value-initialize</strong> an object of type T means:<br> — if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);<br> — if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;<br> — if T is an array type, then each element is value-initialized;<br> — otherwise, the object is zero-initialized </p> </blockquote>
10,456,174
OAuth: how to test with local URLs?
<p>I am trying to test <a href="https://en.wikipedia.org/wiki/OAuth" rel="noreferrer">OAuth</a> buttons, but they all (Facebook, Twitter, LinkedIn) come back with errors that seem to signal that I can not test or use them from a <em>local</em> URL.</p> <p>How do people usually work in development with OAuth stuff if they all seem to require a <em>non-dev</em> and <em>non-local</em> connections environments?</p>
10,459,981
12
1
null
2012-05-04 21:10:16.37 UTC
44
2022-02-07 17:51:43.483 UTC
2020-03-09 15:42:41.48 UTC
null
814,702
null
1,341,975
null
1
214
oauth|localhost
156,169
<p><strong>Update October 2016</strong>: Easiest now: use <a href="http://lvh.me" rel="noreferrer">lvh.me</a> which always points to <code>127.0.0.1</code>, but make sure to verify that this is still true every time you need to invoke it (because domains can expire or get taken over, and DNS poisoning is always a concern)</p> <p><strong>Previous Answer</strong>:</p> <p>Since the callback request is issued by the browser, as a HTTP redirect response, you can set up your .hosts file or equivalent to point a domain that is not <code>localhost</code> to 127.0.0.1.</p> <p>Say for example you register the following callback with Twitter: <code>http://www.publicdomain.com/callback/</code>. Make sure that <code>www.publicdomain.com</code> points to 127.0.0.1 in your hosts file, AND that twitter can do a successful DNS lookup on <a href="http://www.publicdomain.com" rel="noreferrer">www.publicdomain.com</a>, i.e the domain needs to exist and the specific callback should probably return a 200 status message if requested.</p> <p><strong>EDIT</strong>:</p> <p>I just read the following article: <a href="https://web.archive.org/web/20171219093121/www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine/" rel="noreferrer">http://www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine</a>, which was linked to from this question: <a href="https://stackoverflow.com/questions/800827/twitter-oauth-callbackurl-localhost-development">Twitter oAuth callbackUrl - localhost development</a>.</p> <p>To quote the article:</p> <blockquote> <p>You can use bit.ly, a URL shortening service. Just shorten the [localhost URL such as http//localhost:8080/twitter_callback] and register the shortened URL as the callback in your Twitter app.</p> </blockquote> <p>This should be easier than fiddling around in the .hosts file.</p> <p>Note that now (Aug '14) bit.ly is not allowing link forwarding to localhost; however Google link shortener works.</p> <p>PS edit: (Nov '18): Google link shortener stopped giving support for localhost or 127.0.0.1.</p>
22,841,764
Best practice for Django project working directory structure
<p>I know there is actually no single right way. However I've found that it's hard to create a directory structure that works well and remain clean for every developer and administrator. There is some standard structure in most projects on github. But it does not show a way to organize another files and all projects on pc.</p> <p>What is the most convenient way to organize all these directories on development machine? How do you name them, and how do you connect and deploy this to server?</p> <ul> <li>projects (all projects that your are working on)</li> <li>source files (the application itself)</li> <li>working copy of repository (I use git)</li> <li>virtual environment (I prefer to place this near the project)</li> <li>static root (for compiled static files)</li> <li>media root (for uploaded media files)</li> <li>README</li> <li>LICENSE</li> <li>documents</li> <li>sketches</li> <li>examples (an example project that uses the application provided by this project)</li> <li>database (in case sqlite is used)</li> <li>anything else that you usually need for successful work on project</li> </ul> <p>The problems that I want to solve:</p> <ul> <li>Good names of directories so that their purpose is clear.</li> <li>Keeping all project files (including virtualenv) in one place, so I can easily copy, move, archive, remove whole project or estimate disk space usage.</li> <li>Creating multiple copies of some selected file sets such as entire application, repository or virtualenv, while keeping single copy of another files that I don't want to clone.</li> <li>Deploying right set of files to the server simply by rsyncing selected one dir.</li> </ul>
23,469,321
6
0
null
2014-04-03 15:09:58.91 UTC
229
2020-07-30 15:43:10.36 UTC
2017-03-13 17:07:22.093 UTC
null
3,274,259
null
969,451
null
1
245
django|directory-structure|organization|project-structure
182,010
<p>There're two kind of Django &quot;projects&quot; that I have in my <code>~/projects/</code> directory, both have a bit different structure.:</p> <ul> <li>Stand-alone websites</li> <li>Pluggable applications</li> </ul> <h1>Stand-alone website</h1> <p>Mostly private projects, but doesn't have to be. It usually looks like this:</p> <pre><code>~/projects/project_name/ docs/ # documentation scripts/ manage.py # installed to PATH via setup.py project_name/ # project dir (the one which django-admin.py creates) apps/ # project-specific applications accounts/ # most frequent app, with custom user model __init__.py ... settings/ # settings for different environments, see below __init__.py production.py development.py ... __init__.py # contains project version urls.py wsgi.py static/ # site-specific static files templates/ # site-specific templates tests/ # site-specific tests (mostly in-browser ones) tmp/ # excluded from git setup.py requirements.txt requirements_dev.txt pytest.ini ... </code></pre> <h3>Settings</h3> <p>The main settings are production ones. Other files (eg. <code>staging.py</code>, <code>development.py</code>) simply import everything from <code>production.py</code> and override only necessary variables.</p> <p>For each environment, there are separate settings files, eg. production, development. I some projects I have also testing (for test runner), staging (as a check before final deploy) and heroku (for deploying to heroku) settings.</p> <h3>Requirements</h3> <p>I rather specify requirements in setup.py directly. Only those required for development/test environment I have in <code>requirements_dev.txt</code>.</p> <p>Some services (eg. heroku) requires to have <code>requirements.txt</code> in root directory.</p> <h3><code>setup.py</code></h3> <p>Useful when deploying project using <code>setuptools</code>. It adds <code>manage.py</code> to <code>PATH</code>, so I can run <code>manage.py</code> directly (anywhere).</p> <h3>Project-specific apps</h3> <p>I used to put these apps into <code>project_name/apps/</code> directory and import them using relative imports.</p> <h3>Templates/static/locale/tests files</h3> <p>I put these templates and static files into global templates/static directory, not inside each app. These files are usually edited by people, who doesn't care about project code structure or python at all. If you are full-stack developer working alone or in a small team, you can create per-app templates/static directory. It's really just a matter of taste.</p> <p>The same applies for locale, although sometimes it's convenient to create separate locale directory.</p> <p>Tests are usually better to place inside each app, but usually there is many integration/functional tests which tests more apps working together, so global tests directory does make sense.</p> <h3>Tmp directory</h3> <p>There is temporary directory in project root, excluded from VCS. It's used to store media/static files and sqlite database during development. Everything in tmp could be deleted anytime without any problems.</p> <h3>Virtualenv</h3> <p>I prefer <code>virtualenvwrapper</code> and place all venvs into <code>~/.venvs</code> directory, but you could place it inside <code>tmp/</code> to keep it together.</p> <h3>Project template</h3> <p>I've created project template for this setup, <a href="https://github.com/elvard/django-start-template/" rel="noreferrer">django-start-template</a></p> <h3>Deployment</h3> <p>Deployment of this project is following:</p> <pre><code>source $VENV/bin/activate export DJANGO_SETTINGS_MODULE=project_name.settings.production git pull pip install -r requirements.txt # Update database, static files, locales manage.py syncdb --noinput manage.py migrate manage.py collectstatic --noinput manage.py makemessages -a manage.py compilemessages # restart wsgi touch project_name/wsgi.py </code></pre> <p>You can use <code>rsync</code> instead of <code>git</code>, but still you need to run batch of commands to update your environment.</p> <p>Recently, I made <a href="https://github.com/elvard/django-deploy" rel="noreferrer"><code>django-deploy</code></a> app, which allows me to run single management command to update environment, but I've used it for one project only and I'm still experimenting with it.</p> <h3>Sketches and drafts</h3> <p>Draft of templates I place inside global <code>templates/</code> directory. I guess one can create folder <code>sketches/</code> in project root, but haven't used it yet.</p> <h1>Pluggable application</h1> <p>These apps are usually prepared to publish as open-source. I've taken example below from <a href="https://github.com/elvard/django-forme" rel="noreferrer">django-forme</a></p> <pre><code>~/projects/django-app/ docs/ app/ tests/ example_project/ LICENCE MANIFEST.in README.md setup.py pytest.ini tox.ini .travis.yml ... </code></pre> <p>Name of directories is clear (I hope). I put test files outside app directory, but it really doesn't matter. It is important to provide <code>README</code> and <code>setup.py</code>, so package is easily installed through <code>pip</code>.</p>
31,840,176
Changing language on the fly in swift
<p>Now I know that apple does not recommend this.</p> <blockquote> <p>In general, you should not change the iOS system language (via use of the AppleLanguages pref key) from within your application. This goes against the basic iOS user model for switching languages in the Settings app, and also uses a preference key that is not documented, meaning that at some point in the future, the key name could change, which would break your application.</p> </blockquote> <p>However, this is an application that changing the language on the fly makes sense, just trust me on that. I also know this question was asked here: <a href="https://stackoverflow.com/questions/5109245/changing-language-on-the-fly-in-running-ios-iphone-app">Changing language on the fly, in running iOS, programmatically</a>. This however is getting old and I was wondering if there are any newer, better, or easier ways to do this. Currently in my app, I have a language choosing screen. Clicking on of the buttons in this view calls the following function with the language the button is associated with: </p> <pre><code> func changeLang(language: String) { if language != (currentLang as! String?)! { func handleCancel(alertView: UIAlertAction!) { } var alert = UIAlertController(title: NSLocalizedString("language", comment: "Language"), message: NSLocalizedString("languageWarning", comment: "Warn User of Language Change Different Than Defaults"), preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:handleCancel)) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction) in NSUserDefaults.standardUserDefaults().setObject([language], forKey: "AppleLanguages") NSUserDefaults.standardUserDefaults().synchronize() println(self.currentLang) let alert = UIAlertView() alert.title = NSLocalizedString("language", comment: "Sign In Failed") alert.message = NSLocalizedString("languageChangeNotification", comment: "Notify of language change") alert.addButtonWithTitle(NSLocalizedString("ok", comment: "Okay")) alert.show() self.performSegueWithIdentifier("welcome", sender: AnyObject?()) })) self.presentViewController(alert, animated: true, completion: { }) } else { self.performSegueWithIdentifier("welcome", sender: AnyObject?()) } } </code></pre> <p>Example:</p> <pre><code>@IBAction func english(sender: UIButton) { changeLang("en") } </code></pre> <p>If the user picks a language different than their own, they get a confirmation alert, and then are requested to restart there device. This is what I want to change. It appears that this section of NSUSerDefaults is not synchronized until the app restarts. Evidence:</p> <pre><code>let currentLang: AnyObject? = NSLocale.preferredLanguages()[0] println(currentLang) // Prints english changeLang("zh-Hans") println(currentLang) // Prints english still until restart </code></pre> <p>The current internationalization system apple has is great, and I plan on using it. However, how can I change the language on the fly, maybe by forcing an update on the NSUSerDefaults?</p> <p><strong>Edit:</strong> I recommend using this <a href="https://github.com/marmelroy/Localize-Swift" rel="noreferrer">library</a> to do this now. Best of luck!</p>
31,887,430
3
1
null
2015-08-05 18:31:06.98 UTC
10
2019-12-26 05:13:06.843 UTC
2017-05-23 12:18:10.873 UTC
null
-1
null
5,030,164
null
1
17
ios|iphone|swift|internationalization|nsuserdefaults
31,128
<p>Basically you have to teach you bundle how to switch languages by loading different bundle files.</p> <p>I translated my <a href="https://stackoverflow.com/a/29874319/106435">Objective-C code</a> to Swift — with leaving the NSBundle category untouched. </p> <p><img src="https://i.stack.imgur.com/4QheI.gif" alt="enter image description here"> </p> <p>The result is a view controller class that offers a <code>languageDidChange()</code> method for overriding. </p> <hr> <p>NSBundle+Language.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface NSBundle (Language) +(void)setLanguage:(NSString*)language; @end </code></pre> <hr> <p>NSBundle+Language.m</p> <pre><code>#import "NSBundle+Language.h" #import &lt;objc/runtime.h&gt; static const char associatedLanguageBundle=0; @interface PrivateBundle : NSBundle @end @implementation PrivateBundle -(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName { NSBundle* bundle=objc_getAssociatedObject(self, &amp;associatedLanguageBundle); return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName]; } @end @implementation NSBundle (Language) +(void)setLanguage:(NSString*)language { static dispatch_once_t onceToken; dispatch_once(&amp;onceToken, ^{ object_setClass([NSBundle mainBundle],[PrivateBundle class]); }); objc_setAssociatedObject([NSBundle mainBundle], &amp;associatedLanguageBundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end </code></pre> <hr> <p>AppDelegate.swift</p> <pre><code>import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -&gt; Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector: "languageWillChange:", name: "LANGUAGE_WILL_CHANGE", object: nil) let targetLang = NSUserDefaults.standardUserDefaults().objectForKey("selectedLanguage") as? String NSBundle.setLanguage((targetLang != nil) ? targetLang : "en") return true } func languageWillChange(notification:NSNotification){ let targetLang = notification.object as! String NSUserDefaults.standardUserDefaults().setObject(targetLang, forKey: "selectedLanguage") NSBundle.setLanguage(targetLang) NSNotificationCenter.defaultCenter().postNotificationName("LANGUAGE_DID_CHANGE", object: targetLang) } } </code></pre> <hr> <p>BaseViewController.swift</p> <pre><code>import UIKit class BaseViewController: UIViewController { @IBOutlet weak var englishButton: UIButton! @IBOutlet weak var spanishButton: UIButton! deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "languageDidChangeNotification:", name: "LANGUAGE_DID_CHANGE", object: nil) languageDidChange() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func switchLanguage(sender: UIButton) { var localeString:String? switch sender { case englishButton: localeString = "en" case spanishButton: localeString = "es" default: localeString = nil } if localeString != nil { NSNotificationCenter.defaultCenter().postNotificationName("LANGUAGE_WILL_CHANGE", object: localeString) } } func languageDidChangeNotification(notification:NSNotification){ languageDidChange() } func languageDidChange(){ } } </code></pre> <hr> <p>ViewController.swift</p> <pre><code>import UIKit class ViewController: BaseViewController { @IBOutlet weak var helloLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func languageDidChange() { super.languageDidChange() self.helloLabel.text = NSLocalizedString("Hello", comment: "") } } </code></pre> <hr> <p>instead of using subclasses of BaseViewController, your viewcontrollers could also post "LANGUAGE_WILL_CHANGE" and listen for "LANGUAGE_DID_CHANGE" </p> <p>I pushed the complete project here: <a href="https://github.com/vikingosegundo/ImmediateLanguageSwitchSwift" rel="noreferrer">ImmediateLanguageSwitchSwift</a></p>
31,671,244
How to dump a postgres db excluding one specific table?
<p>I'd like to use <code>pg_dump</code> to backup <code>postgres</code> database content. I only want to ignore one specific table containing cached data of several hundred GB.</p> <p>How could I achieve this with pg_dump?</p>
31,671,440
2
4
null
2015-07-28 08:36:30.67 UTC
2
2022-04-22 11:38:45.187 UTC
null
null
null
null
1,194,415
null
1
49
postgresql
26,126
<p>According to <a href="http://www.postgresql.org/docs/current/static/app-pgdump.html" rel="noreferrer">the docs</a>, there is an option to <code>--exclude-table</code> which excludes tables from the dump by matching on a pattern (i.e. it allows wildcards):</p> <blockquote> <p>-T table --exclude-table=table Do not dump any tables matching the table pattern. The pattern is interpreted according to the same rules as for -t. -T can be given more than once to exclude tables matching any of several patterns.</p> <p>When both -t and -T are given, the behavior is to dump just the tables that match at least one -t switch but no -T switches. If -T appears without -t, then tables matching -T are excluded from what is otherwise a normal dump.</p> </blockquote> <p>There are a few examples <a href="http://www.postgresql.org/docs/current/static/app-pgdump.html#PG-DUMP-EXAMPLES" rel="noreferrer">here</a>.</p>
19,162,874
Swapping child views in a container view
<p>Let <code>ContainerView</code> be the parent container view with two child content views: <code>NavigationView</code> and <code>ContentView</code>.</p> <p><img src="https://i.stack.imgur.com/AUmRV.png" alt="Example of View Layout"></p> <p>I would like to be able to swap out the controller of <code>ContentView</code> with another view. For example, swapping a home page controller with a news page controller. Currently, the only way I can think to do this is by using a delegate to tell the <code>ContainerView</code> that I want to switch views. This seems like a sloppy way to do this because the <code>ContainerViewController</code> would end up having a bunch of special delegates for all of the subviews.</p> <p>This also needs to communicate with the <code>NavigationView</code> which has information about which view is currently in the <code>ContentView</code>. For example: if the user is on the news page, the navigation bar within the navigation view will show that the news button is currently selected.</p> <p><strong>Question A:</strong> Is there a way to swap the controller in <code>ContentView</code> without a delegate method calling the <code>ContainerView</code> itself? I would like to do this programmatically (no storyboard).</p> <p><strong>Question B:</strong> How can I swap controllers in <code>ContentView</code> from the <code>NavigationView</code> without a delegate call? I would like to do this programmatically (no storyboard).</p>
19,163,585
3
1
null
2013-10-03 15:15:48.283 UTC
15
2016-10-17 19:30:56.383 UTC
2016-10-17 19:30:56.383 UTC
null
2,012,219
null
1,840,086
null
1
25
ios|objective-c|animation|transitions|uicontainerview
27,715
<p>When you have child views that have their own view controllers, you should be following the custom container controller pattern. See <a href="https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html#//apple_ref/doc/uid/TP40007457-CH11-SW1" rel="noreferrer">Creating Custom Container View Controllers</a> for more information.</p> <p>Assuming you've followed the custom container pattern, when you want to change the child view controller (and its associated view) for the "content view", you would do that programmatically with something like:</p> <pre><code>UIViewController *newController = ... // instantiate new controller however you want UIViewController *oldController = ... // grab the existing controller for the current "content view"; perhaps you maintain this in your own ivar; perhaps you just look this up in self.childViewControllers newController.view.frame = oldController.view.frame; [oldController willMoveToParentViewController:nil]; [self addChildViewController:newController]; // incidentally, this does the `willMoveToParentViewController` for the new controller for you [self transitionFromViewController:oldController toViewController:newController duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ // no further animations required } completion:^(BOOL finished) { [oldController removeFromParentViewController]; // incidentally, this does the `didMoveToParentViewController` for the old controller for you [newController didMoveToParentViewController:self]; }]; </code></pre> <p>When you do it this way, there's no need for any delegate-protocol interface with the content view's controller (other than what iOS already provides with the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/doc/uid/TP40006926-CH3-SW86" rel="noreferrer">Managing Child View Controllers in a Custom Container</a> methods).</p> <hr> <p>By the way, this assumes that the initial child controller associated with that content view was added like so:</p> <pre><code>UIViewController *childController = ... // instantiate the content view's controller any way you want [self addChildViewController:childController]; childController.view.frame = ... // set the frame any way you want [self.view addSubview:childController.view]; [childController didMoveToParentViewController:self]; </code></pre> <hr> <p>If you want a child controller to tell the parent to change the controller associated with the content view, you would:</p> <ol> <li><p>Define a protocol for this:</p> <pre><code>@protocol ContainerParent &lt;NSObject&gt; - (void)changeContentTo:(UIViewController *)controller; @end </code></pre></li> <li><p>Define the parent controller to conform to this protocol, e.g.:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "ContainerParent.h" @interface ViewController : UIViewController &lt;ContainerParent&gt; @end </code></pre></li> <li><p>Implement the <code>changeContentTo</code> method in the parent controller (much as outlined above):</p> <pre><code>- (void)changeContentTo:(UIViewController *)controller { UIViewController *newController = controller; UIViewController *oldController = ... // grab reference of current child from `self.childViewControllers or from some property where you stored it newController.view.frame = oldController.view.frame; [oldController willMoveToParentViewController:nil]; [self addChildViewController:newController]; [self transitionFromViewController:oldController toViewController:newController duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ // no further animations required } completion:^(BOOL finished) { [oldController removeFromParentViewController]; [newController didMoveToParentViewController:self]; }]; } </code></pre></li> <li><p>And the child controllers can now use this protocol in reference to the <code>self.parentViewController</code> property that iOS provides for you:</p> <pre><code>- (IBAction)didTouchUpInsideButton:(id)sender { id &lt;ContainerParent&gt; parentViewController = (id)self.parentViewController; NSAssert([parentViewController respondsToSelector:@selector(changeContentTo:)], @"Parent must conform to ContainerParent protocol"); UIViewController *newChild = ... // instantiate the new child controller any way you want [parentViewController changeContentTo:newChild]; } </code></pre></li> </ol>
3,859,489
android: running a background task using AlarmManager
<p>I am writing an app which needs to periodically check the server for new messages and notify the user. I have seen some examples using AlarmManager to hit a BroadcastReciever which seems like the right thing to do, but i cant seem to get it to work.</p> <p>Can anyone show me a step by step tutorial for this sort of thing (repeating alarm which triggers some kind of background code that fires a Notification)?</p> <p>TIA</p>
3,860,059
1
3
null
2010-10-04 22:02:43.917 UTC
19
2018-01-29 21:58:35.803 UTC
null
null
null
null
339,428
null
1
11
android|notifications|broadcastreceiver|alarmmanager
15,896
<p>Here is one complete example: <a href="http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/" rel="nofollow noreferrer">http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/</a></p> <p>The pattern this example uses, and one that I've found that seems to work well, is to use a boot receiver to setup the <em>AlarmManager</em> (and of course also check to start the polling from your main <em>Activity</em> too, for the case when your app is installed and the system is not booted) and have the <em>AlarmManager</em> send an <em>Intent</em> for another receiver: <a href="http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealBootReceiver.java" rel="nofollow noreferrer">http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealBootReceiver.java</a></p> <p>And then from the <em>AlarmReceiver</em> start an <em>IntentService</em>: <a href="http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealAlarmReceiver.java" rel="nofollow noreferrer">http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealAlarmReceiver.java</a></p> <p>From your <em>IntentService</em> then make your network call to poll for data, or whatever you need to do. <em>IntentService</em> automatically puts your work in a background thread, it's very handy: <a href="http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealService.java" rel="nofollow noreferrer">http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealService.java</a></p> <p>Check the docs for these classes too, a lot of into in there. </p> <p>The caveat with this example is that it does <em>not</em> deal with the wake lock gap (the excellent CommonsWare code does that if you need it), but it may give you some more ideas about how to potentially address the "poll using AlarmManager and Service" stuff.</p> <p>UPDATE: the code is now here: <a href="https://github.com/charlieCollins/android-in-practice" rel="nofollow noreferrer">https://github.com/charlieCollins/android-in-practice</a></p>
21,229,180
Convert column index into corresponding column letter
<p>I need to convert a Google Spreadsheet column index into its corresponding letter value, for example, given a spreadsheet:</p> <p><img src="https://i.stack.imgur.com/DyaPs.png" alt="enter image description here"></p> <p>I need to do this (this function obviously does not exist, it's an example):</p> <pre><code>getColumnLetterByIndex(4); // this should return "D" getColumnLetterByIndex(1); // this should return "A" getColumnLetterByIndex(6); // this should return "F" </code></pre> <p>Now, I don't recall exactly if the index starts from <code>0</code> or from <code>1</code>, anyway the concept should be clear.</p> <p>I didn't find anything about this on gas documentation.. am I blind? Any idea?</p> <p>Thank you</p>
21,231,012
23
3
null
2014-01-20 08:24:51.917 UTC
36
2022-08-20 13:51:21.907 UTC
2019-11-05 20:14:55.61 UTC
null
2,032,235
null
1,054,151
null
1
116
javascript|google-apps-script|indexing|google-sheets
102,802
<p>I wrote these a while back for various purposes (will return the double-letter column names for column numbers > 26):</p> <pre><code>function columnToLetter(column) { var temp, letter = ''; while (column &gt; 0) { temp = (column - 1) % 26; letter = String.fromCharCode(temp + 65) + letter; column = (column - temp - 1) / 26; } return letter; } function letterToColumn(letter) { var column = 0, length = letter.length; for (var i = 0; i &lt; length; i++) { column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1); } return column; } </code></pre>
1,625,021
How to return generated ID in RESTful POST?
<p>Let's say we have a service to add a new hotel:</p> <pre><code>&gt; POST /hotel &gt; &lt;hotel&gt; &gt; &lt;a&gt;aaa&lt;/a&gt; &gt; &lt;b&gt;aaa&lt;/b&gt; &gt; &lt;c&gt;aaa.......this is 300K&lt;/c&gt; &gt; &lt;/hotel&gt; </code></pre> <p>And then we have a get:</p> <pre><code>&gt; GET /hotel &lt; HTTP/1.1 200 OK &lt; &lt;hotel&gt; &lt; &lt;a&gt;aaa&lt;/a&gt; &lt; &lt;b&gt;aaa&lt;/b&gt; &gt; &lt;c&gt;aaa.......this is 300K&lt;/c&gt; &lt; &lt;/hotel&gt; </code></pre> <p>Question is what do we return for the initial POST creation? We would like to return the ID (generated on the server) for a "reference" to the new resource but we don't want to return all the hotel data as in our case one of the data fields is a flat file of ~300K.</p> <p>So should you just return:</p> <pre><code>&lt; HTTP/1.1 200 OK &lt; &lt;hotel&gt; &lt; &lt;id&gt;123&lt;/id&gt; &lt; &lt;/hotel&gt; </code></pre> <p>Or should you return the full object:</p> <pre><code>&lt; HTTP/1.1 200 OK &lt; &lt;hotel&gt; &lt; &lt;id&gt;123&lt;/id&gt; &lt; &lt;a&gt;aaa&lt;/a&gt; &lt; &lt;b&gt;aaa&lt;/b&gt; &gt; &lt;c&gt;aaa.......this is 300K&lt;/c&gt; &lt; &lt;/hotel&gt; </code></pre> <p>??</p> <p>I'm interested in the restful best practice. </p> <p>Note: this related <a href="https://stackoverflow.com/questions/797834/should-a-restful-put-operation-return-something">post</a> talks more about what to return but less about how to return it.</p>
1,625,652
3
0
null
2009-10-26 14:10:20.227 UTC
4
2009-10-31 19:49:24.477 UTC
2017-05-23 12:22:53.67 UTC
null
-1
null
47,281
null
1
30
rest
12,798
<p>Return the status code 201 - Created, and put the URL in the Location header. You don't need to return a body at all.</p>
1,367,514
How to decorate a method inside a class?
<p>I am attempting to decorate a method inside a class but python is throwing an error. My class looks like this:</p> <pre><code>from pageutils import formatHeader class myPage(object): def __init__(self): self.PageName = '' def createPage(self): pageHeader = self.createHeader() @formatHeader #&lt;----- decorator def createHeader(self): return "Page Header ",self.PageName if __name__=="__main__": page = myPage() page.PageName = 'My Page' page.createPage() </code></pre> <hr> <p><code>pageutils.py</code>:</p> <pre><code>def formatHeader(fn): def wrapped(): return '&lt;div class="page_header"&gt;'+fn()+'&lt;/div&gt;' return wrapped </code></pre> <p>Python throws the following error</p> <pre class="lang-none prettyprint-override"><code>self.createHeader() TypeError: wrapped() takes no arguments (1 given) </code></pre> <p>Where am I goofing?</p>
1,367,530
3
1
null
2009-09-02 12:50:19.947 UTC
15
2021-05-20 14:38:37.327 UTC
2019-01-08 21:54:57.62 UTC
null
355,230
null
26,143
null
1
70
python|decorator
42,871
<p>Python automatically passes the class instance as reference. (The <code>self</code> argument which is seen in all instance methods).</p> <p>You could do:</p> <pre><code>def formatHeader(fn): def wrapped(self=None): return '&lt;div class=&quot;page_header&quot;&gt;'+fn(self)+'&lt;/div&gt;' return wrapped </code></pre>
8,480,401
Draw glow around inside edge of multiple CGPaths
<p><a href="https://i.stack.imgur.com/gYAri.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gYAri.jpg" alt="image" /></a></p> <p>If I create a CGMutablePathRef by adding together two circular paths as shown by the left image, is it possible to obtain a final CGPathRef which represents only the outer border as shown by the right image?</p> <p>Thanks for any help!</p>
8,482,103
2
1
null
2011-12-12 20:30:41.25 UTC
17
2019-08-15 13:18:24.033 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
961,135
null
1
17
iphone|ios|quartz-2d|cgpath
6,732
<p>What you are asking for is the union of bezier paths. Apple doesn't ship any APIs for computing the union of paths. It is in fact a rather complicated algorithm. Here are a couple of links:</p> <ul> <li><a href="http://www.cocoadev.com/index.pl?NSBezierPathcombinatorics" rel="noreferrer">http://www.cocoadev.com/index.pl?NSBezierPathcombinatorics</a></li> <li><a href="http://losingfight.com/blog/2011/07/09/how-to-implement-boolean-operations-on-bezier-paths-part-3/" rel="noreferrer">http://losingfight.com/blog/2011/07/09/how-to-implement-boolean-operations-on-bezier-paths-part-3/</a></li> </ul> <p>If you explain what you want to do with the union path, we might be able to suggest some alternatives that don't require actually computing the union.</p> <p>You can draw a pretty decent inner glow without actually computing the union of the paths. Instead, make a bitmap. Fill each path on the bitmap. You'll use this as the mask. Next, create an inverted image of the mask, that has everything <em>outside</em> of the union area filled. You'll draw this to make CoreGraphics draw a shadow around the inner edge of the union. Finally, set the mask as your CGContext mask, set the shadow parameters, and draw the inverted image.</p> <p>Ok, that sounds complicated. But here's what it looks like (Retina version on the right):</p> <p><img src="https://i.stack.imgur.com/4o4r6.png" alt="glow"> <img src="https://i.stack.imgur.com/7vmma.png" alt="glow retina"></p> <p>It's not perfect (too light at the corners), but it's pretty good.</p> <p>So here's the code. I'm passing around UIBezierPaths instead of CGPaths, but it's trivial to convert between them. I use a some UIKit functions and objects. Remember that you can always make UIKit draw to an arbitrary CGContext using <code>UIGraphicsPushContext</code> and <code>UIGraphicsPopContext</code>.</p> <p>First, we need an mask image. It should be an alpha-channel-only image that is 1 inside any of the paths, and 0 outside all of the paths. This method returns such an image:</p> <pre><code>- (UIImage *)maskWithPaths:(NSArray *)paths bounds:(CGRect)bounds { // Get the scale for good results on Retina screens. CGFloat scale = [UIScreen mainScreen].scale; CGSize scaledSize = CGSizeMake(bounds.size.width * scale, bounds.size.height * scale); // Create the bitmap with just an alpha channel. // When created, it has value 0 at every pixel. CGContextRef gc = CGBitmapContextCreate(NULL, scaledSize.width, scaledSize.height, 8, scaledSize.width, NULL, kCGImageAlphaOnly); // Adjust the current transform matrix for the screen scale. CGContextScaleCTM(gc, scale, scale); // Adjust the CTM in case the bounds origin isn't zero. CGContextTranslateCTM(gc, -bounds.origin.x, -bounds.origin.y); // whiteColor has all components 1, including alpha. CGContextSetFillColorWithColor(gc, [UIColor whiteColor].CGColor); // Fill each path into the mask. for (UIBezierPath *path in paths) { CGContextBeginPath(gc); CGContextAddPath(gc, path.CGPath); CGContextFillPath(gc); } // Turn the bitmap context into a UIImage. CGImageRef cgImage = CGBitmapContextCreateImage(gc); CGContextRelease(gc); UIImage *image = [UIImage imageWithCGImage:cgImage scale:scale orientation:UIImageOrientationDownMirrored]; CGImageRelease(cgImage); return image; } </code></pre> <p>That was actually the hard part. Now we need an image that is our glow color everywhere <em>outside</em> of the mask (path union) area. We can use UIKit functions to make this easier than a pure CoreGraphics approach:</p> <pre><code>- (UIImage *)invertedImageWithMask:(UIImage *)mask color:(UIColor *)color { CGRect rect = { CGPointZero, mask.size }; UIGraphicsBeginImageContextWithOptions(rect.size, NO, mask.scale); { // Fill the entire image with color. [color setFill]; UIRectFill(rect); // Now erase the masked part. CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage); CGContextClearRect(UIGraphicsGetCurrentContext(), rect); } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } </code></pre> <p>With those two images, we can draw an inner glow into the current UIKit graphics context for an array of paths:</p> <pre><code>- (void)drawInnerGlowWithPaths:(NSArray *)paths bounds:(CGRect)bounds color:(UIColor *)color offset:(CGSize)offset blur:(CGFloat)blur { UIImage *mask = [self maskWithPaths:paths bounds:bounds]; UIImage *invertedImage = [self invertedImageWithMask:mask color:color]; CGContextRef gc = UIGraphicsGetCurrentContext(); // Save the graphics state so I can restore the clip and // shadow attributes after drawing. CGContextSaveGState(gc); { CGContextClipToMask(gc, bounds, mask.CGImage); CGContextSetShadowWithColor(gc, offset, blur, color.CGColor); [invertedImage drawInRect:bounds]; } CGContextRestoreGState(gc); } </code></pre> <p>To test it, I created an image using a couple of circles and put it in a UIImageView:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; UIBezierPath *path1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, 60, 60)]; UIBezierPath *path2 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 60, 60)]; NSArray *paths = [NSArray arrayWithObjects:path1, path2, nil]; UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0.0); { [self drawInnerGlowWithPaths:paths bounds:self.imageView.bounds color:[UIColor colorWithHue:0 saturation:1 brightness:.8 alpha:.8] offset:CGSizeZero blur:10.0]; } imageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } </code></pre>
8,521,683
Is there a way to throttle javascript performance to simulate a slow client
<p>I am working on a site that uses jQuery and has a fair amount of javascript that is run using <code>$(document).ready()</code>. On my dev machine everything runs great but it's a pretty powerful machine. I have had reports from people using older hardware of behavior that seems strange and I am fairly convinced that it is down to the time taken to process this initial javascript on slower machines.</p> <p>Clearly, the solution is to sort out this initial javascript but it got me wondering - does anyone know of a way to slow down the execution speed of javascript in either Chrome or Firefox to be able to simulate these slower clients on my dev machine?</p> <p>Cheers!</p> <p><strong><em>Update:</em></strong> Back when this question was posted, there weren't the same set of tools that there are today. At that time the VM option was the best option therefore I am leaving it as the accepted answer. However these days I would go straight for Chrome dev tools instead as suggested by Oded Niv</p>
8,521,733
10
1
null
2011-12-15 14:32:36.19 UTC
10
2020-07-21 10:11:51.113 UTC
2018-10-23 11:22:38.11 UTC
null
2,884,309
null
219,405
null
1
63
javascript
26,058
<p>This might not be the best solution, but something that could definetely work is to run a virtual machine, there you could specify all hardware specs as long as they are lower than you real machine. Look at <a href="https://superuser.com/questions/297550/how-can-i-simulate-a-slow-machine-in-a-vm">this post</a> </p>
19,674,380
Execute jQuery function after another function completes
<p>I want to execute a custom jQuery function after another custom function completes<br> The first function is used for creating a "typewriting" effect </p> <pre><code>function Typer() { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; setInterval(function() { if(i == srcText.length) { clearInterval(this); return; }; i++; result += srcText[i].replace("\n", "&lt;br /&gt;"); $("#message").html( result); }, 100); } </code></pre> <p>and the second function plays a sound</p> <pre><code>function playBGM() { document.getElementById('bgm').play(); } </code></pre> <p>I am calling the functions one after the another like</p> <pre><code>Typer(); playBGM(); </code></pre> <p>But the sound starts playing as the text is getting typed. I want to play the sound only AFTER the typewriting has finished.</p> <p>Here is what I have tried: <a href="http://jsfiddle.net/GkUEN/5/" rel="noreferrer">http://jsfiddle.net/GkUEN/5/</a></p> <p>How can I fix this?</p>
19,674,400
4
1
null
2013-10-30 05:18:40.697 UTC
20
2019-12-16 10:31:07.507 UTC
2018-02-08 06:34:10.287 UTC
null
1,402,846
null
2,878,249
null
1
45
jquery|function
157,743
<p>You should use a callback parameter:</p> <pre><code>function Typer(callback) { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; var interval = setInterval(function() { if(i == srcText.length - 1) { clearInterval(interval); callback(); return; } i++; result += srcText[i].replace("\n", "&lt;br /&gt;"); $("#message").html(result); }, 100); return true; } function playBGM () { alert("Play BGM function"); $('#bgm').get(0).play(); } Typer(function () { playBGM(); }); // or one-liner: Typer(playBGM); </code></pre> <p>So, you pass a function as parameter (<code>callback</code>) that will be called in that <code>if</code> before <code>return</code>.</p> <p>Also, <a href="http://recurial.com/programming/understanding-callback-functions-in-javascript/" rel="nofollow noreferrer">this</a> is a good article about callbacks.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Typer(callback) { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; var interval = setInterval(function() { if(i == srcText.length - 1) { clearInterval(interval); callback(); return; } i++; result += srcText[i].replace("\n", "&lt;br /&gt;"); $("#message").html(result); }, 100); return true; } function playBGM () { alert("Play BGM function"); $('#bgm').get(0).play(); } Typer(function () { playBGM(); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="message"&gt; &lt;/div&gt; &lt;audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3"&gt; &lt;/audio&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/GkUEN/14/" rel="nofollow noreferrer"><strong>JSFIDDLE</strong></a></p>
871,560
How does Wolfram Alpha work?
<p>Behind the tables and tables of raw data, how does Wolfram Alpha work?</p> <p>I imagine there are various artificial intelligence mechanisms driving the site but I can't fathom how anyone would put something like this together. Are there any explanations that would help a programmer understand how something like this is created? Does the knowledge base learn on its own or is it taught very specific details in a very organized manner? What kind of structure and language is used to store this type of data?</p> <p>Obviously this is a huge question and can't fully be answered here but some of the general concepts would be nice to know so I can build off of them and do my own research.</p>
871,606
4
0
2009-05-16 02:53:07.5 UTC
2009-05-16 02:53:07.53 UTC
10
2009-05-16 20:38:06.723 UTC
null
null
null
null
20,471
null
1
14
artificial-intelligence|machine-learning
4,158
<p><a href="http://blog.wolframalpha.com/2009/05/01/the-secret-behind-the-computational-engine-in-wolframalpha/" rel="nofollow noreferrer">This official blog post</a> has some portion of the explanation: the language Mathematica.</p>
1,208,802
Django and urls.py: How do I HttpResponseRedirect via a named url?
<p>I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') </code></pre> <p>What I want to accomplish is something like:</p> <pre><code>def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName </code></pre> <p>I get syntax errors when I execute this, any ideas?</p>
1,208,839
4
0
null
2009-07-30 19:29:30.133 UTC
5
2019-05-08 08:53:24.053 UTC
2014-04-22 14:50:33.197 UTC
null
100,297
null
143,078
null
1
28
python|django|redirect|django-urls
31,193
<p>You need to use the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse" rel="noreferrer"><code>reverse()</code></a> utils function.</p> <pre><code>from django.urls import reverse # or Django &lt; 2.0 : from django.core.urlresolvers import reverse def myview(request): return HttpResponseRedirect(reverse('arch-summary', args=[1945])) </code></pre> <p>Where <code>args</code> satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.</p>
56,675,698
Show Assistant Editor missing in Xcode 11?
<p>In Xcode 10, the toolbar had an inter-locking ring icon which showed the assistant editor, it's missing in Xcode 11. </p> <p><a href="https://i.stack.imgur.com/Qi19p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qi19p.png" alt="Xcode 10"></a></p> <p><a href="https://i.stack.imgur.com/T6ZBX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T6ZBX.png" alt="Xcode 11"></a></p>
56,676,238
8
1
null
2019-06-19 20:54:25.413 UTC
12
2021-05-09 05:08:10.19 UTC
null
null
null
null
6,782,989
null
1
108
xcode|xcode10|xcode11
44,708
<blockquote> <p>In Xcode 10, the toolbar had an inter-locking ring icon which showed the assistant editor, it's missing in Xcode 11.</p> </blockquote> <p>The interface has changed a little, but the functionality is still there. The top right corner of the editor pane has two buttons:</p> <p><a href="https://i.stack.imgur.com/8DmGH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8DmGH.png" alt="top right corner of Xcode text editor pane"></a></p> <p>Clicking the left button, which looks like lines of text, displays the popup menu, where you can choose various editor configuration options. Clicking the right button just narrows the existing editor and adds another one next to it.</p> <p>Some of the same options are also available in the Editor menu in the main menu bar.</p> <hr> <p><strong>Update:</strong> This is from the <a href="https://developer.apple.com/documentation/xcode_release_notes/xcode_11_beta_7_release_notes" rel="noreferrer">Xcode 11 beta release notes</a>, and perhaps more fully explains why the UI was changed:</p> <blockquote> <p>Editors can be added to any window without needing the Assistant Editor. Editors are added using the “Add Editor” button in the jump bar or the File > New > Editor command. Each editor can now be in one of three modes: “Editor Only”, “Editor and Assistant” or “Editor and Canvas”. The latter two modes automatically show relevant content when available. When using multiple editors, the View > Editor > Focus command can be used to temporarily expand the active editor to fill the entire window, hiding other editors. For source control support, the Code Review button in the Toolbar replaces the Comparison Editor. The “Show Authors” command is now available from the Source Editor’s Editor menu. The SCM Log is now in the Inspector Area. (43806898)</p> </blockquote> <p>With multiple editors possible in a window, you need editor-specific controls for showing the ancillary views like the assistant editor, author view, etc.</p> <hr> <p>From SMGreenfield's comment:</p> <blockquote> <p>Sometimes I want to look at a different part of the same darn document. There has always been a way to do this, but it involved jumping through hoops.</p> </blockquote> <p>Just add another editor: click the Add Editor button in the upper right corner of the editor, or choose <strong>File > New > Editor</strong>. The new editor will default to showing the same file you were working on in the existing editor. </p> <p>If new editors show up on the right of the existing editor and you'd prefer them to stack vertically, you can choose <strong>View > Change Editor Orientation</strong>. If you want them to stack horizontally most of the time (the default) but just want one to show up below, choose <strong>File > New > Editor Below</strong>.</p>