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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50,430 |
CSS - Placement of a div in the lower left-hand corner
|
<p>I wish I were a CSS smarty .... </p>
<p>How can you place a div container in the lower left-hand corner of the web page; taking into account the users scroll-position?</p>
| 50,442 | 1 | 0 | null |
2008-09-08 19:03:27.093 UTC
| 1 |
2017-02-20 17:19:24.917 UTC
|
2016-03-04 15:56:13.58 UTC
|
Brian Warshaw
| 996,815 |
deadbug
| 4,646 | null | 1 | 28 |
css|html|positioning
| 39,863 |
<p>To position an element relative to the "viewport" (the window or frame it's in), and have it ignore how that viewport is scrolled, you can use the <code>position: fixed;</code> property value (<a href="https://developer.mozilla.org/en/docs/Web/CSS/position#Fixed_positioning" rel="noreferrer">MDN documentation</a>). This has been supported by every browser since Internet Explorer 7.</p>
<p>To position the element at the bottom-left of the window, we need to also specify that it should be positioned at <code>0</code> distance from the <code>bottom</code> and <code>left</code>:</p>
<pre><code>position: fixed;
bottom: 0;
left: 0;
</code></pre>
<h3>Full Example</h3>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bottom-left {
position: fixed;
bottom: 0;
left: 0;
}
.alert {
border: 2px solid red;
background: white;
font-weight: bold;
padding: 1em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bottom-left alert">
Look at me!
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dignissim diam arcu, a gravida justo malesuada et. Fusce iaculis, dui laoreet ultricies congue, arcu lectus rhoncus neque, ut molestie magna augue ut neque. Duis in feugiat ipsum, et imperdiet nunc. Cras convallis lorem eu diam malesuada malesuada. Nunc dapibus suscipit ligula, vel mattis eros blandit id. In placerat justo vitae pretium fermentum. Proin ac erat commodo nibh ullamcorper feugiat. Nulla ultricies maximus massa, non semper dolor malesuada vel. Nullam sem justo, bibendum vel tempus pharetra, gravida vel sapien. Morbi facilisis tristique mauris vel elementum. Ut porttitor egestas metus eget auctor. Phasellus efficitur rutrum massa nec fringilla. Aliquam et imperdiet leo. Sed tincidunt hendrerit tortor eget tempor.</p>
<p>Sed vel dolor lectus. Nulla sed blandit lacus. Mauris ac magna nec libero vehicula aliquet id a libero. Vivamus sed lobortis velit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed at feugiat sapien, ut commodo mi. Quisque scelerisque maximus efficitur. In ultrices, magna eu semper pellentesque, tellus odio hendrerit augue, ut porta sapien lacus quis odio.</p>
<p>Duis sodales, dui a condimentum imperdiet, tellus est laoreet velit, a viverra risus libero sed urna. Phasellus sollicitudin tincidunt viverra. Proin vulputate leo at justo auctor feugiat. Nam auctor, mauris at commodo tempus, eros diam varius ligula, vitae efficitur massa lectus et enim. Integer tristique nibh in lacus condimentum, et interdum urna mollis. Aenean id risus tristique, volutpat dolor sed, fermentum ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam velit nibh, elementum at orci quis, tempor fermentum tellus. Nunc facilisis nisi at leo auctor aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam tempor ipsum vel scelerisque tincidunt. Etiam vulputate auctor ante, in tristique est congue ut. Vestibulum maximus nibh vestibulum tristique ullamcorper. Phasellus eu eleifend ante, nec efficitur nulla.</p>
<p>Nunc pulvinar purus id arcu egestas, sed iaculis nisl finibus. Sed cursus bibendum tortor, id cursus lacus euismod in. Nam lacinia, sapien faucibus dapibus varius, neque velit fringilla est, in porta quam sem sit amet ligula. Aliquam ornare est ac pellentesque suscipit. Curabitur eleifend convallis sem, volutpat efficitur erat laoreet id. Maecenas interdum ante in lectus varius, lobortis auctor quam rutrum. Nullam tristique felis quis lectus luctus gravida. Cras porttitor pellentesque nibh. Fusce placerat vehicula commodo. Mauris vel lectus viverra sem consectetur sagittis quis vel lectus. Quisque vel dapibus augue. Sed lacinia massa quis dui sodales faucibus.</p>
<p>Donec sagittis, dolor sed fermentum dapibus, justo ipsum porttitor purus, sed fermentum mi nulla non lorem. Praesent aliquet iaculis molestie. Phasellus enim nunc, vestibulum non odio vel, porta imperdiet lorem. Morbi laoreet felis a ipsum elementum sollicitudin. Morbi varius mollis ex, a posuere lorem fringilla ac. Curabitur metus ligula, mollis quis diam eu, pulvinar placerat libero. Aenean vestibulum lacinia diam in facilisis. Praesent egestas sapien a est consequat facilisis. Nulla id mauris a metus venenatis pellentesque. Praesent justo augue, efficitur ac vulputate et, luctus at elit. Proin quis urna quam. Pellentesque iaculis, felis sed hendrerit venenatis, purus augue venenatis tellus, a posuere justo tellus at ex. Donec et arcu non arcu scelerisque efficitur nec sed dolor. Sed eget lacus enim. Donec sodales mollis condimentum.</p></code></pre>
</div>
</div>
</p>
|
44,447,232 |
Error while executing test, if using CreateResponse extention method to return Azure Function HttpResonseMessage
|
<p>My Azure Function code is like below</p>
<pre><code>public static class MyHttpTriggerFunction
{
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
// some business logic
if (valid)
{
return req.CreateResponse(HttpStatusCode.OK, true);
}
else
{
return req.CreateResponse(HttpStatusCode.BadRequest, "some error message");
}
}
}
</code></pre>
<p>In my test project I am reading the result like below:</p>
<pre><code>var result = await MyHttpTriggerFunction.Run(req, log).ConfigureAwait(false);
</code></pre>
<p>After executing the function, when it try to return the response in result variable, the test method fails with exception.</p>
<p>**</p>
<blockquote>
<p>System.InvalidOperationException: The request does not have an
associated configuration object or the provided configuration was
null.</p>
</blockquote>
<p>**</p>
<p>I have made sure that test project has the same <code>System.Net.Http.HttpRequestMessageExtension</code> dll.</p>
<p>If I change the function code not to use <code>CreateResponse</code> extension method (this extension method is from the VS 2017 template's code )
and return the response like below, I get the response in test method and the test case runs fine.</p>
<pre><code>var res = new HttpResponseMessage();
if (valid)
{
res.StatusCode = HttpStatusCode.OK;
res.Content = new ObjectContent<bool>(true, new JsonMediaTypeFormatter());
return res;
}
else
{
res.StatusCode = HttpStatusCode.BadRequest;
res.Content = new ObjectContent<string>("some error message", new JsonMediaTypeFormatter());
return res;
}
</code></pre>
<p>Below is the stacktrace of error</p>
<blockquote>
<p>Result StackTrace: at
System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
request, HttpStatusCode statusCode, T value, HttpConfiguration
configuration) at
System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage
request, HttpStatusCode statusCode, T value) at
MyFunctionApp.MyHttpTriggerFunction.d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at
MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.d__2.MoveNext()
in
C:\Users\rsingh\Desktop\Git_Workspace\ActivationAPI\MyFunctionAppUnitTest\MyHttpTriggerFunctionTest.cs:line
53
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action
action) Result Message: Test method
MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.MyHttpTriggerFunction_SuccessResult
threw exception: System.InvalidOperationException: The request does
not have an associated configuration object or the provided
configuration was null.</p>
</blockquote>
<p>Am I missing something trivial</p>
| 44,447,349 | 2 | 0 | null |
2017-06-08 23:51:30.243 UTC
| 3 |
2017-09-18 09:48:28.977 UTC
|
2017-09-18 09:48:28.977 UTC
| null | 1,878,728 | null | 4,372,824 | null | 1 | 30 |
c#|unit-testing|azure|visual-studio-2017|azure-functions
| 13,984 |
<p>The Error message is telling you the problem.</p>
<blockquote>
<p>The request does not have an associated <strong>configuration</strong> object or the provided configuration was null.</p>
</blockquote>
<p>When testing the request out side of a httpserver you need to give the request a <code>HttpConfiguration.</code></p>
<pre><code>// Arrange.
var configuration = new HttpConfiguration();
var request = new System.Net.Http.HttpRequestMessage();
request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;
//...other code
</code></pre>
|
38,855,891 |
Angular Cli Webpack, How to add or bundle external js files?
|
<p>I am not sure how to include JS files (vendors) after switching Angular Cli from SystemJs to Webpack.</p>
<p><strong>For example</strong></p>
<p>Option A</p>
<p><em>I have some js files that were installed via npm. Adding script tags to the head tag like this does not work. Nor does it seem like the best way.</em></p>
<pre><code><head>
<script src="node_modules/some_package/somejs.js">
</head>
//With systemJs I could do this
<head>
<script src="vendor/some_package/somejs.js">
</head>
</code></pre>
<p>Option B</p>
<p><em>Include these js files as part of the webpack bundle. This seems like the way it probably should be done. However I am not sure how to do this as all of the webpack code seems to be hidden behind the angular-cli-webpack node package. I was thinking maybe there is another webpack config that we might have access to. But I am not sure as I didn't see one when creating a new angular-cli-webpack project.</em></p>
<p><strong>More Info:</strong></p>
<p>The js files I am trying to include need to be included before the Angular project. For example jQuery and a third party js lib that isn't really setup for module loading or typescript.</p>
<p><strong>References</strong>
<a href="https://github.com/angular/angular-cli/blob/master/WEBPACK_UPDATE.md" rel="noreferrer">https://github.com/angular/angular-cli/blob/master/WEBPACK_UPDATE.md</a>
<a href="https://github.com/angular/angular-cli/tree/webpack" rel="noreferrer">https://github.com/angular/angular-cli/tree/webpack</a></p>
| 39,661,714 | 5 | 4 | null |
2016-08-09 16:20:01.047 UTC
| 22 |
2021-03-31 13:58:01.63 UTC
|
2017-11-29 14:53:57.95 UTC
| null | 1,949,099 | null | 1,949,099 | null | 1 | 87 |
javascript|angular|angular-cli
| 103,402 |
<p><strong>Last tested using angular-cli 11.x.x with Angular 11.x.x</strong></p>
<p>This can be accomplished using <code>scripts:[]</code> in <code>angular.json</code>.</p>
<pre><code>{
"project": {
"version": "1.0.0",
"name": "my-project"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": ["assets"],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "app",
"mobile": false,
"styles": [
"styles.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js"
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false
}
}
</code></pre>
<p><strong>Note:</strong> As <a href="https://github.com/angular/angular-cli/wiki/angular-cli" rel="noreferrer">the documentation suggests</a> in the global library installation: if you change the value of your <code>styles</code> (or <code>scripts</code>!) property, then:</p>
<blockquote>
<p>Restart ng serve if you're running it,</p>
</blockquote>
<p>..to see the scripts executed in a **globalcontext via the <code>scripts.bundle.js</code> file.</p>
<p><strong>Note:</strong> As discussed in the comments below. JS libs that support UMD modules via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import" rel="noreferrer">es6 imports</a> such as jQuery can also be imported into your typescript files using the es6 import syntax. For example: <code>import $ from 'jquery';</code>.</p>
|
38,757,538 |
Android Design Layout ListItem RecyclerView Horizontal
|
<p>I am using the tools:listitem attribute to show my views in the design layout with a recyclerview. Problem is, they always show up in a vertical list. Is there a way to have the Design Layout Editor display them horizontally?</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@android:layout/simple_list_item_checked"/>
</code></pre>
<p></p>
<p><a href="https://i.stack.imgur.com/qvKh6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qvKh6.png" alt="enter image description here"></a></p>
<p>I want the above image, displayed horizontally. IN THE DESIGN VIEW. NOT in the application itself, I know how to do that.</p>
| 40,020,239 | 4 | 5 | null |
2016-08-04 02:24:53.743 UTC
| 3 |
2021-08-22 12:49:05.69 UTC
|
2016-10-16 22:54:23.427 UTC
| null | 796,231 | null | 796,231 | null | 1 | 28 |
android|xml|android-studio
| 11,301 |
<p>Please Check this code</p>
<pre><code> <android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
</code></pre>
|
26,093,962 |
Can I change my Android app icon and name in later release?
|
<p>This is going to sound stupid in a way, but I want to know if it is possible to change the application logo (icon) and Android name in my subsequent releases?</p>
<p>Say, today I push my app in the Android market, and tomorrow I want to change the logo/icon (I know I "should" not do this), but is it possible to do so? Also, what about the application name?</p>
<p>Thanks</p>
| 26,094,044 | 5 | 0 | null |
2014-09-29 06:47:49.013 UTC
| 5 |
2020-12-26 01:17:35.727 UTC
|
2019-07-29 03:31:33.297 UTC
| null | 6,214,491 | null | 216,190 | null | 1 | 28 |
android|google-play|android-icons
| 52,711 |
<p>Yes, you can change the name and logo whenever you want by changing <code>android:label</code> and <code>android:logo</code> attribute of your application tag in <code>AndroidManifest.xml file</code>.</p>
<p>But, you can't change <code>Package</code> name once you uploaded app on play store.</p>
|
54,839,672 |
Difference between Swagger & HATEOAS
|
<p>Can anyone explain difference between Swagger & HATEOAS. I can Search many time but no buddy can explain the proper detailed answer this two aspects. </p>
| 54,841,309 | 3 | 0 | null |
2019-02-23 08:28:45.53 UTC
| 9 |
2021-08-18 18:40:19.753 UTC
| null | null | null | null | 10,870,476 | null | 1 | 18 |
rest|spring-mvc|swagger|spring-hateoas
| 10,484 |
<p>The main difference between Swagger and HATEOAS IMO, which is not covered in the accepted answer, is, that Swagger is only needed for RPC'esque APIs. Such APIs, however, have actually hardly anything to do with REST.</p>
<p>There is a further, widespread misconception that anything exchanged via HTTP is automatically RESTful (~ in accordance with the REST archtitectural style), which it is not. REST just defines a set of constraints that are not choices or options but are mandatory. From start to finish. There is nothing wrong from being not RESTful, but it is wrong to term such an architecture REST.</p>
<p>Swagger describe the operations that can be performed on an endpoint and the payload (including headers and the expected representation formats) that needs to be sent to the service and also describe what a client might expect as response. This allows Swagger to be used both as documentation as well as testing-framework for the API. Due to the tight coupling of Swagger to the API it behaves much like a typical RPC service description, i.e. similar to WSDL files in SOAP or stub or skeletton classes in RMI or CORBA. If either the endpoint changes or something in the payload changes, clients implementing against a Swagger documentation will probably break over time just reintroducing the same problems typical RPC implementations have.</p>
<p>REST and HATEOAS, on the other side, are designed for disovery and further development. REST isn't a protocol but an architectural style to start with that describes the interaction flow between a client and server in a distributed system. It basically took the concepts which made the Web so successful and translated it onto the application layer. So the same concepts that apply to the browsable Web also apply to REST. Therefore it is no miracle that also HATEOAS (the usage of and support for links, link relations and link names) behave similar to the Web.</p>
<p>On designing a REST architecture it is benefitial to think of a state machine where a server provides all of the information a client needs to take further actions. Asbjørn Ulsberg held a great talk back in 2016 where he <a href="https://www.youtube.com/watch?time_continue=1222&v=QIv9YR1bMwY&t=13m37s" rel="noreferrer">explains affordances and how a state machine might be implemented through HATEOAS</a>. Besides common or standardized media-types and relation names no out-of-band knowledge is necessary to interact with the service further. In the case of the toaster example Asbjørn gave in his talk, a toaster may have the states <code>off</code>, <code>on</code>, <code>heating</code> and <code>idle</code> where turning a toaster on will lead to a state transition from <code>off</code> to <code>on</code> followed by a transition to <code>heating</code> till a certain temperature is reached where the state is transitioned to <code>idle</code> and switches between <code>idle</code> and <code>heating</code> till the toaster is turned off.</p>
<p>HATOAS will provide a client with the information on the current state and include links a client can invoke to transition to the next state, i.e. turning the toaster off again. It's important to stress here, that a client is provided by the server with every action the client might perform next. There is no need for a client implementor to consult any proprietary API documentation in order for a client to be able to interact with a REST service. Further, URIs do not have to be meaningful or designed to convey a semantical-expressive structure as clients will determine whether invoking that URI makes sense via the link-relation name. Such relation names are either specified by <a href="https://www.iana.org/assignments/link-relations/link-relations.xml" rel="noreferrer">IANA</a>, by a common approach such as <a href="http://dublincore.org/documents/dc-html/" rel="noreferrer">Dublin Core</a> or <a href="https://schema.org/" rel="noreferrer">schema.org</a> or by absolut URIs acting as <a href="https://www.rfc-editor.org/rfc/rfc8288#section-3.4.2" rel="noreferrer">extension attributes</a> which might point to a human-readable description, which further might be propagated to the user via mouse-over tooltips or such.</p>
<p>I hope you can see by yourself that Swagger is only needed to describe RPC Web-APIs rather than applications that follow the REST architectural design. Messages exchanged via REST APIs should include all the information needed by a client to make informed choices on the next state transition. As such it is benefitial to design such message flows and interactions as state machine.</p>
<hr />
<p>Update:</p>
<blockquote>
<p>How are Swagger and HATEOAS mutually exclusive? The former documents your endpoints (making auto-generating code possible) and the latter adds meta-information to your endpoints which tell the consumer what they can do (i.e. which other endpoints are available). These are very different things.</p>
</blockquote>
<p>I never stated that they are mutually exclusive, just that they serve two different purposes, where if you follow one approach the other gets more or less useless. Using both does not make any sense though.</p>
<p>Let's move the discussion to the Web domain as this is probably more easily understandable and REST is de facto just a generalization of the concepts used on the Web, so doing this step is just natural and also a good recommendation in terms of designing REST architectures in general. Think of a case where you as a user want to send some data to the server. You have never used the service before so you basically don't know how a request has to look like.</p>
<p>In Swagger you would call the endpoint documentation, select the option that most likely might solve your task, read up on how the request needs to look like and hack a test-case into your application that ends up generating a HTTP request that is sent to the respective location. Auto-generating code might spare you some hacking time, though you still need to integrate the stub classes into your application and test the whole thing at least once just to be safe. If you later on need to integrate a second service of that API or of yet an other API in general, you need to start from the beginning and look up the Swagger documentation, generate or hack the interaction code and integrate it into your domain. Plenty of manual steps involved and in cases of API changes you need to update your client as otherwise it might stop working.</p>
<p>In the Web example however, you just start your browser/Web client, invoke the respective URI that allows you to send the data to the server and the server will most likely send you a HTML form you just need to fill out and click the send button which automatically sends the request to the server which will start to process it. This is HATEOAS. You used the given controls to drive your workflow. The server taught your client every little detail it needed to make a valid request. It served your client with the target URI to send the request to, the HTTP method it should use and most often also implicitly the media type the payload should be in. In addition to that it also gave your clients a skeleton of the expected and/or supported elements the payload should contain. I.e. the form may require you to fill out a couple of input fields, select among a given set of choices or use some other controls such as a date or time picker value that is translated to a valid date or time representation for you. All you needed to do was to invoke the respective resource in your Web client. No auto-generation, no integration into your browser/application. Using other services (from the same or different providers) will, most likely, just work the same way so no need to change or update your HTTP client (browser) as long as the media-type request and responses are exchanged are supported.</p>
<p>In the case where you rely on Swagger RPC'esque documentation, that documentation is the truth on how to interact with the service. Mixing in some HATEOAS information doesn't provide you any benefits. In the Swagger case, carrying around additional meta-information that bloat up the request/response for no obvious reasons, as all the required information is given in the reference documentation, will, with some certainty, lead to people starting questioning the sanity of the developers of that service and ask for payload reduction. Just look here at SO for a while and you will find enough question asking on how to optimize the interaction further and further and reducing message size to a minimum as they process every little request and don't make use of response caching at all. In the HATEOAS case, pointing to an external reference is just useless as peers in such an architecture most likely already have support for the required necessities, such as URI, HTTP and the respective media types, implemented into it. In cases where custom media-types are used, support can be added at runtime via plug-ins or add-ons dynamically (if supported).</p>
<p>So, Swagger and HATEOAS are not mutually exclusive but the other gets more or less useless once you decided for one route or the other.</p>
|
7,283,134 |
What is the benefit of import in a namespace in R?
|
<p>The namespace mechanism of R allows one to <code>export</code> functions which then are visible to the user. Furthermore, it allows to <code>import</code> functions from other packages. Whereas the benefit of export is obvious, I have more problems understanding the benefit of import.</p>
<p>One benefit seems to be, that one can use functions from other packages without attaching the package and thereby saving memory. This is exemplified in section <a href="http://cran.r-project.org/doc/manuals/R-exts.html#An-example" rel="noreferrer">1.6.4 in the writing R extensions manual</a>.</p>
<p>However, there must be other benefits of the import function. Especially, <a href="http://cran.r-project.org/doc/manuals/R-exts.html#Name-spaces-with-S4-classes-and-methods" rel="noreferrer">section 1.6.6 (that deals with S4 classes)</a> shows the <code>namespace</code> of the stats4 package:</p>
<pre><code> export(mle)
importFrom("graphics", plot)
importFrom("stats", optim, qchisq)
## For these, we define methods or (AIC, BIC, nobs) an implicit generic:
importFrom("stats", AIC, BIC, coef, confint, logLik, nobs, profile,
update, vcov)
exportClasses(mle, profile.mle, summary.mle)
## All methods for imported generics:
exportMethods(coef, confint, logLik, plot, profile, summary, show, update, vcov)
## implicit generics which do not have any methods here
export(AIC, BIC, nobs)
</code></pre>
<p>Here there are functions imported which are neither S4 classes nor generics (where it would make sense to use import as well, as documented in the example in <a href="http://cran.r-project.org/doc/manuals/R-exts.html#Name-spaces-with-S4-classes-and-methods" rel="noreferrer">that section</a>), but functions like <code>plot</code> from the <code>graphics</code> package which are automatically loaded when R starts.</p>
<p>Therefore my question is, what is the benefit of importing functions like <code>plot</code>, <code>optim</code> or <code>qchisq</code>?</p>
| 7,283,511 | 1 | 0 | null |
2011-09-02 12:04:09 UTC
| 13 |
2013-05-23 01:09:39.02 UTC
| null | null | null | null | 289,572 | null | 1 | 30 |
r|namespaces|package
| 5,852 |
<p>If a function <code>foo</code> is imported from package Bar then it is found regardless of what the user does to their search path, e.g., by attaching a package Baz that also has a function <code>foo</code>. Without a name space, the package code would suddenly find itself using <code>Baz::foo</code>. There are also efficiency issues (<code>foo</code> is found immediately, rather than after searching through all symbols on the search path), but these are likely to be trivial for most applications. In the same way, <code>importFrom</code> is an improvement over <code>import</code> because of fewer collisions (or use of unintended functions) and more efficient look-up.</p>
<p>With S4 (and S3) things can get quite complicated. A non-generic function like <code>graphics::plot</code> can be promoted to a generic (with <code>setGeneric</code>) in two different packages, and each generic can have its own set of methods attached. A package author will want to be precise about which <code>plot</code> generic, and hence which methods dispatch table, their classes and methods see.</p>
<p>Calling a function with <code>pkg::foo</code> always resolves to the intended function. It requires that pkg be listed in the Depends: field of the DESCRIPTION file (maybe in Imports: but then it seems like misleading advertising to not import from pkg), polluting the user's search path. It also involves two symbol look-ups and a function call (<code>::</code>), and so is less efficient. The lazy and lack-of-attention-to-detail part of me also sees use of <code>::</code> as tedious and error prone.</p>
<p>The package <a href="https://hedgehog.fhcrc.org/bioconductor/trunk/madman/Rpacks/codetoolsBioC" rel="noreferrer">codetoolsBioC</a> (via svn with username and password <code>readonly</code>) can generate a NAMESPACE file from an existing package (or at least it could before recent changes to R-devel introduced a NAMESPACE on packages without one; I haven't tried codetoolsBioC on such a package).</p>
|
22,861,828 |
java string.getBytes("UTF-8") javascript equivalent
|
<p>I have this string in java: </p>
<pre><code>"test.message"
byte[] bytes = plaintext.getBytes("UTF-8");
//result: [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
</code></pre>
<p>If I do the same thing in javascript: </p>
<pre><code> stringToByteArray: function (str) {
str = unescape(encodeURIComponent(str));
var bytes = new Array(str.length);
for (var i = 0; i < str.length; ++i)
bytes[i] = str.charCodeAt(i);
return bytes;
},
</code></pre>
<p>I get: </p>
<pre><code> [7,163,140,72,178,72,244,241,149,43,67,124]
</code></pre>
<p>I was under the impression that the unescape(encodeURIComponent()) would correctly translate the string to UTF-8. Is this not the case? </p>
<p>Reference: </p>
<p><a href="http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html" rel="noreferrer">http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html</a></p>
| 22,861,911 | 2 | 0 | null |
2014-04-04 11:40:36.003 UTC
| 2 |
2014-09-01 03:48:25.48 UTC
|
2014-04-04 11:49:53.183 UTC
|
user429620
| null |
user429620
| null | null | 1 | 13 |
java|javascript|utf-8|byte|utf-16
| 44,451 |
<p><em>JavaScript</em> has no concept of character encoding for <em>String</em>, everything is in <em>UTF-16</em>. Most of time time the value of a <code>char</code> in <em>UTF-16</em> matches <em>UTF-8</em>, so you can forget it's any different.</p>
<p>There are more optimal ways to do this but</p>
<pre><code>function s(x) {return x.charCodeAt(0);}
"test.message".split('').map(s);
// [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
</code></pre>
<p>So what is <code>unescape(encodeURIComponent(str))</code> doing? Let's look at each individually,</p>
<ol>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="noreferrer"><code>encodeURIComponent</code></a> is converting every character in <code>str</code> which is illegal or has a meaning in <em>URI Syntax</em> into a <em>URI escaped</em> version so that there is no problem using it as a key or value in the search component of a <em>URI</em>, for example <code>encodeURIComponent('&='); // "%26%3D"</code> Notice how this is now a 6 character long <em>String</em>.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape" rel="noreferrer"><code>unescape</code></a> is actually depreciated, but it does a similar job to <code>decodeURI</code> or <code>decodeURIComponent</code> (the reverse of <code>encodeURIComponent</code>). If we look in the <a href="http://es5.github.io/#B.2.2" rel="noreferrer"><strong>ES5 spec</strong></a> we can see <code>11. Let c be the character whose code unit value is the integer represented by the four hexadecimal digits at positions k+2, k+3, k+4, and k+5 within Result(1).</code><br>
So, <code>4</code> digits is <code>2</code> bytes is <em>"UTF-8"</em>, however as I mentioned, all <em>Strings</em> are <em>UTF-16</em>, so it's really a <em>UTF-16</em> string limiting itself to <em>UTF-8</em>.</li>
</ol>
|
22,507,671 |
bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date
|
<pre><code><script type="text/javascript">
// When the document is ready
$(document).ready(function () {
$('.datepicker').datepicker({
format: "yyyy-mm-dd",
}).on('changeDate', function(ev){
// do what you want here
$(this).datepicker('hide');
}).on('changeDate', function(ev){
if ($('#startdate').val() != '' && $('#enddate').val() != ''){
$('#period').text(diffInDays() + ' d.');
} else {
$('#period').text("-");
}
});
});
</script>
</code></pre>
<p>So here's what my datepicker looks like. So basically when I change date by clicking mouse it works good, however when I manually change date with keyboard or manually clear the date change date event doesn't get called. Is this a bug or am I doing something wrong here ?</p>
| 22,507,814 | 11 | 0 | null |
2014-03-19 13:37:47.437 UTC
| 6 |
2021-08-30 18:24:34.843 UTC
|
2017-09-18 09:10:55.223 UTC
| null | 8,311,909 | null | 555,479 | null | 1 | 25 |
javascript|jquery|twitter-bootstrap|datepicker|bootstrap-datepicker
| 137,164 |
<p>You have to use the <code>change</code> event on the input itself if you want to respond to manual input, because the <code>changeDate</code> event is only for when the date is changed using the datepicker.</p>
<p>Try something like this:</p>
<pre><code>$(document).ready(function() {
$('.datepicker').datepicker({
format: "yyyy-mm-dd",
})
//Listen for the change even on the input
.change(dateChanged)
.on('changeDate', dateChanged);
});
function dateChanged(ev) {
$(this).datepicker('hide');
if ($('#startdate').val() != '' && $('#enddate').val() != '') {
$('#period').text(diffInDays() + ' d.');
} else {
$('#period').text("-");
}
}
</code></pre>
|
56,246,416 |
How can I configure NLog in .NET Core with appsettings.json instead of an nlog.config file?
|
<p>The NLog documentation explains how to configure NLog for .NET Core applications by using an <code>nlog.config</code> XML file. However, I'd prefer to have just one configuration file for my application - <code>appsettings.json</code>. For .NET Framework apps, it's possible to put the NLog configuration in <code>app.config</code> or <code>web.config</code>. Is it possible to put the NLog config in <code>appsettings.json</code> in the same way?</p>
<p>For example, how could I put this configuration example from the <a href="https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2" rel="noreferrer">NLog documentation for ASP.NET Core 2</a> into <code>appsettings.json</code>?</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\temp\internal-nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
</code></pre>
| 56,246,417 | 3 | 0 | null |
2019-05-21 21:10:35.907 UTC
| 10 |
2022-02-01 18:01:41.657 UTC
|
2019-05-21 21:19:52.273 UTC
| null | 2,457,005 | null | 2,457,005 | null | 1 | 23 |
asp.net-core|.net-core|configuration-files|nlog
| 29,827 |
<p>Yes, this is possible but has a minimum version requirement. You must be using <strong>NLog.Extensions.Logging >= 1.5.0</strong>. Note that for ASP.NET Core applications this will be installed as a dependency if you install <strong>NLog.Web.AspNetCore >= 4.8.2</strong>.</p>
<p>You can then create an <code>NLog</code> section in <code>appsettings.json</code> and load it with the following code:</p>
<pre class="lang-cs prettyprint-override"><code>var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
NLog.Config.LoggingConfiguration nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));
</code></pre>
<p>For example, for an ASP.NET Core application, your <code>Main()</code> method in <code>Program.cs</code> should look something like this:</p>
<pre class="lang-cs prettyprint-override"><code>public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));
var logger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();
try
{
logger.Debug("Init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "Stopped program because of exception");
}
finally {
LogManager.Shutdown();
}
}
</code></pre>
<p>A configuration like the one in the question can be achieved with the following settings in <code>appsettings.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>"NLog":{
"internalLogLevel":"Info",
"internalLogFile":"c:\\temp\\internal-nlog.txt",
"extensions": [
{ "assembly": "NLog.Extensions.Logging" },
{ "assembly": "NLog.Web.AspNetCore" }
],
"targets":{
"allfile":{
"type":"File",
"fileName":"c:\\temp\\nlog-all-${shortdate}.log",
"layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
},
"ownFile-web":{
"type":"File",
"fileName":"c:\\temp\\nlog-own-${shortdate}.log",
"layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}"
}
},
"rules":[
{
"logger":"*",
"minLevel":"Trace",
"writeTo":"allfile"
},
{
"logger":"Microsoft.*",
"maxLevel":"Info",
"final":"true"
},
{
"logger":"*",
"minLevel":"Trace",
"writeTo":"ownFile-web"
}
]
}
</code></pre>
<p><strong>Edit:</strong> Thanks to Rolf Kristensen (who developed this functionality for NLog in the first place!) for pointing out this wiki page with more documentation on this feature: <a href="https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json" rel="noreferrer">https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json</a></p>
|
56,275,425 |
Pandas: TypeError: '>' not supported between instances of 'int' and 'str' when selecting on date column
|
<p>I have a Pandas DataFrame with a column with TimeStamps. I can select date ranges from this column. But after I make change to other columns in the DataFrame, I can no longer and I get the error "TypeError: '>' not supported between instances of 'int' and 'str'".</p>
<p>The code below reproduce the problem: </p>
<ul>
<li>Generate a DataFrame with some random numbers</li>
<li>Add a column with dates</li>
<li><p>Select on the date column</p>
<pre><code>df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
print(df.loc[mask])
</code></pre></li>
</ul>
<p>All good:</p>
<pre><code> 0 1 2 date
153 0.280575 0.810817 0.534509 2000-06-02
154 0.490319 0.873906 0.465698 2000-06-03
155 0.070790 0.898340 0.390777 2000-06-04
156 0.896007 0.824134 0.134484 2000-06-05
157 0.539633 0.814883 0.976257 2000-06-06
158 0.772454 0.420732 0.499719 2000-06-07
159 0.498020 0.495946 0.546043 2000-06-08
160 0.562385 0.460190 0.480170 2000-06-09
161 0.924412 0.611929 0.459360 2000-06-10
</code></pre>
<p><em>However</em>, now I set column 0 to 0 if it exceeds 0.7 and repeat:</p>
<pre><code>df[df[0] > 0.7] = 0
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
</code></pre>
<p>This gives the error:</p>
<pre><code>TypeError: '>' not supported between instances of 'int' and 'str'
</code></pre>
<p>Why does this happen and how do I avoid it?</p>
| 56,275,604 | 3 | 0 | null |
2019-05-23 12:37:53.55 UTC
| 1 |
2021-12-23 12:06:02.307 UTC
|
2019-05-23 14:10:38.43 UTC
| null | 1,263,935 | null | 1,263,935 | null | 1 | 15 |
python|pandas
| 42,235 |
<p>You can compare a timestamp (<code>Timestamp('2000-01-01 00:00:00')</code>) to a string, pandas will convert the string to <code>Timestamp</code> for you. But once you set the value to <code>0</code>, you cannot compare an <code>int</code> to a <code>str</code>.</p>
<p>Another way to go around this is to change order of your operations.</p>
<pre><code>filters = df[0] > 0.7
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
df[filters] = 0
print(df.loc[mask & filters])
</code></pre>
<p>Also, you mentioned you want <em>to set column 0 to 0 if it exceeds 0.7</em>, so <code>df[df[0]>0.7] = 0</code> does not do exactly what you want: it sets the entire rows to <code>0</code>. Instead:</p>
<pre><code>df.loc[df[0] > 0.7, 0] = 0
</code></pre>
<p>Then you should not have any problem with the original mask.</p>
|
41,904,806 |
How to upload a file to S3 and make it public using boto3?
|
<p>I am able to upload an image file using:</p>
<pre><code>s3 = session.resource('s3')
bucket = s3.Bucket(S3_BUCKET)
bucket.upload_file(file, key)
</code></pre>
<p>However, I want to make the file public too. I tried looking up for some functions to set ACL for the file but seems like boto3 have changes their API and removed some functions. Is there a way to do it in the latest release of boto3?</p>
| 41,909,293 | 5 | 0 | null |
2017-01-27 23:45:09.767 UTC
| 17 |
2022-02-25 01:38:04.333 UTC
| null | null | null | null | 1,993,709 | null | 1 | 82 |
python|amazon-s3|boto|boto3
| 52,891 |
<p>I was able to do it using objectAcl API:</p>
<pre><code>s3 = boto3.resource('s3')
object_acl = s3.ObjectAcl('bucket_name','object_key')
response = object_acl.put(ACL='public-read')
</code></pre>
<p>For details: <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl" rel="noreferrer">http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl</a></p>
|
50,548,629 |
How to open an existing Flutter Project in Android Studio
|
<p>I might sound noob here but I can't see a clear way of opening existing Flutter Project in Android Studio <code>3.1.2</code>.</p>
<p>I checked <a href="https://stackoverflow.com/questions/49067999/flutter-how-to-import-existing-flutter-project-as-a-gradle-project">this</a> but it didn't work. So I want to know if there is a standard IDE way of doing this? I also can't find any docs clearly mentioning it. Do I need to install a 3rd party plugin?</p>
<p>After opening it as an Existing Android Studio Project, I get the following error:</p>
<p><a href="https://i.stack.imgur.com/9w72t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9w72t.png" alt="error"></a></p>
<p>The error is solved by running <code>Get Dependencies</code>. Is it a normal behavior?</p>
| 50,548,664 | 7 | 0 | null |
2018-05-27 02:51:00.09 UTC
| 1 |
2021-09-19 04:53:44.65 UTC
|
2018-05-27 03:09:53.627 UTC
| null | 7,337,723 | null | 7,337,723 | null | 1 | 23 |
android-studio|flutter
| 42,213 |
<ol>
<li><p>Install Flutter plugin for Android studio: <a href="https://flutter.io/get-started/editor/" rel="noreferrer">https://flutter.io/get-started/editor/</a></p></li>
<li><p>Open Android Studio</p></li>
<li><p>Open existing Android Studio project by using one of below methods:</p></li>
</ol>
<hr>
<p><strong>EASIEST WAY: Drag your project folder and drop to Android Studio.</strong></p>
<hr>
<p>Other ways:</p>
<p><a href="https://i.stack.imgur.com/ap05O.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ap05O.png" alt="Android Studio 1"></a></p>
<p><a href="https://i.stack.imgur.com/9Yg5l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Yg5l.png" alt="Android Studio 2"></a></p>
<p><a href="https://i.stack.imgur.com/aUTZo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aUTZo.png" alt="Android Studio 3"></a></p>
|
2,477,321 |
Sync GIT and ClearCase
|
<p>I am currently working on ClearCase and now migrating to GIT.
But we need this migration in a way that all work will be done in GIT and the data will be synced backed to ClearCase stream. We will have the same branch names and stream names in both GIT and CC, so scripting shouldn't be a problem. The problem here is,</p>
<p>Can someone suggest which is the best model to sync CC and GIT</p>
<ol>
<li><p>Have all the Vobs in CC as single repo in GIT, and have the major stream in CC as various branches in GIT. - Single GIT repo (VOBS) and many branches (CC streams). - This takes up less space as VOBs are kept as single repo with many branches.</p></li>
<li><p>Have important CC branches as independent GIT repositories and each repository having all the CC VOBs. - Many GIT repo for many CC branch - This will take up lots of space as VOBs will be replicated across.</p></li>
</ol>
<p>Which do you think is the best way to keep it in sync with ClearCase</p>
| 2,478,707 | 3 | 0 | null |
2010-03-19 12:45:44.14 UTC
| 10 |
2016-08-12 14:29:48.65 UTC
| null | null | null | null | 289,715 | null | 1 | 13 |
git|clearcase|git-branch
| 19,141 |
<blockquote>
<p>Have all the Vobs in CC as single repo in GIT, and have the major stream in CC as various branches in GIT</p>
</blockquote>
<p>No and yes</p>
<blockquote>
<p>Have important CC branches as independent GIT repositories and each repository having all the CC VOBs</p>
</blockquote>
<p>No and No</p>
<p>Re-reading <a href="https://stackoverflow.com/questions/984707/what-are-the-git-limits/984973#984973">my answer about <strong>Git limits</strong></a>, you shouldn't try to cram "everything" in a Git repo.<br>
See also "<a href="https://stackoverflow.com/questions/645008/what-are-the-basic-clearcase-concepts-every-developer-should-know/645771#645771">What are the basic clearcase concepts every developer should know?</a>" for a comparison between ClearCase and Git.</p>
<p>Stream can safely be imported as branch.<br>
But VOBs are not necessarily a Git Repo.</p>
<p>If you are using UCM, I would recommend one Git repo per UCM component.</p>
<p>Anyway, you need to record in your Git Repo a way to know what ClearCase view to use to sync back (through a <a href="https://stackoverflow.com/questions/138321/how-can-i-use-clearcase-to-add-to-source-control-recursively/144310#144310">simple <code>clearfsimport</code></a>) your data.<br>
The view used for that ClearCase data re-import will be a UCM view automatically associated to the right stream, for the right VOB.</p>
<hr>
<p>Note: I mention in "<a href="https://stackoverflow.com/questions/2342131/how-to-bridge-git-to-clearcase/2342164#2342164">How to bridge git to ClearCase?</a>" a simpler solution, but which does not import the <em>all</em> history in a Git repo.</p>
|
3,105,003 |
Literal does not match format string for Oracle SQL to_date on a string column
|
<p>Dear SQL Gurus from Stack Overflow:</p>
<p><strong>Environment:</strong> Oracle</p>
<p>I'm trying to understand why I can't do a to_date selection on a table column that contains strings. Note tableZ with a column of name Value in the example below contains a bunch of strings, some of which are the correct format, for example 6/20/2010 00:00:00.</p>
<p>tableZ </p>
<pre><code>| Value |
| __________________ |
| 6/21/2010 00:00:00 |
| Somestring |
| Some Other strings |
| 6/21/2010 00:00:00 |
| 6/22/2010 00:00:00 |
</code></pre>
<p><strong>The following works</strong></p>
<pre><code>SELECT To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') somedate
FROM tableX a, tableY b, tableZ c
WHERE Lower(a.name) = 'somedate'
AND a.id = b.other_id
AND b.id = c.new_id
</code></pre>
<p>This returns something like (which is good):</p>
<pre><code>| somedate |
| __________________ |
| 21.06.2010 00:00:00 |
| 21.06.2010 00:00:00 |
| 22.06.2010 00:00:00 |
</code></pre>
<p><strong>The following does not work</strong></p>
<pre><code>SELECT To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') somedate
FROM properties$aud a, template_properties$aud b, consumable_properties$aud c
WHERE Lower(a.name) = 'somedate'
AND a.id = b.property_id
AND b.id = c.template_property_id
AND To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') IS NOT NULL
</code></pre>
<p>Comes back with:</p>
<p><strong><em>ORA-01861: literal does not match format string</em></strong></p>
<p>What am I missing here? Just a quick note:</p>
<pre><code> ...
AND b.id = c.template_property_id
AND To_Date(c.Value, 'DD.MM.YYYY HH24:MI:SS') IS NOT NULL
</code></pre>
<p>doesn't work either.</p>
<p>Thanks!!</p>
<p><strong>Goal</strong> to be able to do date BETWEEN queries on c.value in order to select date ranges.</p>
| 3,105,218 | 4 | 0 | null |
2010-06-23 19:50:06.7 UTC
| null |
2013-11-27 10:16:57.18 UTC
| null | null | null | null | 129,735 | null | 1 | 6 |
sql|oracle|datetime|to-date
| 46,320 |
<p>The order that Oracle evaluates the conditions found in the where clause is not fixed. That is to say that it can choose to evaluate the condition containing TO_DATE before the other criteria, in which case the query will fail. To prevent that, add the ordered_predicates hint to your query, but be aware that this may require additional manual tuning to improve performance.</p>
<pre><code>SELECT /*+ ordered_predicates */
To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') somedate
FROM properties$aud a,
template_properties$aud b,
consumable_properties$aud c
WHERE Lower(a.name) = 'somedate'
AND a.id = b.property_id
AND b.id = c.template_property_id
AND To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') IS NOT NULL
</code></pre>
<hr>
<p>Apparently <code>ordered_predicates</code> is deprecated starting with 10g. In that case, I think your only option is to use a sub-query in such a way that optimizer is forced to evaluate it first (i.e. it can't combine the queries). The easiest way to do this is to put <code>rownum</code> in the where statement of the inner query.</p>
<pre><code>SELECT To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') somedate
FROM (SELECT value
FROM properties$aud a,
template_properties$aud b,
consumable_properties$aud c
WHERE Lower(a.name) = 'somedate'
AND a.id = b.property_id
AND b.id = c.template_property_id
AND rownum > 0)
WHERE To_Date(c.Value, 'MM/DD/YYYY HH24:MI:SS') IS NOT NULL
</code></pre>
|
2,877,436 |
How can I ask Maven for a list of the default repositories?
|
<p>What command can I use to ask Maven for a list of the default repositories that it searches for its dependencies? If no such command exists, where else may I look to find this default list?</p>
| 2,878,312 | 4 | 0 | null |
2010-05-20 20:11:31.757 UTC
| 7 |
2018-11-22 12:34:18.717 UTC
|
2010-07-27 10:28:17.13 UTC
| null | 342,852 | null | 107,158 | null | 1 | 32 |
java|maven-2|build-process
| 26,751 |
<p>on the command line, execute</p>
<pre><code>mvn help:evaluate
</code></pre>
<p>then, when prompted, enter</p>
<pre><code>${project.repositories}
</code></pre>
<p>see <a href="http://maven.apache.org/plugins/maven-help-plugin/evaluate-mojo.html" rel="noreferrer">http://maven.apache.org/plugins/maven-help-plugin/evaluate-mojo.html</a></p>
|
2,618,989 |
How can I remove my last commit in my local git repository
|
<p>When I do a 'git pull', I have conflict with the head commit. So I did a 'git rebase --abort'</p>
<p>Can I 'save' my commit to a "patch" and then do a git pull?</p>
<p>What I want to emulate is:</p>
<ul>
<li>I did not commit, but I did a 'git stash' instead</li>
<li>Do a git pull to avoid any merge error</li>
</ul>
<p>So I need somehow to 'turn back the clock'. Is that possible with git?</p>
| 2,619,068 | 4 | 0 | null |
2010-04-11 22:44:23.127 UTC
| 19 |
2016-01-12 19:40:17.317 UTC
|
2016-01-12 19:40:17.317 UTC
| null | 1,139,725 | null | 286,802 | null | 1 | 36 |
git
| 52,142 |
<p>Your <code>7826b2</code> patch will still cause a conflict when it's applied after pulling, but you can do the following:</p>
<pre><code>git reset --soft HEAD^
git stash
git pull
git stash pop # Will cause a conflict
git commit # Re-commit 7826b2
</code></pre>
<p>Another workflow is also possible:</p>
<pre><code>git reset --hard HEAD^
git pull
git cherry-pick 7826b2 # Will cause a conflict
</code></pre>
<p>The second workflow relies on the fact that Git keeps the <code>7826b2</code> commit in the reflog (you can think of it as the recycle bin) even though you reset the changes it introduced with the first line.</p>
|
31,909,664 |
Display phone numbers as left-to-right in right-to-left language
|
<p>I have a display of a users contact details where the user can alternate the display between left-to-right and right-to-left text.</p>
<p><em>In the Arabic language, the text is displayed and read from right-to-left, but phone numbers, web addresses and email addresses are displayed and read left-to-right in Arabic and other right-to-left languages.</em></p>
<p>I have been able to alternate the display of the users contact details, but the phone numbers do not display left-to-right when there is a space in the phone number. Here is a visual display of the issue I have:</p>
<p>The following is the left-to-right display in the English language:
<a href="https://i.stack.imgur.com/0Cko1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0Cko1.png" alt="enter image description here"></a></p>
<p>Here is the same details as above but displayed right-to-left in the Arabic language (the phone numbers (in the lime colour) have spaces and are <strong>not</strong> displayed correctly):</p>
<p><a href="https://i.stack.imgur.com/FV2o9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FV2o9.png" alt="enter image description here"></a></p>
<p>Here is the same details again, displayed right-to-left in the Arabic language, but with spaces eliminated from the phone numbers (the phone numbers (in the lime colour) are displayed correctly here):</p>
<p><a href="https://i.stack.imgur.com/kbWOK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kbWOK.png" alt="enter image description here"></a></p>
<p><strong>Does anyone know how to display the phone numbers with spaces in them as left-to-right when in a right-to-left language?</strong></p>
<p>Here is my HTML code:</p>
<pre><code><div class="row contact_reverse">
{{ #if contact_details_phone }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-phone icon_size20 icon_padding_rtl"></i><span class="contact_dir_reverse">{{ contact_details_phone }}</span>
</div>
{{ /if }}
{{ #if contact_details_mobile_phone }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-tablet icon_size20 icon_padding_rtl"></i><span class="contact_dir_reverse">{{ contact_details_mobile_phone }}</span>
</div>
{{ /if }}
{{ #if contact_details_email_address }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-envelope icon_size20 icon_padding_rtl"></i>{{ contact_details_email_address }}
</div>
{{ /if }}
{{ #if contact_details_linkedin_address }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-linkedin icon_size20 icon_padding_rtl"></i><span class="btu-link">{{ contact_details_linkedin_address }}</span>
</div>
{{ /if }}
{{ #if contact_details_facebook_address }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-facebook icon_size20 icon_padding_rtl"></i><span class="btu-link">{{ contact_details_facebook_address }}</span>
</div>
{{ /if }}
{{ #if contact_details_twitter_address }}
<div class="col-sm-4 col-md-4 col-lg-4 ellipsis contact_reverse" dir="rtl" style="direction: rtl;">
<i class="fa fa-twitter icon_size20 icon_padding_rtl"></i><span class="btu-link">{{ contact_details_twitter_address }}</span>
</div>
{{ /if }}
</div>
</code></pre>
<p>Here is my CSS code:</p>
<pre><code>.contact_reverse {
background-color: red;
-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.icon_size20 {
font-size: 20px !important;
}
.icon_padding_rtl {
padding-left: 6px !important;
background-color: peru;
}
.contact_dir_reverse {
background-color: lime;
direction: ltr;
}
</code></pre>
| 31,909,788 | 3 | 0 | null |
2015-08-09 23:03:11.983 UTC
| 8 |
2021-12-10 00:06:37.277 UTC
| null | null | null | null | 1,261,774 | null | 1 | 20 |
html|css|right-to-left|left-to-right
| 10,627 |
<p>I just figured this out!</p>
<p>I added the <code>unicode-bidi: embed;</code> to the <code>contact_dir_reverse</code> css class, like so:</p>
<pre><code>.contact_dir_reverse {
background-color: lime;
direction: ltr;
unicode-bidi: embed;
}
</code></pre>
<p>I hope that this will help someone.</p>
|
32,029,094 |
how to make <svg> 100% width
|
<p>I am trying to make this <code><svg></code> element stretch to 100% of the screen width:</p>
<pre><code> <svg height="100" width="100">
<path d="M0 0 L100 0 L50 100 Z" />
</svg>
</code></pre>
<p>What do I need to do?</p>
| 32,029,371 | 1 | 0 | null |
2015-08-15 20:35:10.443 UTC
| 5 |
2018-12-18 10:06:17.19 UTC
|
2018-12-18 10:06:17.19 UTC
| null | 63,810 | null | 5,180,453 | null | 1 | 23 |
html|svg
| 39,106 |
<p>The viewBox defines the co-ordinates you can see. Height and width define the size of the SVG. E.g.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
width: 100%;
height: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg height="100%" width="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
<path d="M0 0 L100 0 L50 100 Z" />
</svg></code></pre>
</div>
</div>
</p>
|
31,943,989 |
Spring Data JPA And NamedEntityGraphs
|
<p>currently I am wrestling with being able to fetch only the data I need. The findAll() method needs to fetch data dependant on where its getting called.
I do not want to end up writing different methods for each entity graph.
Also, I would avoid calling entitymanagers and forming the (repetitive) queries myself.
Basicly I want to use the build in findAll method, but with the entity graph of my liking. Any chance?</p>
<pre><code>@Entity
@Table(name="complaints")
@NamedEntityGraphs({
@NamedEntityGraph(name="allJoinsButMessages", attributeNodes = {
@NamedAttributeNode("customer"),
@NamedAttributeNode("handling_employee"),
@NamedAttributeNode("genre")
}),
@NamedEntityGraph(name="allJoins", attributeNodes = {
@NamedAttributeNode("customer"),
@NamedAttributeNode("handling_employee"),
@NamedAttributeNode("genre"),
@NamedAttributeNode("complaintMessages")
}),
@NamedEntityGraph(name="noJoins", attributeNodes = {
})
})
public class Complaint implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private long id;
private Timestamp date;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer")
private User customer;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "handling_employee")
private User handling_employee;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="genre")
private Genre genre;
private boolean closed;
@OneToMany(mappedBy = "complaint", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<ComplaintMessage> complaintMessages = new ArrayList<ComplaintMessage>();
//getters and setters
}
</code></pre>
<p>And my JPARepository</p>
<pre><code>@Repository
public interface ComplaintRepository extends JpaRepository<Complaint, Long>{
List<Complaint> findByClosed(boolean closed);
@EntityGraph(value = "allJoinsButMessages" , type=EntityGraphType.FETCH)
@Override
List<Complaint> findAll(Sort sort);
}
</code></pre>
| 33,373,905 | 6 | 1 | null |
2015-08-11 14:03:07.6 UTC
| 22 |
2021-06-28 19:04:55.75 UTC
| null | null | null | null | 3,540,120 | null | 1 | 58 |
jpa|fetch|spring-data-jpa|entitygraph
| 52,527 |
<p>We ran into a similar problem and devised several prospective solutions but there doesn't seem to be an elegant solution for what seems to be a common problem.</p>
<p>1) Prefixes. Data jpa affords several prefixes (find, get, ...) for a method name. One possibility is to use different prefixes with different named graphs. This is the least work but hides the meaning of the method from the developer and has a great deal of potential to cause some non-obvious problems with the wrong entities loading. </p>
<pre><code>@Repository
@Transactional
public interface UserRepository extends CrudRepository<User, Integer>, UserRepositoryCustom {
@EntityGraph(value = "User.membershipYearsAndPreferences", type = EntityGraphType.LOAD)
User findByUserID(int id);
@EntityGraph(value = "User.membershipYears", type = EntityGraphType.LOAD)
User readByUserId(int id);
}
</code></pre>
<p>2) CustomRepository. Another possible solutions is to create custom query methods and inject the EntityManager. This solution gives you the cleanest interface to your repository because you can name your methods something meaningful, but it is a significant amount of complexity to add to your code to provide the solution AND you are manually grabbing the entity manager instead of using Spring magic.</p>
<pre><code>interface UserRepositoryCustom {
public User findUserWithMembershipYearsById(int id);
}
class UserRepositoryImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public User findUserWithMembershipYearsById(int id) {
User result = null;
List<User> users = em.createQuery("SELECT u FROM users AS u WHERE u.id = :id", User.class)
.setParameter("id", id)
.setHint("javax.persistence.fetchgraph", em.getEntityGraph("User.membershipYears"))
.getResultList();
if(users.size() >= 0) {
result = users.get(0);
}
return result;
}
}
@Repository
@Transactional
public interface UserRepository extends CrudRepository<User, Integer>, UserRepositoryCustom {
@EntityGraph(value = "User.membershipYearsAndPreferences", type = EntityGraphType.LOAD)
User findByUserID(int id);
}
</code></pre>
<p>3) JPQL. Essentially this is just giving up on named entity graphs and using JPQL to handle your joins for you. Non-ideal in my opinion.</p>
<pre><code>@Repository
@Transactional
public interface UserRepository extends CrudRepository<User, Integer>, UserRepositoryCustom {
@EntityGraph(value = "User.membershipYearsAndPreferences", type = EntityGraphType.LOAD)
User findByUserID(int id);
@Query("SELECT u FROM users WHERE u.id=:id JOIN??????????????????????????")
User findUserWithTags(@Param("id") final int id);
}
</code></pre>
<p>We went with option 1 because it is the simplest in implementation but this does mean when we use our repositories we have have to look at the fetch methods to make sure we are using the one with the correct entity graph. Good luck.</p>
<p>Sources:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/31216971/jpa-entitygraph-with-different-views-using-spring">JPA EntityGraph with different views using Spring</a></li>
<li><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods" rel="noreferrer">https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods</a></li>
</ul>
<p>I don't have enough reputation to post all of my sources. Sorry :(</p>
|
28,417,140 |
Styling default JavaFX Dialogs
|
<p>I'm looking for a way to style the default JavaFX Dialog (<code>javafx.scene.control.Dialog</code>). </p>
<p>I tried to get the DialogPane and add a stylesheet, but it covers only a small piece of the dialog. I would prefer to style only with an external css file and without to add styleClasses over the code. This would look messy (header, content, own content on the content and more..)</p>
<p>I googled already alot and only found examples for ControlsFX, but since jdk8_40 JavaFX has it's own Dialogs i use them now. </p>
<p>Any suggestions?</p>
<p><strong>Edit:</strong></p>
<p>Since José Pereda posted the solution i created my own dialog.css.
I'll post it here because it covers the whole dialog and maybe someone want's to copy&paste it. Note .dialog-pane is already a given styleClass name so you don't need to apply your own. Of course, Josés is more fine detailed.</p>
<pre><code>.dialog-pane {
-fx-background-color: black;
}
.dialog-pane .label {
-fx-text-fill: white;
}
.dialog-pane:header .header-panel {
-fx-background-color: black;
}
.dialog-pane:header .header-panel .label {
-fx-font-style: italic;
-fx-font-size: 2em;
}
</code></pre>
| 28,421,229 | 1 | 0 | null |
2015-02-09 18:53:16.56 UTC
| 11 |
2016-12-22 16:21:17.04 UTC
|
2016-12-22 16:21:17.04 UTC
| null | 1,266,705 | null | 1,266,705 | null | 1 | 35 |
javafx|dialog|javafx-8
| 41,385 |
<p>You can style your dialogs with your own css file, but for that you need to take into consideration that the dialog is in fact a new stage, with a new scene, and the root node is a <code>DialogPane</code> instance.</p>
<p>So once you create some dialog instance:</p>
<pre><code>@Override
public void start(Stage primaryStage) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("This is a Custom Confirmation Dialog");
alert.setContentText("We override the style classes of the dialog");
...
}
</code></pre>
<p>you can access to its dialog pane and add your own style sheet and your own class selector:</p>
<pre><code>DialogPane dialogPane = alert.getDialogPane();
dialogPane.getStylesheets().add(
getClass().getResource("myDialogs.css").toExternalForm());
dialogPane.getStyleClass().add("myDialog");
</code></pre>
<p>Now the trick is knowing all the rules a <code>Dialog</code> style sheet has implemented by default.</p>
<p>And that's a difficult task... since they are not in the <code>modena.css</code> file, as for all the regular controls. On the contrary, they are found in the <code>modena.bss</code> file, a binary file located in the jfxrt.jar under private packages.</p>
<p>After some digging I've managed to get those rules, so your custom <code>myDialogs.css</code> file will look something like this:</p>
<pre><code>.myDialog{
-fx-background-color: #f9d900;
}
.myDialog > *.button-bar > *.container{
-fx-background-color: #a9e200;
}
.myDialog > *.label.content{
-fx-font-size: 14px;
-fx-font-weight: bold;
}
.myDialog:header *.header-panel{
-fx-background-color: #a59c31;
}
.myDialog:header *.header-panel *.label{
-fx-font-size: 18px;
-fx-font-style: italic;
-fx-fill: #292929;
}
</code></pre>
<p>And you will have your styled dialog:</p>
<p><img src="https://i.stack.imgur.com/y6yJm.png" alt="Styled dialog"></p>
<p><del>Note that being a bss file under private packages, these selectors can change without notice in future releases.</del></p>
<p><strong>EDIT</strong></p>
<p>I've just found that the <code>.dialog-pane</code> selector is already part of <a href="http://hg.openjdk.java.net/openjfx/8u40/rt/file/6cc08ec1ea82/modules/controls/src/main/resources/com/sun/javafx/scene/control/skin/modena/modena.css">modena.css</a> in the last 8u40 <a href="https://jdk8.java.net/download.html">early versions</a>, so you can find all the selectors and rules applied to the dialog pane there.</p>
|
51,389,042 |
Difference between auto_now and auto_now_add
|
<p>What I understood in <code>Django</code> models field's attributes is </p>
<ul>
<li><code>auto_now</code> - updates the value of field to current time and date every time the Model.save() is called.</li>
<li><code>auto_now_add</code> - updates the value with the time and date of creation of record.</li>
</ul>
<p>My question is what if a filed in model contains both the <code>auto_now</code> and <code>auto_now_add</code> set to True? What happens in that case?</p>
| 51,389,274 | 5 | 0 | null |
2018-07-17 19:38:08.173 UTC
| 7 |
2021-11-10 09:04:06.903 UTC
|
2019-07-04 13:59:05.767 UTC
| null | 4,626,254 | null | 10,095,725 | null | 1 | 69 |
python|django|django-models|django-forms|django-templates
| 36,014 |
<p><code>auto_now</code> takes precedence (obviously, because it updates field each time, while <code>auto_now_add</code> updates on creation only). Here is the code for <a href="https://docs.djangoproject.com/en/2.0/_modules/django/db/models/fields/#DateField" rel="noreferrer"><code>DateField.pre_save</code></a> method:</p>
<pre><code>def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.date.today()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
</code></pre>
<p>As you can see, if <code>auto_now</code> is set or both <code>auto_now_add</code> is set and the object is new, the field will receive current day.</p>
<p>The same for <a href="https://docs.djangoproject.com/en/2.0/_modules/django/db/models/fields/#DateTimeField" rel="noreferrer"><code>DateTimeField.pre_save</code></a>:</p>
<pre><code>def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
</code></pre>
|
38,387,125 |
How do I make a fetch request using NSManagedObject's new fetchRequest function?
|
<p>In iOS 10 the CoreData team added a new "fetchRequest" method to NSManagedObject. It looks like this:</p>
<pre><code>public class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>
</code></pre>
<p>Which, from what I understand, allows us to replace this:</p>
<pre><code>let request = NSFetchRequest<MyEntity>(entityName: "MyEntity")
</code></pre>
<p>with this:</p>
<pre><code>let request = MyEntity.fetchRequest()
</code></pre>
<p>However, when I try to make a simple request like this:</p>
<pre><code>let request = MyEntity.fetchRequest()
do {
results = try request.execute()
} catch let error {
print("failed to fetch coffee object: \(error)")
}
</code></pre>
<p>I receive the following error:</p>
<blockquote>
<p>Error Domain=NSCocoaErrorDomain Code=134060 "(null)"
UserInfo={message=Cannot fetch without an NSManagedObjectContext in
scope}</p>
</blockquote>
<p>So, clearly the error is stating that I need to bring an NSManagedObjectContext into scope. I've been looking for examples but can seem to find a full example of how to perform a request using the new API features. </p>
<h2>Question</h2>
<p>Using the latest Core Data API features, how do I make a simple fetch request? The underlying question is how do I bring my NSmanagedObjectCotnext into scope.</p>
<p>I should note that I am able to successfully make a request using the traditional syntax.</p>
| 38,387,472 | 2 | 0 | null |
2016-07-15 02:46:39.617 UTC
| 4 |
2017-01-24 07:45:57.92 UTC
| null | null | null | null | 1,664,443 | null | 1 | 30 |
ios|core-data|nsfetchrequest|swift3|xcode8-beta2
| 15,815 |
<p>Ok, I figured out two ways of doing this. The <strong>first approach</strong>, which is similar to my example code is just simply:</p>
<pre><code>var moc: NSManagedObjectContext!
let request = MyEntity.fetchRequest()
var results : [MyEntity]
do {
results = try moc.fetch(request)
} catch { // error stuff}
</code></pre>
<p>The <strong>second approach</strong>, which was shown in WWDC 2016 uses a function named "execute" on our fetch request object.</p>
<p>If you view the details on NSFetchRequest you'll see a comment that clearly states that the operation must be performed with in a block. </p>
<pre><code> // Executes the fetch request using the current managed object context. This method must be called from within a block submitted to a managed object context.
@available(iOS 10.0, *)
public func execute() throws -> [ResultType]
</code></pre>
<p>It's dawned on me that this was the way to perform the fetch:</p>
<pre><code>var moc: NSManagedObjectContext!
let request = MyEntity.fetchRequest()
var results : [MyEntity]
moc.perform {
self.results = try! request.execute()
}
</code></pre>
<p><strong>For those who roll their own</strong></p>
<p>If you are rolling your own code you may find that your code does not compile. Included in the auto-generated code is a new method called fetchRequest that the compiler uses to pass the type along. Here's what the code looks like.</p>
<pre><code>@nonobjc public class func fetchRequest() -> NSFetchRequest<MyEntity> {
return NSFetchRequest<MyEntity>(entityName: "MyEntity");
}
</code></pre>
|
470,040 |
boost::bind with functions that have parameters that are references
|
<p>I noticed that when passing reference parameters to boost bind, those parameters won't act like references. Instead boost creates another copy of the member and the original passed in variable remains unchanged. </p>
<p>When I change the references to pointers, everything works ok.</p>
<p>My question is:</p>
<p>Is it possible to get references to work, or at least give a compiling error when it tries to use reference parameters?</p>
| 470,053 | 2 | 0 | null |
2009-01-22 17:19:34.45 UTC
| 4 |
2014-01-13 18:18:14.433 UTC
|
2009-07-11 18:49:28.973 UTC
| null | 95,735 |
Brian R. Bondy
| 3,153 | null | 1 | 31 |
c++|boost-bind
| 23,207 |
<p>The <a href="http://www.boost.org/doc/libs/1_37_0/libs/bind/bind.html#with_functions" rel="noreferrer">boost documentation for bind</a> suggests that you can use boost::ref and boost::cref for this.</p>
|
2,636,068 |
Hide cursor in Chrome (and IE)
|
<p>I have the following CSS that hides the mouse cursor for anything on the web page. It works perfectly in Firefox, but in IE and Chrome, it doesn't work.</p>
<pre><code>html {
cursor: none;
}
</code></pre>
<p>In Chrome, I always see the mouse pointer. In IE, however, I see whatever cursor was last 'active' when it entered the screen. Presumably it's keeping the last selection instead of removing it.</p>
| 2,636,106 | 6 | 7 | null |
2010-04-14 08:55:52.397 UTC
| 6 |
2021-12-23 15:42:47.293 UTC
|
2021-12-23 15:42:47.293 UTC
| null | 4,294,399 | null | 94,278 | null | 1 | 18 |
html|css|mouse-cursor
| 38,117 |
<p>This property <code>cursor:none;</code> isn't part of the standard</p>
<p>See here <a href="http://www.w3schools.com/css/pr_class_cursor.asp" rel="noreferrer">w3c cursor CSS properties</a>.</p>
<p>You might want to look into hiding it with Javascript or JQuery.</p>
<p>Also, look at blank cursor files <a href="http://pc.autons.net/stuff/blanks/" rel="noreferrer">here</a>.</p>
<p>And one last link to an <a href="http://www.ajaxblender.com/howto-create-custom-image-cursors.html" rel="noreferrer">ajax solution</a>.</p>
<p>Chrome has had this issue since it was built, there have been reports sent to the people at <a href="http://code.google.com/chromium/" rel="noreferrer">Chromium</a>, and I assume they are working on it.</p>
<p>Also, don't trust that anything would work in IE. Ever. :P</p>
|
2,578,930 |
Understanding this matrix transposition function in Haskell
|
<p>This matrix transposition function works, but I'm trying to understand its step by step execurtion and I don't get it.</p>
<pre><code> transpose:: [[a]]->[[a]]
transpose ([]:_) = []
transpose x = (map head x) : transpose (map tail x)
</code></pre>
<p>with </p>
<pre><code>transpose [[1,2,3],[4,5,6],[7,8,9]]
</code></pre>
<p>it returns:</p>
<pre><code> [[1,4,7],[2,5,8],[3,6,9]]
</code></pre>
<p>I don't get how the concatenation operator is working with map. It is concatenating each head of x in the same function call? How?</p>
<p>is this </p>
<pre><code>(map head x)
</code></pre>
<p>creating a list of the head elements of each list?</p>
| 2,578,979 | 7 | 1 | null |
2010-04-05 14:40:11.077 UTC
| 3 |
2022-06-22 15:15:37.27 UTC
|
2011-04-18 23:31:11.383 UTC
| null | 83,805 | null | 45,963 | null | 1 | 30 |
algorithm|list|haskell
| 19,844 |
<p>Let's look at what the function does for your example input:</p>
<pre><code>transpose [[1,2,3],[4,5,6],[7,8,9]]
<=>
(map head [[1,2,3],[4,5,6],[7,8,9]]) : (transpose (map tail [[1,2,3],[4,5,6],[7,8,9]]))
<=>
[1,4,7] : (transpose [[2,3],[5,6],[8,9]])
<=>
[1,4,7] : (map head [[2,3],[5,6],[8,9]]) : (transpose (map tail [[2,3],[5,6],[8,9]]))
<=>
[1,4,7] : [2,5,8] : (transpose [[3],[6],[9]])
<=>
[1,4,7] : [2,5,8] : (map head [[3],[6],[9]]) : (transpose (map tail [[3],[6],[9]]))
<=>
[1,4,7] : [2,5,8] : [3, 6, 9] : (transpose [[], [], []])
<=>
[1,4,7] : [2,5,8] : [3, 6, 9] : [] -- because transpose ([]:_) = []
<=>
[[1,4,7],[2,5,8],[3,6,9]]
</code></pre>
<p>Note that the order in which I chose to reduce the terms, is not the same as the evaluation order haskell will use, but that does not change the result.</p>
<p>Edit: In response to your edited question:</p>
<blockquote>
<p>is this</p>
<pre><code>(map head x)
</code></pre>
<p>creating a list of the head elements of each list?</p>
</blockquote>
<p>Yes, it is.</p>
|
2,932,421 |
Detect if a method was overridden using Reflection (C#)
|
<p>Say I have a base class TestBase where I define a virtual method TestMe()</p>
<pre><code>class TestBase
{
public virtual bool TestMe() { }
}
</code></pre>
<p>Now I inherit this class:</p>
<pre><code>class Test1 : TestBase
{
public override bool TestMe() {}
}
</code></pre>
<p>Now, using Reflection, I need to find if the method TestMe has been overriden in child class - is it possible? </p>
<p>What I need it for - I am writing a designer visualizer for type "object" to show the whole hierarchy of inheritance and also show which virtual methods were overridden at which level.</p>
| 2,932,448 | 9 | 1 | null |
2010-05-28 20:47:28.133 UTC
| 17 |
2022-08-31 12:40:03.273 UTC
|
2013-08-24 13:13:30.44 UTC
| null | 126,014 | null | 151,200 | null | 1 | 63 |
c#|reflection|overriding
| 27,793 |
<p>Given the type <code>Test1</code>, you can determine whether it has its own <strike>implementation</strike> declaration of <code>TestMe</code>:</p>
<pre><code>typeof(Test1).GetMethod("TestMe").DeclaringType == typeof(Test1)
</code></pre>
<p>If the declaration came from a base type, this will evaluate false.</p>
<p>Note that since this is testing declaration, not true implementation, this <em>will</em> return true if <code>Test1</code> is also abstract and <code>TestMe</code> is abstract, since <code>Test1</code> would have its own declaration. If you want to exclude that case, add <code>&& !GetMethod("TestMe").IsAbstract</code></p>
|
25,230,812 |
When should I use Docker's container name?
|
<p>When I ran <code>docker ps -a</code>, I got</p>
<pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e3be2faeb751 centos:latest touch /var/log/test 2 minutes ago Exited (1) 2 minutes ago insane_kirch6
</code></pre>
<p>What is the name, <em>insane_kirch6</em>, for?</p>
| 25,231,029 | 3 | 0 | null |
2014-08-10 16:42:15.02 UTC
| 9 |
2021-02-22 16:55:25.553 UTC
|
2019-11-17 23:05:18.83 UTC
| null | 63,550 | null | 1,254,250 | null | 1 | 72 |
docker
| 79,287 |
<p>You can name your own containers with <code>--name</code> when you use <code>docker run</code>. If you do not provide a name, Docker will generate a random one like the one you have.</p>
<p>Check their documentation for naming at <em><a href="https://docs.docker.com/network/links/#the-importance-of-naming" rel="noreferrer">Legacy container links, The importance of naming</a></em></p>
|
23,587,862 |
How to get all elements into list or string with Selenium using C#?
|
<p>I've tried using WebElement (and IWebElement) and string lists, but I keep getting errors. How can I get a list or strings of all the elements text by classname? I have all Selenium references. Do I need some java.util dll? </p>
<p>Should I implement a foreach loop?</p>
<pre><code>IList<IWebElement> all = new IList<IWebElement>();
all = driver.FindElements(By.ClassName("comments")).Text;
</code></pre>
<p>Error: Cannot create an instance of the abstract class or interface 'System.Collections.Generic.IList'</p>
<p>Error: 'System.Collections.ObjectModel.ReadOnlyCollection' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type</p>
| 23,587,903 | 5 | 0 | null |
2014-05-11 01:00:30.437 UTC
| 2 |
2017-04-02 10:59:14.437 UTC
|
2017-04-02 10:59:14.437 UTC
| null | 617,450 | null | 3,609,872 | null | 1 | 6 |
c#|list|selenium|selenium-webdriver
| 71,293 |
<p>You can get all of the element text like this:</p>
<pre><code>IList<IWebElement> all = driver.FindElements(By.ClassName("comments"));
String[] allText = new String[all.Count];
int i = 0;
foreach (IWebElement element in all)
{
allText[i++] = element.Text;
}
</code></pre>
|
6,087,716 |
Setting CSS position using Javascript
|
<p>How to set <code>relative 50% 50%</code> position using JS?</p>
<p>I tried:</p>
<pre><code>document.getElementById("id").style.position = "relative 50% 50%";
</code></pre>
<p>but it don't seems to work...</p>
| 6,087,730 | 2 | 1 | null |
2011-05-22 11:46:24.03 UTC
| 1 |
2015-08-27 05:55:56.823 UTC
| null | null | null | null | 746,841 | null | 1 | 10 |
javascript|css
| 48,538 |
<p>You have to set them individually.</p>
<p>I made a variable to point to the <code>style</code> object, because we are modifying more than one property and because <code>with() { ... }</code> is <a href="http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/" rel="noreferrer">considered harmful</a>.</p>
<p>Also, I set the <code>50%</code> to both properties because of right to left assignment, and because assignment of this string to the two properties isn't a problem (make sure you understand how this works, e.g. <code>var a = b = []</code> will set <code>a</code> and <code>b</code> to the <strong>same</strong> <code>Array</code> object, often not desired).</p>
<pre><code>var elementStyle = document.getElementById("id").style;
elementStyle.position = "relative";
elementStyle.top = elementStyle.left = "50%";
</code></pre>
<p><a href="http://jsfiddle.net/alexdickson/J4qEu/" rel="noreferrer">jsFiddle</a>.</p>
|
5,744,694 |
Extract matrix column values by matrix column name
|
<p>Is it possible to get a matrix column by name from a matrix?</p>
<p>I tried various approaches such as <code>myMatrix["test", ]</code> but nothing seems to work.</p>
| 5,744,722 | 2 | 0 | null |
2011-04-21 13:20:52.177 UTC
| 11 |
2018-06-20 11:22:28.137 UTC
|
2018-06-20 11:22:28.137 UTC
| null | 680,068 | null | 356,790 | null | 1 | 53 |
r|matrix|subset
| 144,603 |
<p>Yes. But place your "test" after the comma if you want the column...</p>
<pre><code>> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
</code></pre>
<p>see also <code>help(Extract)</code></p>
|
31,381,992 |
Java equivalent of Where Clause in C# Linq
|
<p>I can do this in C# : </p>
<pre><code>int CheetahNumber = 77;
Animal Cheetah = Model.Animals
.Where(e => e.AnimalNo.Equals(CheetahNumber))
.FirstOrDefault();
</code></pre>
<p>For example in Java I have <code>ArrayList<Animal> Animals</code></p>
<p>How can I query such an ArrayList? Thanks.</p>
| 31,382,223 | 3 | 2 | null |
2015-07-13 11:20:00.187 UTC
| 9 |
2017-09-15 00:19:22.953 UTC
|
2017-09-15 00:19:22.953 UTC
| null | 57,611 | null | 1,954,132 | null | 1 | 32 |
java|lambda
| 37,519 |
<p>Java 8 introduces the <a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html">Stream API</a> that allows similar constructs to those in Linq.</p>
<p>Your query for example, could be expressed:</p>
<pre><code>int cheetahNumber = 77;
Animal cheetah = animals.stream()
.filter((animal) -> animal.getNumber() == cheetahNumber)
.findFirst()
.orElse(Animal.DEFAULT);
</code></pre>
<p>You'll obviously need to workout if a default exists, which seems odd in this case, but I've shown it because that's what the code in your question does.</p>
|
32,998,902 |
MSVCP140.dll missing
|
<p>I just developed my first program in C++ and I wanted to share it with one of my friends.<br />
But when he tries to open the exe it gets an error which says "MSVCP140.dll is missing". Why is this issue happening and how can we fix it?</p>
| 32,999,084 | 4 | 0 | null |
2015-10-07 17:37:48.367 UTC
| 23 |
2022-08-26 14:58:20.483 UTC
|
2022-08-26 14:58:20.483 UTC
| null | 5,323,015 | null | 5,323,015 | null | 1 | 67 |
c++|windows|visual-studio-2015
| 195,275 |
<p>Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.</p>
<p>In visual studio, go to <code>Project tab -> properties - > configuration properties -> C/C++ -> Code Generation</code> on runtime library choose <code>/MTd</code> for debug mode and <code>/MT</code> for release mode.</p>
<p>This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.</p>
|
21,634,088 |
Execute "ffmpeg" command in a loop
|
<p>I have three <code>.wav</code> files in my folder and I want to convert them into <code>.mp3</code> with ffmpeg.</p>
<p>I wrote this bash script, but when I execute it, only the first one is converted to mp3.</p>
<p>What should I do to make script keep going through my files?</p>
<p>This is the script:</p>
<pre><code>#!/bin/bash
find . -name '*.wav' | while read f; do
ffmpeg -i "$f" -ab 320k -ac 2 "${f%.*}.mp3"
done
</code></pre>
| 21,634,265 | 3 | 0 | null |
2014-02-07 17:28:03.567 UTC
| 8 |
2021-01-07 17:33:51.363 UTC
|
2021-01-07 17:33:51.363 UTC
| null | 10,248,678 | null | 1,891,264 | null | 1 | 26 |
bash|ffmpeg
| 26,286 |
<p>No reason for <a href="/questions/tagged/find" class="post-tag" title="show questions tagged 'find'" rel="tag">find</a>, just use <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged 'bash'" rel="tag">bash</a> wildcard globbing</p>
<pre><code>#!/bin/bash
for name in *.wav; do
ffmpeg -i "$name" -ab 320k -ac 2 "${name%.*}.mp3"
done
</code></pre>
|
21,786,184 |
Setting up a 2D view in Three.js
|
<p>I'm new to <code>three.js</code> and am trying to set up what amounts to a 2D visualization (for an assortment of layered sprites) using these 3D tools. I'd like some guidance on the <code>PerspectiveCamera()</code> arguments and <code>camera.position.set()</code> arguments. I already have a nudge in the right direction from <a href="https://stackoverflow.com/a/11469614/2441384">this answer</a> to a <a href="https://stackoverflow.com/questions/11456758/is-there-at-two-js-counterpart-to-three-js/16071265#16071265">related question</a>, which said to set the <code>z</code> coordinate equal to <code>0</code> in <code>camera.position.set(x,y,z)</code>.</p>
<p>Below is the snippet of code I'm modifying from one of <a href="https://github.com/stemkoski/stemkoski.github.com" rel="noreferrer">stemkoski's three.js examples</a>. The parts that are hanging me up for the moment are the values for the <code>VIEW_ANGLE</code>, <code>x</code>, and <code>y</code>. Assuming I want to have a flat camera view on a plane the size of the screen how should I assign these variables? I've tried range of values but it's hard to tell from the visualization what is happening. Thanks in advance!</p>
<pre><code>var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = ?, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
var x = ?, y = ?, z = 0;
camera.position.set(x,y,z);
camera.lookAt(scene.position);
</code></pre>
<p><strong>UPDATE - perspective vs orthographic camera:</strong></p>
<p>Thanks @GuyGood, I realize I need to make a design choice about the perspective camera versus the orthographic camera. I now see that the <code>PerspectiveCamera()</code>, even in this 2D context would allow for things like <a href="https://stackoverflow.com/a/14823021/2441384">parallax</a>, whereas <code>OrthographicCamera()</code> would allow for literal rendering of sizes (no diminishing with distance) no matter what layer my 2D element is on. I'm inclined to think I'll still use the <code>PerspectiveCamera()</code> for effects such as small amounts of parallax between the sprite layers (so I guess my project is not purely 2D!).</p>
<p>It seems then that the main thing is to make all the sprite layers parallel to the viewing plane and that <code>camera.position.set()</code> is the orthogonal viewing line to the center of the field of view.This must be basic for so many folks here; it is such a new world to me!</p>
<p>I think I still have a hard time wrapping my head around the role of <code>VIEW_ANGLE</code>, <code>x</code>, and <code>y</code> and the distance between the camera and the far and near viewing planes in a 2D visualization. With the orthographic camera this is pretty immaterial - you just need enough depth to include all the layers you want and a viewing plane that suits the scale of your sprites. However, with the perspective camera the role of depth and field influences the effect of parallax, but are there other considerations as well?</p>
<p><strong>UPDATE 2 - Angle of view and other variables:</strong></p>
<p>After a bit more tooling around in pursuit of how to think about Angle of View (Field of View, or FOV) for the camera and the x,y,z arguments for the camera position, I came across this helpful <a href="http://www.youtube.com/watch?v=blZUao2jTGA" rel="noreferrer">video summary of the role of Field of View in game design</a> (a close enough analog to answer my questions for my 2D visualization). Along with this <a href="http://www.youtube.com/watch?v=eCa1dfl5o7k" rel="noreferrer">Field of View tutorial for photographers</a> that I also found helpful (if maybe a touch cheesy ;), these two resources helped me get a sense of how to choose a Field of View for my project and what happens with either very wide or narrow Fields of View (which are measured in number of degrees out of 360). The best results are a mix of what feels like a natural field of vision for a human, depending on the distance of the screen or projection from their face, and is also keenly related to the relative scale of things in the foreground versus background in the visualization (wider fields of view make the background look smaller, narrower fields of view magnify the background - similar to, though not as pronounced as the effect of an orthographic camera). I hope you find this as helpful as I did!</p>
<p><strong>UPDATE 3 - Further reading</strong></p>
<p>For anyone zesting for more detail about camera specifications in a range of uses, you may find chapter 13 of <a href="https://rads.stackoverflow.com/amzn/click/com/0321399528" rel="noreferrer" rel="nofollow noreferrer">Computer Graphics Principles and Practice</a> as useful as I have for addressing my above questions and much more.</p>
<p><strong>UPDATE 4 - Considerations for the z dimension in the Orthographic camera</strong></p>
<p>As I've continued my project I decided to use the orthographic camera so that I could increment the z dimensions of my sprites in order to avoid <a href="https://en.wikipedia.org/wiki/Z-fighting" rel="noreferrer">z-fighting</a>, yet not have them appear to recede progressively into the distance. By contrast, if I want to make it appear as though a sprite is receding into the distance, I can simply adjust its size. However, today I ran across a silly mistake that I wanted to point out to save others from the same trouble. Although the orthographic camera does not depict receding size as objects are more distant, take care that there is still a <a href="https://www.ntu.edu.sg/home/ehchua/programming/opengl/images/Graphics3D_Orthographic.png" rel="noreferrer">back frustrum plane</a> past which objects will be culled from view. Today I accidentally incremented the z values of several of my objects past that plane and could not figure out why they were not showing up on screen. It can be easy to forget this factor about the z coordinate while working with the orthographic camera.</p>
| 21,787,531 | 1 | 0 | null |
2014-02-14 17:51:36.617 UTC
| 9 |
2020-01-21 07:14:29.717 UTC
|
2018-10-18 13:25:11.6 UTC
| null | 2,441,384 | null | 2,441,384 | null | 1 | 18 |
javascript|graphics|three.js|2d|perspectivecamera
| 19,433 |
<p>What is your goal? If you do not need perspective distortion, use the orthographic camera.
Also just check the documentation:</p>
<p><a href="https://threejs.org/docs/#api/en/cameras/PerspectiveCamera" rel="nofollow noreferrer">https://threejs.org/docs/#api/en/cameras/PerspectiveCamera</a></p>
<p>View Angle/Fieldof View is self explanatory, if you don't know what it is, read up on it. </p>
<p><a href="http://www.incgamers.com/wp-content/uploads/2013/05/6a0120a85dcdae970b0120a86d9495970b.png" rel="nofollow noreferrer">http://www.incgamers.com/wp-content/uploads/2013/05/6a0120a85dcdae970b0120a86d9495970b.png</a></p>
<p>Concerning the x y and z value. Well, this depends on the size of your plane and the distance to the camera. You can either set the camera position or the plane's position and keep the camera at (0,0,0).
Just imagine a plane in 3D space. You can calculate the position of the camera depending on the size of your plane or just go by try and error...
For using the orthographic camera, see this post:</p>
<p><a href="https://stackoverflow.com/questions/17558085/three-js-orthographic-camera">Three.js - Orthographic camera</a></p>
|
35,361,467 |
TensorFlow: numpy.repeat() alternative
|
<p>I want to compare the predicted values <code>yp</code> from my neural network in a pairwise fashion, and so I was using (back in my old numpy implementation):</p>
<pre><code>idx = np.repeat(np.arange(len(yp)), len(yp))
jdx = np.tile(np.arange(len(yp)), len(yp))
s = yp[[idx]] - yp[[jdx]]
</code></pre>
<p>This basically create a indexing mesh which I then use. <code>idx=[0,0,0,1,1,1,...]</code> while <code>jdx=[0,1,2,0,1,2...]</code>. I do not know if there is a simpler manner of doing it...</p>
<p>Anyhow, TensorFlow has a <code>tf.tile()</code>, but it seems to be lacking a <code>tf.repeat()</code>.</p>
<pre><code>idx = np.repeat(np.arange(n), n)
v2 = v[idx]
</code></pre>
<p>And I get the error:</p>
<pre><code>TypeError: Bad slice index [ 0 0 0 ..., 215 215 215] of type <type 'numpy.ndarray'>
</code></pre>
<p>It also does not work to use a TensorFlow constant for the indexing:</p>
<pre><code>idx = tf.constant(np.repeat(np.arange(n), n))
v2 = v[idx]
</code></pre>
<p>-</p>
<pre><code>TypeError: Bad slice index Tensor("Const:0", shape=TensorShape([Dimension(46656)]), dtype=int64) of type <class 'tensorflow.python.framework.ops.Tensor'>
</code></pre>
<p>The idea is to convert my <a href="http://research.microsoft.com/en-us/um/people/cburges/papers/ICML_ranking.pdf" rel="noreferrer">RankNet</a> implementation to TensorFlow.</p>
| 35,367,161 | 10 | 0 | null |
2016-02-12 11:28:07.753 UTC
| 9 |
2021-12-09 09:06:52.187 UTC
|
2016-02-12 17:06:42.05 UTC
| null | 2,680,707 | null | 2,680,707 | null | 1 | 44 |
tensorflow
| 37,284 |
<p>You can achieve the effect of <code>np.repeat()</code> using a combination of <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/tile" rel="noreferrer"><code>tf.tile()</code></a> and <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/reshape" rel="noreferrer"><code>tf.reshape()</code></a>:</p>
<pre><code>idx = tf.range(len(yp))
idx = tf.reshape(idx, [-1, 1]) # Convert to a len(yp) x 1 matrix.
idx = tf.tile(idx, [1, len(yp)]) # Create multiple columns.
idx = tf.reshape(idx, [-1]) # Convert back to a vector.
</code></pre>
<p>You can simply compute <code>jdx</code> using <code>tf.tile()</code>:</p>
<pre><code>jdx = tf.range(len(yp))
jdx = tf.tile(jdx, [len(yp)])
</code></pre>
<p>For the indexing, you could try using <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/gather" rel="noreferrer"><code>tf.gather()</code></a> to extract non-contiguous slices from the <code>yp</code> tensor:</p>
<pre><code>s = tf.gather(yp, idx) - tf.gather(yp, jdx)
</code></pre>
|
25,553,711 |
Disable magnification gesture in WKWebView
|
<p>I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS.</p>
<p>WKWebView.h</p>
<pre><code>#if !TARGET_OS_IPHONE
/* @abstract A Boolean value indicating whether magnify gestures will
change the web view's magnification.
@discussion It is possible to set the magnification property even if
allowsMagnification is set to NO.
The default value is NO.
*/
@property (nonatomic) BOOL allowsMagnification;
</code></pre>
<p>I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible.</p>
<p>I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible.</p>
| 31,943,976 | 21 | 0 | null |
2014-08-28 16:31:14.533 UTC
| 17 |
2021-09-07 12:35:48.06 UTC
| null | null | null | null | 397,453 | null | 1 | 62 |
ios|webkit|ios8|wkwebview
| 52,699 |
<p>You can prevent your users from zooming by setting the delegate of your WKWebKit's UIScrollView and implementing <code>viewForZooming(in:)</code> as in the following:</p>
<pre><code>class MyClass {
let webView = WKWebView()
init() {
super.init()
webView.scrollView.delegate = self
}
deinit() {
// Without this, it'll crash when your MyClass instance is deinit'd
webView.scrollView.delegate = nil
}
}
extension MyClass: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil
}
}
</code></pre>
|
8,450,817 |
Increase size of list-style-bullet type
|
<p>Is there a way to increase the size of <em>just</em> the bullet list-style-type using CSS? I don't want to increase the size of the bullet text, just the bullet type. I can't use images or JavaScript either. It has to be something I can embed inside <code><style></code> tags within the <code><head></code> tag.</p>
| 8,450,930 | 7 | 0 | null |
2011-12-09 19:40:51.813 UTC
| 2 |
2022-05-19 22:38:41.883 UTC
|
2015-12-11 16:55:05.167 UTC
| null | 2,301,450 | null | 773,202 | null | 1 | 27 |
css|html-lists
| 69,623 |
<p>Might not work in old version of IE.</p>
<p><code>li:before{ content:'\00b7'; font-size:100px; }</code></p>
<p><a href="http://jsfiddle.net/GuzCm/1/">Demo</a></p>
<p><strong>For IE6:</strong></p>
<p>Without javascript or images, I would recommend putting a <code><span>&#183;</span></code> in the beginning of every list item and styling that.</p>
|
30,669,015 |
autoscroll of text and scrollbar in python text box
|
<p>I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? </p>
<p>Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar.</p>
<pre><code> scrollbar = Tkinter.Scrollbar(group4.interior())
scrollbar.pack(side = 'right',fill='y')
Details1 = Output()
outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9")
outputwindow.pack( side = 'left',fill='y')
scrollbar.config( command = outputwindow.yview )
outputwindow.yview('end')
outputwindow.config(yscrollcommand=scrollbar.set)
outputwindow.insert('end',Details1)
</code></pre>
<p>In the program the function output() will continuously send data, which should scroll</p>
<p>Thanks in advance,</p>
| 30,671,211 | 3 | 0 | null |
2015-06-05 14:24:38.653 UTC
| 4 |
2021-10-13 17:15:42.42 UTC
| null | null | null | null | 4,946,244 | null | 1 | 19 |
python|tkinter
| 46,820 |
<p>You can cause the text widget to scroll to any location with the <code>see</code> which takes an index.</p>
<p>For example, to make the last line of the widget visible you can use the index <code>"end"</code>:</p>
<pre><code>outputwindow.see("end")
</code></pre>
<p>Here's a complete working example:</p>
<pre><code>import time
try:
# python 2.x
import Tkinter as tk
except ImportError:
# python 3.x
import tkinter as tk
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.text = tk.Text(self, height=6, width=40)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
self.add_timestamp()
def add_timestamp(self):
self.text.insert("end", time.ctime() + "\n")
self.text.see("end")
self.after(1000, self.add_timestamp)
if __name__ == "__main__":
root =tk.Tk()
frame = Example(root)
frame.pack(fill="both", expand=True)
root.mainloop()
</code></pre>
|
43,681,644 |
Is there a way to stop/disable a Google Cloud Function?
|
<p>I have running multiple Google Cloud functions. One is not operating well, so I want to stop them until I've fixed the situation.</p>
<p>I have seen that I can remove the function, but is there a way to disable and later; enable the function?</p>
| 43,684,556 | 7 | 1 | null |
2017-04-28 13:39:45.64 UTC
| 3 |
2021-03-28 17:01:30.713 UTC
| null | null | null | null | 7,328,924 | null | 1 | 31 |
google-cloud-functions
| 17,727 |
<p>You cannot disable a function. Just comment the function body. It would be a good practice to log the call in the console and then return null so you can keep track whenever the function is invoked.</p>
|
1,217,772 |
C# Put string into TextBox
|
<p>I want to show the results of this code in my TextBox:</p>
<pre><code> string txtout1 = txtOrgText.Text.Replace(parm, txtTo.Text).ToString();
txtout = txtout1;
</code></pre>
<p>I have a textbox, <code>txtOrgtext</code>, into which the user inputs text. I want to put some text into txtout now.
I have set txtout to ReadOnly and MultiLine.</p>
<p>When I try running my program, I get the following error:</p>
<pre><code>Error 1 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' C:\Users\xxx\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 45 25 WindowsFormsApplication1
</code></pre>
<p>I tried <code>txtout1.ToString()</code>, but nothing changes.</p>
<p>I also tried <code>txtout.Text = txtout1</code> and get this error :</p>
<pre><code>Cross-thread operation not valid:
Control 'txtout' accessed from a thread other than the thread it was created on.
</code></pre>
<p>I got an error because I used Threading, without Threading it works fine.</p>
| 1,217,774 | 3 | 2 | null |
2009-08-01 23:29:52.56 UTC
| 1 |
2018-09-12 12:01:41.027 UTC
|
2017-04-29 15:43:01.273 UTC
| null | 543,538 | null | 149,130 | null | 1 | 7 |
c#
| 94,612 |
<p>What you need to do is:</p>
<pre><code> txtout.Text = txtout1;
</code></pre>
<p>This is because <code>txtout1</code> is just a string of characters, while <code>txtout</code> is a full TextBox, with all the drawing and colouring and stuff like that.</p>
<p>I see that you were on the right lines with your first line of code - txtOrgText.Text - the <code>.Text</code> is used both ways - for reading and writing. (Or "looking" and "changing" is another way of putting it.)</p>
<p>You do this with a lot of other controls - a ComboBox, a Form (to set the caption), a DomainUpDown (the thing with the arrows on the right) to name a few.</p>
<p>The reason that "ToString()" doesn't work is that ToString() is making your string of text into a string of text! It doesn't turn it into a TextBox for you.</p>
|
132,940 |
Why does Castle Windsor hold onto transient objects?
|
<p>Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.</p>
<p>I've found if I put an explicit call to <code>IWindsorContainer.Release(hangingObject)</code>, that it will drop its references.</p>
<p>This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places.</p>
<p>Have you seen this problem, and do you have any suggestions for how to get around it?</p>
| 166,523 | 3 | 0 | null |
2008-09-25 12:16:08.73 UTC
| 8 |
2015-09-11 07:34:01.227 UTC
|
2015-09-11 07:32:34.89 UTC
| null | 542,251 |
Scott Langham
| 11,898 | null | 1 | 30 |
c#|castle-windsor
| 7,038 |
<p>I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site <a href="http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html" rel="nofollow noreferrer">here</a>.</p>
<p>In many scenarios especially where your container exists for the lifetime of the hosting application, and where transient components really don't need to be tracked (because you're handling disposal in your calling code or component that's been injected with the service) then you can just set the release policy to the <code>NoTrackingReleasePolicy</code> implementation and be done with it.</p>
<p>Prior to Castle v 1.0 I believe Component Burden will be implemented/introduced - which will help alleviate some of these issues as well around disposal of injected dependencies etc.</p>
<p><strong>Edit:</strong></p>
<p>Check out the following posts for more discussion of component burden.</p>
<p><a href="http://elegantcode.com/2008/12/14/the-component-burden/" rel="nofollow noreferrer">The Component Burden - Davy Brions</a></p>
<p>Also component burden is implemented in the <a href="http://ayende.com/Blog/archive/2009/05/05/castle-windsor-2.0-rtm-released.aspx" rel="nofollow noreferrer">official 2.0 release</a> of the Windsor Container.</p>
|
181,693 |
What are the complexity guarantees of the standard containers?
|
<p>Apparently ;-) the standard containers provide some form of guarantees.</p>
<p>What type of guarantees and what exactly are the differences between the different types of container?</p>
<p>Working from <a href="http://www.sgi.com/tech/stl/" rel="noreferrer">the SGI page</a> (about <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>) I have come up with this:</p>
<pre><code>Container Types:
================
Container:
Forward Container
Reverse Container
Random Access Container
Sequence
Front Insert Sequence
Back Insert Sequence
Associative Container
Simple Associative Container
Pair Associative Container
Sorted Associative Container
Multiple Associative Container
Container Types mapped to Standard Containers
=============================================
std::vector: Sequence Back Sequence Forward/Reverse/Random Container
std::deque: Sequence Front/Back Sequence Forward/Reverse/Random Container
std::list: Sequence Front/Back Sequence Forward/Reverse Container
std::set: Sorted/Simple/Unique Associative Container Forward Container
std::map: Sorted/Pair/Unique Associative Container Forward Container
std::multiset: Sorted/Simple/Multiple Associative Container Forward Container
std::multimap: Sorted/Pair/Multiple Associative Container Forward Container
Container Guarantees:
=====================
Simp
or
For Rev Rand Front Back Assoc Sort Mult
Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont:
Copy Const: O(n)
Fill Const: O(n)
begin() O(1)
end() O(1)
rbegin() O(1)
rend() O(1)
front() O(1)
push_front() O(1)
pop_front() O(1)
push_back() O(1)
pop_back() O(1)
Insert() O(ln(n))
Insert: fill O(n)
Insert: range O(n) O(kln(n)+n)
size() O(1)
swap() O(1)
erase key O(ln(n))
erase element O(1)
erase range O(ln(n)+S)
count() O(log(n)+k)
find() O(ln(n))
equal range O(ln(n))
Lower Bound/Upper Bound O(ln(n))
Equality O(n)
InEquality O(n)
Element Access O(1)
</code></pre>
| 26,395,804 | 3 | 10 | null |
2008-10-08 07:35:11.323 UTC
| 168 |
2021-11-09 17:15:45.417 UTC
|
2021-11-09 17:15:45.417 UTC
|
Martin York
| 14,065 |
Martin York
| 14,065 | null | 1 | 178 |
c++|stl|containers|big-o
| 144,800 |
<p>I found the nice resource <em><a href="http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-summary.html" rel="noreferrer">Standard C++ Containers</a></em>. Probably this is what you all looking for.</p>
<p><strong>VECTOR</strong></p>
<p><strong>Constructors</strong></p>
<pre><code>vector<T> v; Make an empty vector. O(1)
vector<T> v(n); Make a vector with N elements. O(n)
vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)
vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n)
</code></pre>
<p><strong>Accessors</strong></p>
<pre><code>v[i] Return (or set) the I'th element. O(1)
v.at(i) Return (or set) the I'th element, with bounds checking. O(1)
v.size() Return current number of elements. O(1)
v.empty() Return true if vector is empty. O(1)
v.begin() Return random access iterator to start. O(1)
v.end() Return random access iterator to end. O(1)
v.front() Return the first element. O(1)
v.back() Return the last element. O(1)
v.capacity() Return maximum number of elements. O(1)
</code></pre>
<p><strong>Modifiers</strong></p>
<pre><code>v.push_back(value) Add value to end. O(1) (amortized)
v.insert(iterator, value) Insert value at the position indexed by iterator. O(n)
v.pop_back() Remove value from end. O(1)
v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)
v.erase(iterator) Erase value indexed by iterator. O(n)
v.erase(begin, end) Erase the elements from begin to end. O(n)
</code></pre>
<p>For other containers, refer to the page.</p>
|
28,845,058 |
constexpr const vs constexpr variables?
|
<p>It seems obvious that constexpr implies const and thus it is common to see:</p>
<pre><code>constexpr int foo = 42; // no const here
</code></pre>
<p>However if you write:</p>
<pre><code>constexpr char *const str = "foo";
</code></pre>
<p>Then GCC will spawn "warning: deprecated conversion from string constant to ‘char*’" if -Wwrite-string flag is passed.</p>
<p>Writing:</p>
<pre><code>constexpr const char *const str = "foo";
</code></pre>
<p>solves the issue.</p>
<p>So are constexpr const and constexpr really the same?</p>
| 28,845,237 | 3 | 2 | null |
2015-03-04 01:13:55.137 UTC
| 16 |
2020-02-27 19:47:23.557 UTC
|
2020-02-27 19:47:23.557 UTC
| null | 1,410,669 | null | 1,442,517 | null | 1 | 65 |
c++|c++11|constants|constexpr
| 24,926 |
<p>The issue is that in a variable declaration, <code>constexpr</code> always applies the <code>const</code>-ness to the object declared; <code>const</code> on the other hand can apply to a different type, depending on the placement.</p>
<p>Thus</p>
<pre><code>constexpr const int i = 3;
constexpr int i = 3;
</code></pre>
<p>are equivalent;</p>
<pre><code>constexpr char* p = nullptr;
constexpr char* const p = nullptr;
</code></pre>
<p>are equivalent; both make <code>p</code> a <code>const</code> pointer to <code>char</code>.</p>
<pre><code>constexpr const char* p = nullptr;
constexpr const char* const p = nullptr;
</code></pre>
<p>are equivalent. <code>constexpr</code> makes <code>p</code> a <code>const</code> pointer. The <code>const</code> in <code>const char *</code> makes <code>p</code> point to <code>const char</code>.</p>
|
20,606,432 |
Number validate at keypress
|
<p>I validate the phone number using below code its working fine but i allow char at first time while user entering the values. how i can solve it. . . .</p>
<pre><code>$('.Number').keypress(function () {
$('.Number').keypress(function (event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 ||
keycode == 37 ||keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
});
</code></pre>
| 20,606,478 | 5 | 0 | null |
2013-12-16 08:34:40.347 UTC
| 1 |
2019-02-04 11:02:01.03 UTC
|
2013-12-16 08:38:48.543 UTC
| null | 2,074,608 | null | 2,830,895 | null | 1 | 5 |
javascript|jquery|asp.net-mvc|jquery-ui
| 42,132 |
<p>The first character is unrestricted because you have nested <code>keypress</code> handlers. Try this:</p>
<pre><code>$('.Number').keypress(function (event) {
var keycode = event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
</code></pre>
|
24,320,237 |
change the text of the button on click using angular JS
|
<p>How I can change the text of the button on click of the button.</p>
<p>Here it is what I have tried.</p>
<p>HTML:</p>
<pre><code><button ng-click="toggle = !toggle">Toggle!</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
</code></pre>
<p>JS:</p>
<pre><code>function MainController($scope) {
$scope.toggle = true;
}
</code></pre>
| 24,320,257 | 4 | 0 | null |
2014-06-20 04:59:43 UTC
| 3 |
2016-10-24 21:54:44.843 UTC
|
2014-06-20 05:05:52.643 UTC
| null | 3,563,847 | null | 1,853,128 | null | 1 | 18 |
javascript|jquery|angularjs
| 49,793 |
<p>I think, using a watch of <code>toggle</code> should do it</p>
<pre><code><button ng-click="toggle = !toggle">{{toggleText}}</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
</code></pre>
<p>then</p>
<pre><code>app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Toggle!' : 'some text';
})
})
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/arunpjohny/Ljrpd/" rel="noreferrer">Fiddle</a></p>
|
65,553,800 |
Why does an optional in fast enumeration cause an infinite loop?
|
<p>Evaluating the following code, I would expect a single printing of <code>Hello World</code>. Instead, it causes an infinite loop. Can someone explain why?</p>
<pre><code>let array = ["what"]
for text: String? in array {
print("Hello World")
}
</code></pre>
<p>(Removing the optional <code>?</code> obviously makes it print only once)</p>
| 65,554,547 | 2 | 1 | null |
2021-01-03 19:07:55.413 UTC
| 3 |
2021-02-01 12:05:17.003 UTC
|
2021-01-03 20:28:04.387 UTC
| null | 14,531,220 | null | 3,749,617 | null | 1 | 30 |
swift
| 464 |
<p>This is an unexpected result, but it is happening because of the way Swift <code>for in</code> loops work under the hood.</p>
<p><code>for in</code> takes a variable and a <code>Sequence</code>. Swift calls <code>makeIterator()</code> on the <code>Sequence</code> to get an <code>IteratorProtocol</code> which returns successive items when <code>next()</code> is called on the iterator. <code>next()</code> returns an <em>Optional</em> so that it can return <code>nil</code> when all of the items have been exhausted.</p>
<p>In a normal case, you receive the non-optional values and Swift continues giving them out until <code>nil</code> is received in which case the loop ends.</p>
<p>This is the equivalent of your code when you don't use an <em>optional</em>:</p>
<pre><code>let array = ["what"]
var iter = array.makeIterator()
while let text = iter.next() {
print("Hello World")
}
</code></pre>
<p>The <em>optional binding</em> (<code>while let</code>) fails when <code>iter.next()</code> returns <code>nil</code> and the loop ends.</p>
<p>In your case, you have said that you will explicitly receive <code>nil</code> values (by declaring your loop variable as an <em>optional</em>), so when <code>next()</code> is called on the iterator and it is out of values, it hands you a <code>nil</code> which you graciously receive and the loop continues. The iterator continues to hand out <code>nil</code> and you continue to take them, and you have an infinite loop.</p>
<p>This is the equivalent of your code when you use an <em>optional</em>:</p>
<pre><code>let array = ["what"]
var iter = array.makeIterator()
while let text: String? = iter.next() {
print("Hello World")
}
</code></pre>
<p>In this case, the <em>optional binding</em> always works because <code>text</code> can receive the <code>nil</code>.</p>
<p><a href="https://swiftrocks.com/swift-sequence-inside-the-compiler-how-for-loops-work" rel="noreferrer">This blog</a> gives a nice detailed explanation of what is happening under the hood with Swift <code>for in</code> loops.</p>
|
5,765,962 |
How to execute a update statement using Oracle ODP.Net in C#
|
<p>I am using <code>Oracle.DataAccess.Client</code> to work with <strong>Oracle</strong> database in my <strong>ASP.Net</strong> application. There is no help documentation in <strong>MSDN</strong> for <strong>ODP.Net</strong> and <strong>Oracle</strong>'s documentation is really really bad. I am not able find the answer to this simple question.</p>
<p>Is it not possible to execute a simple update statement without having to build a <code>dataset</code> object and updating the <code>dataset</code>?</p>
<p>How to execute an update statement using <strong>Oracle ODP.Net</strong> in <strong>C#</strong>?</p>
| 5,766,007 | 3 | 1 | null |
2011-04-23 18:09:03.29 UTC
| 2 |
2017-08-30 13:29:40.09 UTC
|
2017-08-30 13:29:40.09 UTC
| null | 7,920,473 | null | 399,186 | null | 1 | 9 |
c#|asp.net|odp.net
| 51,833 |
<p>I will need to check the exact syntax, but here is some quick code off the top of my head</p>
<pre><code>using (OracleConnection con = new OracleConnection(...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update table set col1 = :param1, col2 = :param2 where key = :keyValue";
cmd.Parameters.AddWithValue("param1", 1);
cmd.Parameters.AddWithValue("param2", "Text data");
cmd.Parameters.AddWithValue("keyValue", "1");
cmd.ExecuteNonQuery();
}
</code></pre>
<p>The above creates a command object sets the command up to execute an SQL Update statement, in this example I show one way to setup a parameterized query, you should always go with a parameterized query. Once the command is setup you just call <code>ExecuteNonQuery</code> to actually execute the command.</p>
|
5,642,021 |
Batch process all files in directory
|
<p>Right now i have a batch job I wrote that calls another file and passes in the variables that executable needs to run (password and filename). </p>
<p>Ex:</p>
<pre><code>> cd f:\test\utils
> admin import-xml -Dimport.file=f:\DB\file1.xml -Dadmin.db.password=test123
</code></pre>
<p>I wrote a job that does this, but found out that there would be multiple files.</p>
<p>The username and password never change but the filename differs for like 15 different xml files--with maybe more coming soon.</p>
<p>The files will always be located in the same folder. Instead of ending up with like 15-20 jobs (one for each file), can I write something that will process each file located in this directory. And either wait till one is completed before the next or I can add a 3 min sleep before it starts the next file.</p>
| 5,644,619 | 3 | 0 | null |
2011-04-12 21:48:01.993 UTC
| 5 |
2013-03-14 06:42:57.483 UTC
| null | null | null | null | 697,671 | null | 1 | 10 |
windows|batch-file|cmd
| 50,084 |
<pre><code>pushd C:\test\utils
for %%F in (F:\DB\*.xml) do (
admin import-xml "-Dimport.file=%%~dpnxF" -Dadmin.db.password=test123
)
popd
</code></pre>
<p>The <code>%%~dpnxF</code> expands to <strong>d</strong>rive, <strong>p</strong>ath, base<strong>n</strong>ame and e<strong>x</strong>tension of the current file.</p>
<p>If you intend to set <em>and</em> use environment variables (<code>%foo%</code>) in that loop, read <code>help set</code> first before you get into trouble.</p>
|
5,746,319 |
Get cell contents of a selected row in a DataGridView
|
<p>I have a <code>DataGridView</code> populated from a database.</p>
<p>I am trying to get the contents of the row that is selected on the <code>RowEnter</code> event. I have set the grid's selection mode to <code>FullRowSelect</code></p>
<p>I have tried the following: </p>
<pre><code>int orderId = (int)dgUnprocessedCards.Rows[dgUnprocessedCards.SelectedCells[0].RowIndex].Cells[0].Value;
</code></pre>
<p>this keep throwing the error</p>
<blockquote>
<p>Index was out of range. Must be non-negative and less than the size of the collection.</p>
</blockquote>
<p>Any help is appreciated.</p>
| 5,746,524 | 4 | 0 | null |
2011-04-21 15:31:22.843 UTC
| 1 |
2021-12-12 11:28:41.607 UTC
|
2011-06-21 15:02:13.383 UTC
| null | 556,595 | null | 705,803 | null | 1 | 8 |
c#|winforms|datagridview
| 62,222 |
<p>I've just tried this in a sample datagridview app and it works just fine so there must be something going on which you haven't told us about.</p>
<p>First thing to do is break your one big statement up into discrete smaller statements so you can see exactly where the failure is.</p>
<p>You can rewrite the code above to something like this for debugging purposes:</p>
<pre><code>var cellindex = dgUnprocessedCards.SelectedCells[0].RowIndex;
var cellcollection = dgUnprocessedCards.Rows[cellindex].Cells[0];
int orderId = (int)dgUnprocessedCards.Value;
</code></pre>
<p>Also, you should be able to do the following to achieve what you want:</p>
<pre><code>int orderId = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
</code></pre>
<p>That uses the SelectedRows collection which is a little bit more concise and I'd say the more usual way of accessing selected items from the datagridview.</p>
<p>Finally, you probably want to do checking around your cast of the value, since the Value might not necessarily be an int. Something like:</p>
<pre><code>int orderid;
if (!int.TryParse(cellcollection.Value.ToString(), out orderid))
{
// Some logic to deal with the fact that Value was not an int
}
</code></pre>
<hr>
<p><strong>When is the SelectionChanged event raised?</strong></p>
<p>Now - as you mention, your selection changed event fires while loading data into the grid. This doesn't seem to cause a problem in my test version but could be part of your issue.</p>
<p>Why this happens should not be related to the type of data source you are using, but to when you attach the selection changed eventhandler. This is because databinding causes a selection changed event to be raised.</p>
<p>If you add an eventhandler for the DataBindingComplete event and attach your SelectionChanged or RowEnter eventhandlers there, you should not see the handler invoked during databinding.</p>
<pre><code>void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.dataGridView1.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
}
</code></pre>
<p>Note that you will need to delete the designer generated event attachment and reference the designer generated methods for this to work. </p>
|
6,012,019 |
How to echo a custom object in PHP?
|
<p>Given a particular class, <code>TheClass</code>, with an instance <em>foo</em>, is there any way to have PHP <code>echo foo;</code> in a customized manner?</p>
<pre><code>class TheClass {
public $Name;
public $Number;
function MrFunction() { /* bla bla bla */ }
}
$foo = new TheClass();
echo $foo;
</code></pre>
<p>As I understand, you cannot overload <code>echo</code> and I realize I could easily have <code>$foo->MrFunction()</code> do the work. However I am wondering if there is a way to code in which</p>
<p><code>echo $foo</code> prints out <code>$foo->Name</code> and <code>$foo->Number</code>.</p>
<p>We're using <em>PHP Version 5.2.6</em> but upgrading is not an issue.</p>
| 6,012,035 | 4 | 3 | null |
2011-05-15 23:42:12.523 UTC
| 4 |
2021-12-25 03:10:25.493 UTC
|
2021-12-25 03:10:25.493 UTC
|
user1228
| 578,023 | null | 578,023 | null | 1 | 24 |
php|class|object|echo
| 58,025 |
<pre><code>class TheClass {
public $Name;
public $Number;
function MrFunction() { /* bla bla bla */ }
public function __toString()
{
return $this->Name . ' '. $this->Number;
}
}
echo $theClassInstance;
</code></pre>
|
5,855,985 |
sass :first-child not working
|
<p>I have not been using SASS for a very long time and wanted to know if there are some issues with pseudo-elements such as <code>:first-child</code> or <code>:last-child</code> ?</p>
| 6,061,731 | 4 | 1 | null |
2011-05-02 10:19:47.973 UTC
| 2 |
2022-01-20 17:17:49.157 UTC
| null | null | null | null | 348,869 | null | 1 | 41 |
css|sass|pseudo-element
| 177,349 |
<p>While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.</p>
<p>As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:</p>
<pre><code>div#top-level
declarations: ...
div.inside
declarations: ...
&:first-child
declarations: ...
</code></pre>
<p>which compiles as one would expect:</p>
<pre><code>div#top-level{
declarations... }
div#top-level div.inside {
declarations... }
div#top-level div.inside:first-child {
declarations... }
</code></pre>
<p>I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything. </p>
|
6,223,355 |
Static variables in member functions
|
<p>Can someone please explain how static variables in member functions work in C++. </p>
<p>Given the following class:</p>
<pre><code>class A {
void foo() {
static int i;
i++;
}
}
</code></pre>
<p>If I declare multiple instances of <code>A</code>, does calling <code>foo()</code> on one instance increment the static variable <code>i</code> on all instances? Or only the one it was called on?</p>
<p>I assumed that each instance would have its own copy of <code>i</code>, but stepping through some code I have seems to indicate otherwise.</p>
| 6,223,371 | 4 | 0 | null |
2011-06-03 05:33:53.487 UTC
| 57 |
2020-06-26 14:25:53.79 UTC
|
2018-05-05 12:09:30.207 UTC
| null | 873,025 | null | 2,499,176 | null | 1 | 196 |
c++|static|scope
| 105,229 |
<p>Since <code>class A</code> is a non-template class and <code>A::foo()</code> is a non-template function. There will be only one copy of <code>static int i</code> inside the program.</p>
<p>Any instance of <code>A</code> object will affect the same <code>i</code> and lifetime of <code>i</code> will remain through out the program. To add an example:</p>
<pre><code>A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4
</code></pre>
|
1,707,310 |
Is it possible to use ref types in C# built-in Action<> delegate?
|
<p>C# has built-in delegates <code>Action<></code> and <code>Func<></code>. Is it possible to use 'ref' type parameters for this delegates? For example, this code:</p>
<pre><code>public delegate void DTest( ref Guid a );
public event DTest ETest;
</code></pre>
<p>Will compile. But if I use <code>Action<></code>, it will not compile:</p>
<pre><code>public event Action< ref Guid > ETest;
</code></pre>
<p>Any hints?</p>
| 1,707,325 | 2 | 0 | null |
2009-11-10 11:31:22.86 UTC
| 9 |
2011-11-13 16:04:13.083 UTC
|
2009-11-10 11:35:47.393 UTC
| null | 5,380 | null | 69,882 | null | 1 | 45 |
c#
| 21,450 |
<p>No, you can't use pass-by-reference with the <code>Action</code> delegates. While there is a concept of "type passed by reference" as a <code>Type</code> in the framework, it's not really a type in the normal sense as far as C# is concerned. <code>ref</code> is a modifier for the parameter, not part of the type name, if you see what I mean.</p>
<p>However, you can build your own set of equivalent types, e.g.</p>
<pre><code>delegate void ActionRef<T>(ref T item);
</code></pre>
<p>Of course, if you want a mixture of ref and non-ref parameters in the same delegate, you get into a horrible set of combinations:</p>
<pre><code>delegate void ActionRef1<T1, T2>(ref T1 arg1, T2 arg2);
delegate void ActionRef2<T1, T2>(T1 arg1, ref T2 arg2);
delegate void ActionRef3<T1, T2>(ref T1 arg1, ref T2 arg2);
</code></pre>
|
1,379,247 |
Tell if a Django Field is required from template
|
<p>I'm rendering a form. I would like to put a mark next to all the fields that must be filled in. Simple stuff usually... but I've no idea how to access that information!</p>
<pre><code>{% if field.required %}REQUIRED!!{% endif %}
</code></pre>
<p>doesn't bring any love...</p>
| 1,379,288 | 2 | 1 | null |
2009-09-04 13:26:59.11 UTC
| 9 |
2009-09-04 13:31:51.867 UTC
| null | null | null | null | 12,870 | null | 1 | 59 |
django|django-templates
| 17,723 |
<pre><code>{% if field.field.required %}
</code></pre>
<p>From <a href="http://www.djangosnippets.org/snippets/474/" rel="noreferrer">this snippet</a></p>
|
45,815,899 |
LocalNotification with AlarmManager and BroadcastReceiver not firing up in Android O (oreo)
|
<p><strong>I've got my local notifications running on androids prior to SDK 26</strong></p>
<p>But in a Android O I've got the following warning, and the broadcast receiver is not fired.</p>
<pre><code>W/BroadcastQueue: Background execution not allowed: receiving Intent { act=package.name.action.LOCAL_NOTIFICATION cat=[com.category.LocalNotification] flg=0x14 (has extras) } to package.name/com.category.localnotifications.LocalNotificationReceiver
</code></pre>
<p>From what I've read broadcast receivers are more restricted in android O, but if so, how should I schedule the broadcast if I want it launching even if the main activity is not running?</p>
<p>Should I use services instead of receivers?</p>
<p>This is the AlarmManager launch code:</p>
<pre><code>public void Schedule(String aID, String aTitle, String aBody, int aNotificationCode, long aEpochTime)
{
Bundle lExtras = new Bundle();
lExtras.putInt("icon", f.getDefaultIcon());
lExtras.putString("title", aTitle);
lExtras.putString("message", aBody);
lExtras.putString("id", aID);
lExtras.putInt("requestcode", aNotificationCode);
Intent lIntent =
new Intent(LocalNotificationScheduler.ACTION_NAME)
.addCategory(NotificationsUtils.LocalNotifCategory)
.putExtras(lExtras);
PendingIntent lPendIntent = PendingIntent.getBroadcast(f.getApplicationContext(), aNotificationCode,
lIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager lAlarmMgr = (AlarmManager) f.getSystemService(Context.ALARM_SERVICE);
lAlarmMgr.set(AlarmManager.RTC, 1000, lPendIntent);
}
</code></pre>
<p>This is the receiver code:</p>
<pre><code>public class LocalNotificationReceiver extends BroadcastReceiver {
public static native void nativeReceiveLocalNotification (String aID, String aTitle, String aMessage, boolean aOnForeground );
/** This method receives the alarms set by LocalNotificationScheduler,
* notifies the CAndroidNotifications c++ class, and (if needed) ships a notification banner
*/
@Override
public void onReceive(Context aContext, Intent aIntent)
{
Toast.makeText(context, text, duration).show();
}
</code></pre>
<p>}</p>
<p>Android manifest:</p>
<pre><code><receiver android:name="com.category.localnotifications.LocalNotificationReceiver">
<intent-filter>
<action android:name="${applicationId}.action.LOCAL_NOTIFICATION" />
<category android:name="com.category.LocalNotification" />
</intent-filter>
</receiver>
</code></pre>
| 45,825,690 | 4 | 3 | null |
2017-08-22 11:03:23.683 UTC
| 10 |
2019-06-15 11:56:28.1 UTC
|
2019-06-15 11:56:28.1 UTC
| null | 8,375,325 | null | 1,894,850 | null | 1 | 25 |
android|broadcastreceiver|alarmmanager|android-8.0-oreo
| 19,505 |
<p>Android O are pretty new to-date. Hence, I try to digest and provide as accurate possible information.</p>
<p>From <a href="https://developer.android.com/about/versions/oreo/background.html#broadcasts" rel="noreferrer">https://developer.android.com/about/versions/oreo/background.html#broadcasts</a></p>
<ul>
<li>Apps that target Android 8.0 or higher can no longer register broadcast receivers for <strong>implicit broadcasts</strong> in their manifest.
<ul>
<li>Apps can use <code>Context.registerReceiver()</code> at runtime to register a receiver for <strong>any</strong> broadcast, whether <strong>implicit</strong> or <strong>explicit</strong>.</li>
</ul></li>
<li>Apps can continue to register <strong>explicit broadcasts</strong> in their manifest.</li>
</ul>
<hr>
<p>Also, in <a href="https://developer.android.com/training/scheduling/alarms.html" rel="noreferrer">https://developer.android.com/training/scheduling/alarms.html</a> , the examples are using explicit broadcast, and doesn't mention anything special regarding Android O.</p>
<hr>
<p>May I suggest you try out explicit broadcast as follow?</p>
<pre><code>public static void startAlarmBroadcastReceiver(Context context, long delay) {
Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Remove any previous pending intent.
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);
}
</code></pre>
<hr>
<h2>AlarmBroadcastReceiver</h2>
<pre><code>public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
</code></pre>
<p>In <code>AndroidManifest</code>, just define the class as</p>
<pre><code><receiver android:name="org.yccheok.AlarmBroadcastReceiver" >
</receiver>
</code></pre>
|
29,392,281 |
Manually trigger Django email error report
|
<p><a href="https://docs.djangoproject.com/en/1.7/howto/error-reporting/">Django error reporting</a> handles uncaught exceptions by sending an email, and (optionally) shows user a nice 500 error page. </p>
<p>This works very well, but in a few instances I'd like to allow users to continue with their business uninterrupted, but still have Django send me the email error report about the exception.</p>
<p>So basically: can I manually send email error report even if I catch the exception?</p>
<p>Of course, I'd like to avoid manually generating the error report email.</p>
| 29,878,519 | 6 | 0 | null |
2015-04-01 13:37:28.753 UTC
| 5 |
2020-12-15 15:20:33.63 UTC
| null | null | null | null | 236,195 | null | 1 | 35 |
python|django|exception-handling|django-email|django-errors
| 6,089 |
<p>You can use the following code to send manually an email about a <code>request</code> and an exception <code>e</code>:</p>
<pre><code>import sys
import traceback
from django.core import mail
from django.views.debug import ExceptionReporter
def send_manually_exception_email(request, e):
exc_info = sys.exc_info()
reporter = ExceptionReporter(request, is_email=True, *exc_info)
subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989]
message = "%s\n\n%s" % (
'\n'.join(traceback.format_exception(*exc_info)),
reporter.filter.get_request_repr(request)
)
mail.mail_admins(
subject, message, fail_silently=True,
html_message=reporter.get_traceback_html()
)
</code></pre>
<p>You can test it in a view like this:</p>
<pre><code>def test_view(request):
try:
raise Exception
except Exception as e:
send_manually_exception_email(request, e)
</code></pre>
|
53,674,529 |
Is there a way on VS Code to import Makefile projects?
|
<p>As the title said, can I populate automatically c_cpp_properties.json from an existing Makefile?</p>
<p>Edit:</p>
<p>For others trying to import makefiles, I have found a set of scripts that perform exactly what I wanted to achieve, the management of STM32 embedded projects through VS Code. If you dig into the scripts folder you can find the make parser and the VSCode project files populator.</p>
<p><a href="https://github.com/damogranlabs/VS-Code-STM32-IDE" rel="noreferrer">Here</a> the repo, enjoy!</p>
| 53,687,462 | 4 | 3 | null |
2018-12-07 17:46:18.247 UTC
| 4 |
2020-07-11 08:19:44.817 UTC
|
2020-02-06 14:55:56.073 UTC
| null | 3,240,596 | null | 3,240,596 | null | 1 | 12 |
visual-studio-code|makefile|stm32|stm32cubemx
| 42,020 |
<p>This answer may not entirely give you what you want, but hopefully it helps you setting up your VS Code environment.</p>
<p>In your question title, you mention "Makefile projects", which is an indication that you have the wrong impression that (GNU) Makefiles capture project settings in a way similar to Visual Studio project files do. Makefiles do not work like that and the short answer to your question is No, there does not seem to be a way to "import" Makefiles into VS Code and have it automatically set values in your <code>c_cpp_properties.json</code> file.</p>
<p>Having said that, there are some other mechanisms that may help you getting started with VS Code in your situation, depending on the other elements you have in your toolchain.</p>
<p>VS Code works with the premise that it opens one or more directories in your file system. When you do so, it will automatically scan all its subdirectories, display the tree and do linting (if enabled) to detect problems. Indeed, include directories need to be added manually to your <code>c_cpp_properties.json</code> file but to add all your subdirectories recursively to the list of include directories, you can use the expression</p>
<pre><code>"${workspaceRoot}/**"
</code></pre>
<p>as one of the elements in your <code>includePath</code> setting. See the blog post <a href="https://blogs.msdn.microsoft.com/vcblog/2018/05/08/visual-studio-code-cc-extension-may-2018-update-intellisense-configuration-just-got-so-much-easier/" rel="noreferrer">Visual Studio Code C/C++ extension May 2018 Update – IntelliSense configuration just got so much easier!</a> for more details. That often resolves a lot of the missing symbols. If you are using external or 3rd party libraries as well, then you have to add those to your <code>includePath</code> setting manually, there is no way around that.</p>
<p>Additionally, you can create VS Code Tasks to execute your <code>make</code> command to your liking. This is explained here: <a href="https://code.visualstudio.com/docs/editor/tasks" rel="noreferrer">Integrate with External Tools via Tasks</a>. The <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools" rel="noreferrer">Microsoft C/C++ Extension</a> comes with a set of so-called problemMatchers that parse the output of your command and can interpret that for certain known compilers. You will see hyperlinks for errors and warning to navigate directly to the associated location in your code.</p>
<p>An example of such a Task may look like this:</p>
<pre><code> {
"label": "Build All Debug",
"type": "shell",
"command": "make -f path/to/Makefile DEBUG=1",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "new"
},
"problemMatcher": [
"$gcc"
]
}
</code></pre>
|
5,832,693 |
regex to find a word before and after a specific word
|
<p>I need a regex that gives me the word before and after a specific word, included the search word itself.</p>
<p>Like: "<em>This is some dummy text to find a word</em>" should give me a string of "dummy <strong>text</strong> to" when <strong>text</strong> is my search word.</p>
<p>Another question, it's possible that the string provided will contain more then once the search word so I must be able to retrieve all matches in that string with C#.</p>
<p>Like "<em>This is some dummy text to find a word in a string full with text and words</em>"
Should return:</p>
<ul>
<li>"dummy <strong>text</strong> to"</li>
<li>"with <strong>text</strong> and"</li>
</ul>
<p><strong>EDIT:</strong>
Actually I should have all the matches returned that contain the search word.
A few examples:
Text is too read. -> Text is</p>
<p>Read my text. -> my text</p>
<p>This is a text-field example -> a text-field example</p>
| 5,833,319 | 5 | 3 | null |
2011-04-29 13:29:42.853 UTC
| 10 |
2020-05-22 13:25:51.16 UTC
|
2017-12-01 11:43:02.297 UTC
| null | 3,885,376 | null | 731,127 | null | 1 | 13 |
c#|regex
| 47,112 |
<p><strong>EDIT:</strong></p>
<p>If you want to <em>grab all the content from the space before first word to the space after the word</em> use:</p>
<pre><code>(?:\S+\s)?\S*text\S*(?:\s\S+)?
</code></pre>
<p>A simple tests:</p>
<pre><code>string input = @"
This is some dummy text to find a word in a string full with text and words
Text is too read
Read my text.
This is a text-field example
this is some dummy la@text.be to read";
var matches = Regex.Matches(
input,
@"(?:\S+\s)?\S*text\S*(?:\s\S+)?",
RegexOptions.IgnoreCase
);
</code></pre>
<p>the matches are:</p>
<pre>dummy text to
with text and
Text is
my text.
a text-field example
dummy la@text.be to</pre>
|
5,603,910 |
Define enums within a method in C#?
|
<p>I have mainly a C++ background and I am learning C#. So, I need some help with C# idioms and style.</p>
<p>I am trying to write, in C#, a small text-file parsing method in which I need a simple state variable with three states. In C++ I would declare an <code>enum</code> like this for the state variable:</p>
<pre class="lang-cpp prettyprint-override"><code>enum { stHeader, stBody, stFooter} state = stBody;
</code></pre>
<p>...and then use it in my parsing loop like this:</p>
<pre class="lang-cpp prettyprint-override"><code>if (state == stHeader && input == ".endheader")
{
state = stBody;
}
</code></pre>
<p>In C# I realize that it is not possible to declare an <code>enum</code> inside a method. So, what I am supposed to do for sake of clean style? Declare this internal <code>enum</code> outside of the method? Use magic numbers 1,2,3? Create a separate class for this?</p>
<p>Please help me clear up my confusion.</p>
| 5,603,939 | 5 | 3 | null |
2011-04-09 08:45:42.677 UTC
| 1 |
2020-06-25 13:02:43.083 UTC
|
2016-06-10 13:49:25.257 UTC
| null | 1,497,596 | null | 19,884 | null | 1 | 29 |
c#|enums|coding-style
| 23,592 |
<p>The closest you can get is a private nested enum with in the class:</p>
<pre><code>public class TheClass
{
private enum TheEnum
{
stHeader,
stBody,
stFooter
}
// ...the rest of the methods properties etc...
}
</code></pre>
|
6,032,032 |
How do I compute the non-client window size in WPF?
|
<p>WPF has the <a href="http://msdn.microsoft.com/en-us/library/system.windows.systemparameters.aspx" rel="noreferrer"><code>SystemParameters</code> class</a> that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:</p>
<p><img src="https://i.stack.imgur.com/cBEZj.png" alt="Non-client area - Aero"></p>
<p>However, <code>SystemParameters</code> return the following values:</p>
<pre><code>SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21
</code></pre>
<p>Here I have disabled the Aero theme:</p>
<p><img src="https://i.stack.imgur.com/KZXkC.png" alt="Non-client area - classic"></p>
<p>Now, <code>SystemParameters</code> return the following values:</p>
<pre><code>SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18
</code></pre>
<p>How do I compute the actual observed values by using <code>SystemParameters</code>?</p>
| 6,032,318 | 5 | 1 | null |
2011-05-17 14:06:57.27 UTC
| 10 |
2020-05-29 10:01:42.947 UTC
|
2011-05-17 17:47:18.783 UTC
| null | 98,607 | null | 98,607 | null | 1 | 36 |
c#|.net|wpf|windows|winapi
| 10,443 |
<p>For a resizable window you need to use a different set of parameters to compute the size:</p>
<pre><code>var titleHeight = SystemParameters.WindowCaptionHeight
+ SystemParameters.ResizeFrameHorizontalBorderHeight;
var verticalBorderWidth = SystemParameters.ResizeFrameVerticalBorderWidth;
</code></pre>
<p>These sizes will change when you modify the theme.</p>
|
5,891,555 |
Display the date, like "May 5th", using pythons strftime?
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/739241/python-date-ordinal-output">Python: Date Ordinal Output?</a> </p>
</blockquote>
<p>In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way to do this?</p>
| 5,891,598 | 5 | 4 | null |
2011-05-05 01:00:46.893 UTC
| 7 |
2011-05-05 15:27:19.23 UTC
|
2017-05-23 12:02:06.967 UTC
| null | -1 | null | 565,879 | null | 1 | 43 |
python|strftime
| 34,471 |
<p><code>strftime</code> doesn't allow you to format a date with a suffix.</p>
<p>Here's a way to get the correct suffix:</p>
<pre><code>if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
</code></pre>
<p><a href="http://snipplr.com/view/3468/python-date-suffixes-for-strftime/" rel="noreferrer"><strong>found here</strong></a></p>
<h2>Update:</h2>
<p>Combining a more compact solution based on Jochen's comment with <a href="https://stackoverflow.com/questions/5891555/display-the-date-like-may-5th-using-pythons-strftime/5891658#5891658">gsteff's answer</a>:</p>
<pre><code>from datetime import datetime as dt
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def custom_strftime(format, t):
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
print custom_strftime('%B {S}, %Y', dt.now())
</code></pre>
<p>Gives:</p>
<p><code>May 5th, 2011</code></p>
|
5,748,661 |
Most efficient way to check if an object is a value type
|
<p><strong>WARNING: THIS CODE SUCKS, SEE ANTHONY'S COMMENTS</strong></p>
<p>Which is faster?</p>
<p>1.</p>
<pre><code> public bool IsValueType<T>(T obj){
return obj is ValueType;
}
</code></pre>
<p>2.</p>
<pre><code> public bool IsValueType<T>(T obj){
return obj == null ? false : obj.GetType().IsValueType;
}
</code></pre>
<p>3.</p>
<pre><code> public bool IsValueType<T>(T obj){
return default(T) != null;
}
</code></pre>
<p>4.Something else</p>
| 5,748,763 | 6 | 8 | null |
2011-04-21 19:11:34.873 UTC
| 16 |
2021-07-28 14:11:18.023 UTC
|
2011-04-21 19:34:50.667 UTC
| null | 344,211 | null | 344,211 | null | 1 | 53 |
c#|.net|performance|value-type
| 64,413 |
<p>You aren't really testing an object - you want to test the <em>type</em>. To call those, the caller must know the type, but... meh. Given a signature <code><T>(T obj)</code> the only sane answer is:</p>
<pre><code>public bool IsValueType<T>() {
return typeof(T).IsValueType;
}
</code></pre>
<p>or if we want to use an example object for type inference purposes:</p>
<pre><code>public bool IsValueType<T>(T obj) {
return typeof(T).IsValueType;
}
</code></pre>
<p>this doesn't need boxing (<code>GetType()</code> is boxing), and doesn't have problems with <code>Nullable<T></code>. A more interesting case is when you are passing <code>object</code>...</p>
<pre><code> public bool IsValueType(object obj);
</code></pre>
<p>here, we already have massive problems with <code>null</code>, since that could be an empty <code>Nullable<T></code> (a struct) or a class. But A reasonable attempt would be:</p>
<pre><code>public bool IsValueType(object obj) {
return obj != null && obj.GetType().IsValueType;
}
</code></pre>
<p>but note that it is incorrect (and unfixable) for empty <code>Nullable<T></code>s. Here it becomes pointless to worry about boxing as we are already boxed.</p>
|
6,029,916 |
How to enable file sharing for my app?
|
<p>I have an image editing app where users can apply effects to photos. How could I enable it so that users can see my app in iTunes in the File Sharing tab and then just drag+drop photos to the app?</p>
<p>Some of the eBook readers like Stanza works like this and it would be a cool option. Maybe someone can point out a tutorial or resource that talks about how to enable and use this technique.</p>
| 6,029,954 | 7 | 1 | null |
2011-05-17 11:07:36.977 UTC
| 56 |
2020-08-13 04:40:13.813 UTC
| null | null | null | null | 472,300 | null | 1 | 170 |
ios|file-sharing
| 161,876 |
<p>You just have to set <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/uifilesharingenabled" rel="noreferrer"><code>UIFileSharingEnabled</code></a> (<code>Application Supports iTunes file sharing</code>) key in the info plist of your app. <a href="https://web.archive.org/web/20160904190038/https://developer.apple.com/library/ios/documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/CoreServicesLayer/CoreServicesLayer.html#//apple_ref/doc/uid/TP40007898-CH10-SW30" rel="noreferrer">Here's</a> a link for the documentation. Scroll down to the file sharing support part.</p>
<p>In the past, it was also necessary to define <code>CFBundleDisplayName</code> (<code>Bundle Display Name</code>), if it wasn't already there. <a href="https://stackoverflow.com/a/4546581/1436359">More details here</a>.</p>
|
39,231,880 |
Kubernetes API - Get Pods on Specific Nodes
|
<p>Reading the <a href="http://kubernetes.io/docs/user-guide/labels/#selecting-sets-of-nodes" rel="noreferrer">Kubernets documentation</a> it looks to be possible to select a certain range of pods based on labels. I want to select all the pods on one node but I don't want to label each pod on their corresponding node.</p>
<p>Am I missing something from the documentation or is it just not possible to select by node?</p>
<p>If I do:</p>
<pre class="lang-shell prettyprint-override"><code>kubectl get pods \
--output=wide
--namespace=$NS \
--server=$SERVER | head
#=>
NAME READY STATUS RESTARTS AGE NODE
</code></pre>
<p>Can any of these headers be used as selector? If yes, how to do it with <code>kubectl</code>? How to do it with the API?</p>
| 50,811,992 | 6 | 1 | null |
2016-08-30 15:42:02.073 UTC
| 51 |
2022-01-26 14:44:42.117 UTC
|
2022-01-26 00:07:42.46 UTC
| null | 5,963,316 | null | 3,556,705 | null | 1 | 191 |
kubernetes|kubectl
| 152,005 |
<p>As mentioned in the accepted answer the PR is now merged and you can get pods by node as follows:</p>
<pre><code>kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>
</code></pre>
|
5,365,464 |
MATLAB: Is it possible to overload operators on native constructs (cells, structs, etc)?
|
<p>I'm using cells to manage data in some stuff I'm working on. I'd like to be able to do things like:</p>
<pre><code>A = cellfun( @(X)( randn( 5,5 ) ), cell( 5,1 ), 'UniformOutput', 0 );
B = cellfun( @(X)( randn( 5,5 ) ), cell( 5,1 ), 'UniformOutput', 0 );
%#
%# Each of the following would fail if cell member dimensions
%# don't match up
%#
%# matrix sums for each cell entry
%# C = A + B;
C = cellfun( @(X,Y)( X + Y ), A, B, 'UniformOutput', 0 );
%#
%# direct/hadamard product
%# D = A .* B;
D = cellfun( @(X,Y)( X .* Y ), A, B, 'UniformOutput', 0 );
%#
%# matrix-matrix products (not across all entries)
%# E = A * B;
E = cellfun( @(X,Y)( X * Y ), A, B, 'UniformOutput', 0 );
</code></pre>
<p>However, I don't want the extremely verbose syntax to do it. It seems a bit overboard to create a new class for this when all I want to do is provide a definition for math operators on cells.</p>
<p>The question: Is a class the only way to go about it?</p>
<p>If I write a class to do this, it certainly makes it easier to write the code. The biggest negatives I see are related to optimizations, though there's a few other things that bug me about it..</p>
<p>Any optimizations going on behind the scenes (eg, when Jacket compiles something to run on a GPU) would potentially have a harder time determining what optimizations to make. As an example, suppose I have two cells (A,B) containing a number of matrices of appropriate dimension. If I write code to produce a new cell:</p>
<pre><code>Z = c1*A + c2*B
</code></pre>
<p>... with scalars {c1,c2}, I can write it in such a way that Jacket (or whatever) will easily determine that it should do the calculations as:</p>
<pre><code>Z{kk} = c1*A{kk} + c2*B{kk}
</code></pre>
<p>or perhaps an even better optimization than that. Otherwise. it may end up with something slower and/or less memory efficient, eg:</p>
<pre><code>temp1 = cellfun( @(X)( c1*X ), A );
temp2 = cellfun( @(X)( c2*X ), B );
Z = cellfun( @plus, temp1, temp2 );
</code></pre>
<p>Assuming MATLAB or Jacket are unable to optimize it, this would end up using too much memory.</p>
| 5,373,729 | 1 | 2 | null |
2011-03-19 22:50:29.383 UTC
| 14 |
2017-03-30 05:03:56.953 UTC
|
2017-03-30 05:03:56.953 UTC
| null | 52,738 | null | 549,246 | null | 1 | 17 |
matlab|operator-overloading|cell|arithmetic-expressions
| 2,876 |
<p>It is in fact possible to create new operators or overload existing ones for built-in data types in MATLAB. I describe one example of this in <a href="https://stackoverflow.com/a/2430278/52738">my answer</a> to another SO question about <a href="https://stackoverflow.com/q/2425251/52738">modifying the default overflow behavior of integer types</a>.</p>
<p>First, you may want to look at what methods currently exist for cell arrays. You can do this using the function <a href="http://www.mathworks.com/help/matlab/ref/methods.html" rel="nofollow noreferrer">METHODS</a>, and here's what I get in MATLAB R2010b:</p>
<pre><code>>> methods cell
Methods for class cell:
aa2nt issorted regexptranslate strfind
accumarray newdepfun reshape strjust
cell2struct nt2aa rna2dna strmatch
ctranspose nwalign seq2regexp strtok
display permute setdiff transpose
dna2rna regexp setxor union
intersect regexpi sort unique
ismember regexprep strcat
</code></pre>
<p>The arithmetic operator methods would show up in the above list as their <a href="http://www.mathworks.com/help/matlab/arithmetic-operators.html" rel="nofollow noreferrer">function equivalents</a>, like <code>plus</code> for the <code>+</code> operator or <code>times</code> for the <code>.*</code> operator. Only the <code>transpose</code> method (<code>.'</code> operator) is defined for cell arrays. You would have to create the rest yourself, defining how a given operator will behave for cell arrays arguments.</p>
<p>You can do this by first making a new folder called <code>@cell</code> and placing it in an existing folder on your <a href="https://www.mathworks.com/help/matlab/matlab_env/what-is-the-matlab-search-path.html" rel="nofollow noreferrer">MATLAB path</a>. You would then place your new methods in the <code>@cell</code> folder. For example, a <em>very</em> simple implementation of a <code>plus</code> method for cell arrays (without any input-checking, error-checking, etc.) would be this:</p>
<pre><code>function C = plus(A,B)
C = cellfun(@plus,A,B,'UniformOutput',false); %# Apply plus cell-wise
end
</code></pre>
<p>In the above code, you would probably first want to check that the operands <code>A</code> and <code>B</code> are cell arrays of the same size. However, you could create whatever unique functionality you want, such as allowing <code>B</code> to be a scalar value which would get added to every cell of <code>A</code>. It's totally up to you to define how the <code>+</code> operator will behave for cell arrays.</p>
<p>This would then allow you to write your code in a much more compact way, as in this example:</p>
<pre><code>>> A = {[1 2 3] [4 5] 6}; %# One 3-element cell array
>> B = {5 [4 5] 2}; %# Another 3-element cell array
>> C = A+B; %# Use the new plus operator
>> C{:} %# Display the cell contents
ans =
6 7 8
ans =
8 10
ans =
8
</code></pre>
<p>I can't really speak to the behind-the-scenes optimizations and how this might affect them. I know that the documentation <a href="http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html" rel="nofollow noreferrer">"Techniques for Improving Performance"</a> specifically mentions this about <a href="http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html#f8-790494" rel="nofollow noreferrer">overloading built-in functions</a>:</p>
<blockquote>
<p>Overloading MATLAB built-in functions
on any of the standard MATLAB data
classes can negatively affect
performance. For example, if you
overload the <code>plus</code> function to handle
any of the integer classes
differently, you may hinder certain
optimizations in the MATLAB built-in
function code for <code>plus</code>, and thus may
slow down any programs that make use
of this overload.</p>
</blockquote>
<p>However, in your case you aren't overloading <em>existing</em> functions for a class. You're simply creating new ones that didn't exist for that class, so it's hard to say what effect this may ultimately have on performance.</p>
|
5,453,109 |
How to round all values in a matrix?
|
<p>I use the following method to store all my correlations in a matrix:</p>
<pre><code>corrs <- cor(dataset, use="pairwise.complete.obs")
</code></pre>
<p>But now I'd like to round the values to two digits after the comma. How can I do that? I just found a round function but don't know how to apply it to all values.</p>
| 5,453,122 | 1 | 0 | null |
2011-03-27 23:07:21.31 UTC
| 1 |
2016-11-17 09:30:10.527 UTC
|
2011-03-27 23:10:36.673 UTC
| null | 142,162 |
anon
| null | null | 1 | 17 |
r|rounding
| 42,376 |
<p>Just as in your other question, use the function (<code>round</code>) you found :)</p>
<pre><code>corrs <- round(cor(dataset, use="pairwise.complete.obs"), 2)
</code></pre>
<p>For example:</p>
<pre><code>> round(cor(cars),2)
speed dist
speed 1.00 0.81
dist 0.81 1.00
</code></pre>
|
24,570,932 |
postgresql group by and inner join
|
<p>I want a query in SQL which does <code>INNER JOIN</code> and <code>GROUP BY</code> at the same time. I tried the following which doesn't work:</p>
<pre><code>SELECT customer.first_name, SUM(payment.amount)
FROM customer
GROUP BY customer.customer_id
INNER JOIN payment
ON payment.customer_id = customer.customer_id;
</code></pre>
<p>Thank you in advance!</p>
| 24,571,047 | 2 | 1 | null |
2014-07-04 09:23:38.677 UTC
| 9 |
2019-03-27 22:09:20.39 UTC
| null | null | null | null | 3,797,850 | null | 1 | 28 |
sql|postgresql|group-by|inner-join
| 32,792 |
<p>First, <code>GROUP BY</code> comes at the end of the query (just before <code>order by</code> or <code>having</code> clauses if you have some).</p>
<p>Then, all fields in the select which are not in an aggregation function must be in the group by clause.</p>
<p>so</p>
<pre><code>SELECT customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY customer.first_name;
</code></pre>
<p>But customers with same first_name will be grouped, which is probably not really what you want.</p>
<p>so rather</p>
<pre><code>SELECT customer.first_name, SUM(payment.amount)
FROM customer
INNER JOIN payment
ON payment.customer_id = customer.customer_id
GROUP BY customer.first_name, customer.customer_id;
</code></pre>
|
24,497,881 |
boost::asio::spawn yield as callback
|
<p>I'm trying to rewrite a project using <code>boost::asio::spawn</code> coroutines. Some parts of the project cannot be changed. For example, the storage protocol library is also written with <code>boost::asio</code>, but without coroutines. </p>
<p>The problem is how to convert <code>yield_context</code> into a normal callback (a <code>boost::function</code> object or a classical functor).</p>
<p>This is what we have in the storage library API:</p>
<pre><code>void async_request_data(uint64_t item_id, boost::function< void(Request_result *) > callback);
</code></pre>
<p>As we know from examples, the asio yield context can be used like this:</p>
<pre><code> my_socket.async_read_some(boost::asio::buffer(data), yield);
</code></pre>
<p>In this case a <code>boost::asio::yield_context</code> object serves as a callback for <strong>async_read_some</strong>. I would like to pass a <strong>yield</strong> object as the second argument to <code>async_request_data</code>, so i can use it in a synchronous manner.</p>
<p>How can this be done? I think it may be possible via some proxy-object, possibly using an approach based on <strong>asio_handler_invoke</strong>. But I am having trouble seeing how to do this. </p>
| 24,645,114 | 4 | 1 | null |
2014-06-30 19:49:20.657 UTC
| 8 |
2022-08-13 17:31:09.633 UTC
|
2014-07-06 04:16:46.073 UTC
| null | 3,697,273 | null | 1,671,032 | null | 1 | 13 |
c++|boost|boost-asio|coroutine
| 5,359 |
<p>Looks like the best documentation for this feature can be found in a C++ standard proposal written by the boost asio author:</p>
<p><a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4045.pdf" rel="noreferrer">N4045 – Library Foundations for Asynchronous Operations, Revision 2</a></p>
<p>See section 9.1 which says:</p>
<pre><code>handler_type_t<CompletionToken, void(error_code, size_t)> #3
handler(std::forward<CompletionToken>(token));
</code></pre>
<blockquote>
<p>3: The completion token is converted into a handler, i.e. a function object to be called
when the asynchronous operation completes. The signature specifies the arguments
that will be passed to the handler.</p>
</blockquote>
<p>I guess in your case the <code>CompletionToken</code> template argument will actually be <code>boost::asio::yield_context</code> and <code>handler_type</code> converts it to a callback object.</p>
<hr>
<p>Here is the code from section 9.1 updated to call your <code>async_request_data</code> function:</p>
<pre><code>template <class CompletionToken>
auto async_foo(uint64_t item_id, CompletionToken&& token)
{
handler_type_t<CompletionToken, void(Request_result *)>
handler(std::forward<CompletionToken>(token));
async_result<decltype(handler)> result(handler);
async_request_data(item_id, handler);
return result.get();
}
</code></pre>
|
19,674,311 |
JSON serializing Mongodb
|
<p>I am using the python package pymongo to retrieve data from a mongodb database.</p>
<pre><code>>>> r = collection.find() # returns an object of class 'Cursor'
</code></pre>
<p>Then I convert to a list</p>
<pre><code>>>> l = list(r) # returns a 'list' of 'dict'
</code></pre>
<p>here is what print(l) returns:</p>
<pre><code>>>> [{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'_id': 1, u'name': u'name1', u'value': 11},{u'date': datetime.datetime(2013, 11, 10, 10, 45), u'_id': 2, u'name': u'name2', u'value': 22}]
</code></pre>
<p>Now I need to convert to JSON so that I can manipulate it. </p>
<pre><code>>>> json.dumps(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2009, 11, 12, 11, 14) is not JSON serializable
</code></pre>
<p>I have also tried to follow <em><a href="http://api.mongodb.org/python/1.7/api/pymongo/json_util.html" rel="noreferrer">http://api.mongodb.org/python/1.7/api/pymongo/json_util.html</a></em> without success:
Edit: the recent version of the link is <a href="http://api.mongodb.org/python/current/api/bson/json_util.html" rel="noreferrer">http://api.mongodb.org/python/current/api/bson/json_util.html</a></p>
<pre><code>>>> json.dumps(l, default=json_util.default)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'json_util' is not defined
</code></pre>
<p><strong>Note:</strong> precisely I need to push this result to R using the R package rPython and its function rPython::python.get("l")</p>
<p><strong>Side Question</strong>: What is the u (u'Date', u'name', etc..) before each field in the list of dict?</p>
| 19,674,373 | 5 | 0 | null |
2013-10-30 05:09:45.743 UTC
| 11 |
2021-11-07 14:43:16.983 UTC
|
2020-05-20 06:44:02.597 UTC
| null | 958,409 | null | 482,711 | null | 1 | 32 |
python|mongodb|pymongo
| 67,608 |
<p>The pymongo documentation you pointed is obsolete. If you're using version 1.7 I recommend updating. With a more recent version you can do this:</p>
<pre><code>from bson.json_util import dumps
dumps(l)
</code></pre>
<p><a href="https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html" rel="noreferrer">https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html</a></p>
<p><strong>Side answer</strong>: <code>u'name'</code>, <code>u'date'</code>, <code>u'_id'</code> etc are the names of the fields of the document on the database.</p>
|
42,358,448 |
How to backup git stash content?
|
<ul>
<li>I have pending uncommitted works</li>
<li>I need to switch to another branch for some urgent work</li>
<li>As my current Work in Progress is not finished, I don't want to commit it. I use <code>git stash</code> to put it aside.</li>
</ul>
<p>Additionally, I would like to backup that stash content on a shared drive. Just for safety. What is an elegant solution to archive the stash content on file?</p>
| 42,358,522 | 5 | 0 | null |
2017-02-21 04:02:53.143 UTC
| 9 |
2022-04-01 22:01:59.96 UTC
| null | null | null | null | 657,067 | null | 1 | 29 |
git
| 11,030 |
<p>You can get the diff by running show command:</p>
<pre><code>git stash show -p > stash.diff
</code></pre>
<p>This is the diff file which you can use as a backup.</p>
<p>Later you can apply the diff to the existing repository:</p>
<pre><code>git apply stash.diff
# and potentially stash again:
git stash
</code></pre>
|
33,436,525 |
How to parse excel rows back to types using EPPlus
|
<p>EPPlus has a convenient <code>LoadFromCollection<T></code> method to get data of my own type into a worksheet.</p>
<p>For example if I have a class:</p>
<pre><code>public class Customer
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime Birthdate { get; set; }
}
</code></pre>
<p>Then the following code:</p>
<pre><code>var package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("Customers");
var customers = new List<Customer>{
new Customer{
Id = 1,
Firstname = "John",
Surname = "Doe",
Birthdate = new DateTime(2000, 1, 1)
},
new Customer{
Id = 2,
Firstname = "Mary",
Surname = "Moe",
Birthdate = new DateTime(2001, 2, 2)
}
};
sheet.Cells[1, 1].LoadFromCollection(customers);
package.Save();
</code></pre>
<p>...will add 2 rows to a worksheet called "Customers".</p>
<p>My question is if there is a convenient counterpart to extract the rows from excel (for example after some modifications have been made) back into my types.</p>
<p>Something like:</p>
<pre><code>var package = new ExcelPackage(inputStream);
var customers = sheet.Dimension.SaveToCollection<Customer>() ??
</code></pre>
<p>I have</p>
<ul>
<li>been looking through the EPPlus codebase</li>
<li>searched for any <a href="https://stackoverflow.com/search?page=2&tab=relevance&q=epplus%20save">saving</a> questions</li>
<li>searched for any <a href="https://stackoverflow.com/search?page=2&tab=relevance&q=epplus%20parse">parsing</a> questions</li>
<li>seen <a href="https://stackoverflow.com/questions/11685204/reading-excel-spreasheet-using-epplus">this</a> question on reading single cells</li>
</ul>
<p>... but found nothing on how to simply parse the rows to my type.</p>
| 37,746,915 | 2 | 0 | null |
2015-10-30 12:55:29.923 UTC
| 12 |
2016-06-10 12:14:42.227 UTC
|
2017-05-23 12:10:19.85 UTC
| null | -1 | null | 2,952,809 | null | 1 | 35 |
c#|epplus
| 34,088 |
<p>Inspired by the above I took it a slightly different route. </p>
<ol>
<li>I created an attribute and mapped each property to a column. </li>
<li>I use the DTO type to define what I expect each column to be</li>
<li>Allow columns to not be requried</li>
<li>Use EPPlus to convert the types</li>
</ol>
<p>By doing so it allows me to use traditional model validation, and embrace changes to column headers</p>
<p>--
Usage: </p>
<pre><code>using(FileStream fileStream = new FileStream(_fileName, FileMode.Open)){
ExcelPackage excel = new ExcelPackage(fileStream);
var workSheet = excel.Workbook.Worksheets[RESOURCES_WORKSHEET];
IEnumerable<ExcelResourceDto> newcollection = workSheet.ConvertSheetToObjects<ExcelResourceDto>();
newcollection.ToList().ForEach(x => Console.WriteLine(x.Title));
}
</code></pre>
<p>Dto that maps to excel</p>
<pre><code>public class ExcelResourceDto
{
[Column(1)]
[Required]
public string Title { get; set; }
[Column(2)]
[Required]
public string SearchTags { get; set; }
}
</code></pre>
<p>This is the attribute definition</p>
<pre><code>[AttributeUsage(AttributeTargets.All)]
public class Column : System.Attribute
{
public int ColumnIndex { get; set; }
public Column(int column)
{
ColumnIndex = column;
}
}
</code></pre>
<p>Extension class to handle mapping rows to DTO</p>
<pre><code>public static class EPPLusExtensions
{
public static IEnumerable<T> ConvertSheetToObjects<T>(this ExcelWorksheet worksheet) where T : new()
{
Func<CustomAttributeData, bool> columnOnly = y => y.AttributeType == typeof(Column);
var columns = typeof(T)
.GetProperties()
.Where(x => x.CustomAttributes.Any(columnOnly))
.Select(p => new
{
Property = p,
Column = p.GetCustomAttributes<Column>().First().ColumnIndex //safe because if where above
}).ToList();
var rows= worksheet.Cells
.Select(cell => cell.Start.Row)
.Distinct()
.OrderBy(x=>x);
//Create the collection container
var collection = rows.Skip(1)
.Select(row =>
{
var tnew = new T();
columns.ForEach(col =>
{
//This is the real wrinkle to using reflection - Excel stores all numbers as double including int
var val = worksheet.Cells[row, col.Column];
//If it is numeric it is a double since that is how excel stores all numbers
if (val.Value == null)
{
col.Property.SetValue(tnew, null);
return;
}
if (col.Property.PropertyType == typeof(Int32))
{
col.Property.SetValue(tnew, val.GetValue<int>());
return;
}
if (col.Property.PropertyType == typeof(double))
{
col.Property.SetValue(tnew, val.GetValue<double>());
return;
}
if (col.Property.PropertyType == typeof(DateTime))
{
col.Property.SetValue(tnew, val.GetValue<DateTime>());
return;
}
//Its a string
col.Property.SetValue(tnew, val.GetValue<string>());
});
return tnew;
});
//Send it back
return collection;
}
}
</code></pre>
|
41,573,283 |
Seaborn, violin plot with one data per column
|
<p>I would like to combine this violin plot <a href="http://seaborn.pydata.org/generated/seaborn.violinplot.html" rel="noreferrer">http://seaborn.pydata.org/generated/seaborn.violinplot.html</a> (fourth example with split=True) with this one <a href="http://seaborn.pydata.org/examples/elaborate_violinplot.html" rel="noreferrer">http://seaborn.pydata.org/examples/elaborate_violinplot.html</a>.</p>
<p>Actually, I have a dataFrame with a column <code>Success</code> (Yes or No) and several data column. For example :</p>
<pre><code>df = pd.DataFrame(
{"Success": 50 * ["Yes"] + 50 * ["No"],
"A": np.random.randint(1, 7, 100),
"B": np.random.randint(1, 7, 100)}
)
A B Success
0 6 4 Yes
1 6 2 Yes
2 1 1 Yes
3 1 2 Yes
.. .. .. ...
95 4 4 No
96 2 1 No
97 2 6 No
98 2 3 No
99 2 1 No
</code></pre>
<p>I would like to plot a violin plot for each data column. It works with :</p>
<pre><code>import seaborn as sns
sns.violinplot(data=df[["A", "B"]], inner="quartile", bw=.15)
</code></pre>
<p>But now, I would like to split the violin according to the <code>Success</code> column. But, using <code>hue="Success"</code> I got an error with <code>Cannot use 'hue' without 'x' or 'y'</code>. Thus how can I do to plot the violin plot by splitting according to "Success" column ?</p>
| 41,575,149 | 2 | 0 | null |
2017-01-10 16:11:24.827 UTC
| 10 |
2017-07-21 08:36:10.083 UTC
| null | null | null | null | 1,421,907 | null | 1 | 10 |
python|seaborn
| 15,108 |
<p>If understand your question correctly, you need to reshape your dataframe to have it in long format:</p>
<pre><code>df = pd.melt(df, value_vars=['A', 'B'], id_vars='Success')
sns.violinplot(x='variable', y='value', hue='Success', data=df)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/IXNT9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IXNT9.png" alt="enter image description here"></a></p>
|
69,696,321 |
IntelliJ - Invalid source release: 17
|
<p>I've created a new Java project in IntelliJ with Gradle that uses Java 17. When running my app it has the error <code>Cause: error: invalid source release: 17</code>.</p>
<p><strong>My Settings</strong></p>
<p>I've installed <code>openjdk-17</code> through <code>IntelliJ</code> and set it as my <code>Project SDK</code>.</p>
<p>The <code>Project language level</code> has been set to <code>17 - Sealed types, always-strict floating-point semantics</code>.</p>
<p><a href="https://i.stack.imgur.com/h6OBn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h6OBn.png" alt="enter image description here" /></a></p>
<p>In <code>Modules -> Sources</code> I've set the <code>Language level</code> to <code>Project default (17 - Sealed types, always strict floating-point semantics)</code>.</p>
<p><a href="https://i.stack.imgur.com/WxHWG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WxHWG.png" alt="modules->sources" /></a></p>
<p>In <code>Modules -> Dependencies</code> I've set the <code>Module SDK</code> to <code>Project SDK openjdk-17</code>.</p>
<p><a href="https://i.stack.imgur.com/0DMAk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0DMAk.png" alt="modules->dependencies" /></a></p>
<p>In <code>Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler</code> I've set the <code>Project bytecode version</code> to <code>17</code>.</p>
<p><a href="https://i.stack.imgur.com/jZxak.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jZxak.png" alt="enter image description here" /></a></p>
<p><strong>Gradle</strong></p>
<pre><code>plugins {
id 'org.springframework.boot' version '2.5.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.app'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-websocket'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'com.fasterxml.jackson.core:jackson-core:2.13.0'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
}
test {
useJUnitPlatform()
}
</code></pre>
<p>I've looked at all of the answers <a href="https://stackoverflow.com/questions/46280859/intellij-idea-error-java-invalid-source-release-1-9">here</a> but I can't seem to fix this. I must be missing something but I can't find it. I've not had any problems using Java 8 or 11.</p>
<p>How do I resolve this?</p>
| 70,215,091 | 10 | 0 | null |
2021-10-24 11:32:37.483 UTC
| 4 |
2022-08-24 20:02:30.053 UTC
| null | null | null | null | 2,934,534 | null | 1 | 76 |
java|gradle|intellij-idea|java-17
| 60,758 |
<p>In intellij just set Gradle JVM to Java version 17.</p>
<p>"File -> Settings.. -> Build, Execution, Deployment -> Build Tools -> Gradle"
there select your project and set Gradle JVM to your java 17.0.1</p>
|
23,116,330 |
MongoDB SELECT COUNT GROUP BY
|
<p>I am playing around with MongoDB trying to figure out how to do a simple</p>
<pre><code>SELECT province, COUNT(*) FROM contest GROUP BY province
</code></pre>
<p>But I can't seem to figure it out using the aggregate function. I can do it using some really weird group syntax</p>
<pre><code>db.user.group({
"key": {
"province": true
},
"initial": {
"count": 0
},
"reduce": function(obj, prev) {
if (true != null) if (true instanceof Array) prev.count += true.length;
else prev.count++;
}
});
</code></pre>
<p>But is there an easier/faster way using the aggregate function?</p>
| 23,116,396 | 9 | 0 | null |
2014-04-16 17:34:52.713 UTC
| 64 |
2021-07-13 16:25:38.867 UTC
|
2020-04-13 15:38:23.5 UTC
| null | 1,108,305 | null | 150,062 | null | 1 | 296 |
mongodb|group-by|aggregation-framework
| 388,132 |
<p>This would be the easier way to do it using <a href="http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/"><code>aggregate</code></a>:</p>
<pre class="lang-js prettyprint-override"><code>db.contest.aggregate([
{"$group" : {_id:"$province", count:{$sum:1}}}
])
</code></pre>
|
20,219,796 |
bootstrap collapse menu disappears when resizing screen
|
<p>I used bootstrap menu for my app. It looks like this:
<img src="https://i.stack.imgur.com/uTGot.png" alt="menu ok">
but when I change window size to smaller, it disappears - looks like this:
<img src="https://i.stack.imgur.com/Pbwt4.png" alt="menu disappears">
It disappears when its about ~965px wide (so its probably 979px). I tried <a href="https://stackoverflow.com/questions/15825442/fixed-bootstrap-navbar-disappearing-with-768-x-1024-view">this solution</a>, didnt work. May be I'm mixing bootstrap 2 and 3?
This is my menu code:</p>
<pre><code><div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="/">Digrin</a>
<div class="nav-collapse collapse">
<ul class="nav">
{{ request.path }}
<li{% block nav_stocks %}{% endblock %}><a href="/stocks/">Stocks</a></li>
<li{% block nav_mystocks %}{% endblock %}>
<a href="/stocks/mystocks">My Portfolio</a></li>
<li{% block nav_watchstocks %}{% endblock %}>
<a href="/stocks/watchstocks">Watcher</a></li>
{% if not user.is_authenticated %}
<li class="active"><a href="/accounts/login/?next=/stocks/">Login</a></li>
<li><a href="/accounts/register/">Register</a></li>
{% else %}
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
{{ user.username }}
<i class="caret"></i>
</a>
<ul class="dropdown-menu">
<li><a href="/accounts/password/change/">Change password</a></li>
{% if user.is_staff %}<li><a href="/admin">Admin</a></li>{% endif %}
<li><a href="/accounts/logout/?next=/stocks/">Logout</a></li>
</ul>
</li>
</ul>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
</code></pre>
<p>includes:</p>
<pre><code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le styles -->
<link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="{% static "css/bootstrap-responsive.css" %}" rel="stylesheet">
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="{% static "js/jquery-1.8.1.min.js" %}" type="text/javascript"></script>
<script src="{% static "js/bootstrap.min.js" %}" type="text/javascript"></script>
</code></pre>
<p>And <a href="http://www.digrin.com" rel="noreferrer">site</a> (far from finished)
If I zoom in, menu disappears as well.</p>
| 20,221,317 | 1 | 0 | null |
2013-11-26 14:28:06.79 UTC
| 2 |
2013-12-11 01:32:05.647 UTC
|
2017-05-23 12:34:24.807 UTC
| null | -1 | null | 2,026,022 | null | 1 | 16 |
css|twitter-bootstrap|collapse
| 44,825 |
<p>If you do not want your navbar links to be collapsed on smaller devices, then you need to remove the <code><div class="nav-collapse collapse"></code> element.</p>
<p>The basic structure should look something like this....</p>
<pre><code><div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<a class="brand" href="#">Title</a>
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>
</div>
</code></pre>
<p>If you want to keep the responsive functionality, then add the below code to within you <code>container</code> div. This will give you a button to toggle the collapsed menu on smaller devices. </p>
<pre><code> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
</code></pre>
<p>So then the end result would look something like this.</p>
<pre><code><div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<!-- Be sure to leave the brand out there if you want it shown -->
<a class="brand" href="#">Project name</a>
<!-- Everything you want hidden at 940px or less, place within here -->
<div class="nav-collapse collapse">
<!-- .nav, .navbar-search, .navbar-form, etc -->
</div>
</div>
</div>
</div>
</code></pre>
<p>Also, you do not have to nest a <code><ul class="nav"></code> element within a <code><ul class="nav"></code> element for the dropdown menus. The correct structure for you navigation items should look like this. </p>
<pre><code><ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Test
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
...
</ul>
</li>
</ul>
</code></pre>
|
63,967,346 |
Install vue 3.0 in laravel
|
<p>Is there a way to install vue 3.0 to Laravel 8? When I run</p>
<pre><code>npm install vue@next
</code></pre>
<p>It started installing Vue 3.0, but for some reason it also began installing <code>vue-template-compiler</code> v2.6.12. The following appears:</p>
<blockquote>
<pre><code> Additional dependencies must be installed. This will only take a moment.
Running: npm install vue-template-compiler --save-dev --production=false
</code></pre>
</blockquote>
<p>And then when I run</p>
<pre><code>npm run dev
</code></pre>
<p>The following error appears:</p>
<blockquote>
<ul>
<li>vue@3.0.0 (C:\wamp64\www\vue-sample\node_modules\vue\index.js)</li>
<li>vue-template-compiler@2.6.12 (C:\wamp64\www\vue-sample\node_modules\vue-template-compiler\package.json)</li>
</ul>
<p>This may cause things to work incorrectly. Make sure to use the same
version for both. If you are using vue-loader@>=10.0, simply update
vue-template-compiler. If you are using vue-loader@<10.0 or vueify,
re-installing vue-loader/vueify should bump vue-template-compiler to
the latest.</p>
<p>@ ./resources/js/app.js 19:35-79 @ multi ./resources/js/app.js
./resources/sass/app.scss</p>
</blockquote>
<p>I am completely new in Vue. What should I do?</p>
| 63,968,220 | 2 | 0 | null |
2020-09-19 09:40:37.403 UTC
| 9 |
2022-05-13 11:06:46.823 UTC
|
2021-11-24 08:17:08.7 UTC
| null | 8,172,857 | null | 3,263,252 | null | 1 | 23 |
laravel|vue.js|webpack|vue-component|vuejs3
| 23,180 |
<p><strong><strong>Update 2022</strong></strong></p>
<p><img src="https://i.stack.imgur.com/r3F27.png" alt="enter image description here" /></p>
<p>For those who prefer <a href="https://vitejs.dev/" rel="nofollow noreferrer">Vite</a>, there's a tool called <a href="https://laravel-vite.dev/" rel="nofollow noreferrer">Laravel Vite</a> which is a project based on PHP package, Vite plugin and preset, you could install it as follows :</p>
<pre><code>npx @preset/cli apply laravel:vite
</code></pre>
<p>This removes the default config in the Laravel fresh project.</p>
<p>For further details please check the different section in official <a href="https://laravel-vite.dev/" rel="nofollow noreferrer">docs</a></p>
<hr />
<p><strong>Update October 2020</strong></p>
<p>Now with <a href="https://github.com/JeffreyWay/laravel-mix/blob/master/UPGRADE.md" rel="nofollow noreferrer"><code>laravel-mix v6</code></a> you could run Vue 3 code in Laravel App:</p>
<p><strong>1. Installation :</strong></p>
<pre><code>npm i -D laravel-mix@next vue@next @vue/compiler-sfc vue-loader@next
</code></pre>
<p>then</p>
<pre><code>npm i
</code></pre>
<p>before doing that try to <strong>remove</strong> the following dependencies from <code>package.json</code> which some of them are added by <code>php artisan ui vue</code> :</p>
<ul>
<li><code>vue</code></li>
<li><code>vue-template-compiler</code></li>
<li><code>laravel-mix</code></li>
</ul>
<p><strong>2. Config:</strong></p>
<p>in the <code>package.json</code> change the scripts to the following ones:</p>
<pre><code>"scripts": {
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"production": "mix --production"
}
</code></pre>
<p><code>webpack.mix.js</code> should contain :</p>
<pre><code>const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js').vue();
</code></pre>
<p>The minimum content of <code>resources/js/app.js</code></p>
<pre><code>import { createApp } from 'vue';
import App from './components/App.vue'
createApp(App).mount("#app")
</code></pre>
<p>In order to avoid this confusing steps clone this <strong><a href="https://github.com/boussadjra/laravel-vue-3-starter" rel="nofollow noreferrer">REPOSITORY</a></strong> and start coding.</p>
<p><strong>OLD ANSWER</strong></p>
<p>Laravel doesn't support vue 3 yet, but you could try out <a href="https://www.npmjs.com/package/laravel-mix-vue3" rel="nofollow noreferrer">laravel-mix-vue3</a> :</p>
<p><strong>Installation</strong> :</p>
<pre><code>npm install @types/webpack-env @vue/compiler-sfc vue-loader@next laravel-mix-vue3 --save-dev
</code></pre>
<p><strong>Usage</strong> :</p>
<p>Configure in <code>webpack.mix.js</code> as follows :</p>
<pre><code>const mix = require("laravel-mix");
require("laravel-mix-vue3");
mix.vue3("resources/js/app.js", "public/js");
</code></pre>
|
53,448,450 |
How to resolve error "Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7..." when building in Android Studio
|
<p>I've created a new project by checking the "include kotlin" box in Android Studio 3 and out of the box I get an error while compiling</p>
<pre><code>"Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7..."
</code></pre>
<p>I have made sure all plugins are up to date and that the Android SDK is properly installed.</p>
<p>How can I solve for this error?</p>
| 53,448,758 | 2 | 0 | null |
2018-11-23 14:24:37.95 UTC
| 15 |
2020-05-12 15:03:38.413 UTC
|
2020-05-12 15:03:38.413 UTC
| null | 63,550 | null | 5,175,097 | null | 1 | 86 |
kotlin
| 71,823 |
<p><code>kotlin-stdlib-jre[7/8]</code> was deprecated a while ago, and has since been removed. The deprecation note was kept until <a href="https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jre7" rel="noreferrer">1.2.71</a>, which was the last version to release those artifacts. The official deprecation notice can be found <a href="https://kotlinlang.org/docs/reference/whatsnew12.html#standard-library" rel="noreferrer">here</a>. Using any of the deprecated versions (before it was removed) should also produce a warning in (at least) Android Studio and IntelliJ. </p>
<p>Use <a href="https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk7" rel="noreferrer"><code>kotlin-stdlib-jdk7</code></a> instead. It's the same dependency as <code>kotlin-stdlib-jre7</code> (except newer), but it was re-named to <code>kotlin-stdlib-jdk</code>. <code>kotlin-stdlib-jre</code> is now no longer maintained as a separate dependency. </p>
<p>Both IntelliJ and Android Studio currently generate new projects using <code>kotlin-stdlib-jre7</code>; <strong>this likely is a bug</strong>. They have probably not updated the project generators. Therefore, you have to manually replace the dependencies with working ones until they fix this. This is dependent on the Kotlin plugin. Update it if you haven't. <sub>I haven't checked whether it's been patched or not - if it has, that only fixes the creation of new projects. For updating from older versions, the rest of the answer still applies</sub></p>
<p>You naturally have to do this if you're on 1.2.71 or lower, and you're upgrading to 1.3.0 or higher.</p>
<p>These are the new valid dependencies as of Kotlin 1.3.0:</p>
<pre><code>implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
</code></pre>
<p>Where <code>$kotlinVersion</code> is either a variable containing the version, or a hard-coded version (i.e. <code>1.3.0</code>)</p>
<hr>
<p>Alternatively, you can use <a href="https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib" rel="noreferrer">the "plain" stdlib</a> (<code>kotlin-stdlib</code>) instead of the JDK-specific versions. But you have to change your dependency either way, so I recommend you go with <code>kotlin-stdlib-jdk7</code>, or if you plan on using Java 8, <code>kotlin-stdlib-jdk8</code> </p>
<p>The newest versions of the dependencies can also be found <a href="https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8" rel="noreferrer">here</a>. jdk7, jdk8, and the version-unspecific stdlib all follow the same versions (as per this edit - this could change in the future, but there'll likely be notices before that change happens), so whether you check jdk8, jdk7 or the regular one, all the versions should be universally available across the stdlib artifacts. </p>
<h1>Note for other build systems</h1>
<p>The same actual solution applies to other build systems as well, but the code is different. As there are a lot of build systems, I'm not going to include all of them, but the point is changing the artifact from <code>kotlin-stdlib-jre[num]</code> to <code>kotlin-stdlib-jdk[num]</code> (without brackets of course). Or, as mentioned earlier, <code>kotlin-stdlib</code>. </p>
<p>Independently of the build system, this bases itself on access to Maven Central and similar repositories. If your build system doesn't support this, and/or breaks with Maven-style conventions and repositories, you'll have to find what works for your build system.</p>
<h1>TL;DR:</h1>
<p>Use <code>org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version</code> or <code>org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version</code> (depending on which version you originally used) instead.</p>
|
19,017,555 |
SASS Math Calculation
|
<p>Trying to create a responsive grid of videos. Instead of using different %'s for each media query, I was hoping to use a standard SASS formula that calculates based on 100% width, however not sure if SASS can do this. The 40 in the below formula, takes into account 2 x 20px fixed margins (i.e this would be a 3-column grid).</p>
<p><strong>Ideal formula:</strong></p>
<pre><code>ul.videos {
li {
width: ((100% / 3) - 40);
}
}
</code></pre>
<p>Any way that CSS/SASS can handle this? Would prefer not to use JS if possible. </p>
| 19,017,700 | 3 | 0 | null |
2013-09-26 00:51:04.227 UTC
| 8 |
2018-03-02 18:45:06.92 UTC
| null | null | null | null | 1,309,527 | null | 1 | 27 |
css|responsive-design|sass
| 80,684 |
<p>Unfortunately you can't subtract 40px from 33%. SASS generates a standard CSS file to be interpreted by the browser, and at build time SASS doesn't know the dimensions of the browser.</p>
<p>However, you should be able to achieve the desired effect by using CSS margins, eg</p>
<pre><code>ul.videos {
li {
width: (100% / 3);
div {
margin: 0 20px;
}
}
}
</code></pre>
|
26,715,634 |
Variables in nested Foreach-Object and Where-Object
|
<p>I'm wondering how to work with nested Forach-Object, Where-Object and other Cmdlets in Powershell. For example this code:</p>
<pre><code>$obj1 | Foreach-Object {
$obj2 | Where-Object { $_ .... }
}
</code></pre>
<p>So in the code block of Foreach-Object I use the elements of <code>$obj1</code> as <code>$_</code>. But the same happenn in the code block of Where-Object with <code>$obj2</code>. So how can I access both objects elements in the Where-Object code block? I would have to do <code>$_.Arg1 -eq $_.Arg1</code> but this makes no sense.</p>
| 26,715,697 | 3 | 0 | null |
2014-11-03 13:44:38.077 UTC
| 4 |
2021-02-17 00:29:33.35 UTC
| null | null | null | null | 3,898,725 | null | 1 | 41 |
powershell
| 41,752 |
<p>afaik, You'll need to keep a reference to the outer loop by putting it in a local variable.</p>
<pre><code>$obj1 | Foreach-Object {
$myobj1 = $_
$obj2 | Where-Object { $_ .... }
}
</code></pre>
|
43,931,986 |
How to upgrade Angular CLI to the latest version
|
<p>Using <code>ng --version</code> I got:</p>
<blockquote>
<p>@angular/cli: 1.0.0</p>
</blockquote>
<p>which is not the latest release available.</p>
<p>Since I have Angular CLI globally installed on my system, in order to upgrade it I tried:</p>
<p><code>npm update angular-cli -g</code></p>
<p>But it does not work, because it stays to 1.0.0 version.</p>
| 43,931,987 | 10 | 0 | null |
2017-05-12 07:35:19.97 UTC
| 196 |
2022-08-09 08:30:30.233 UTC
| null | null | null | null | 3,497,671 | null | 1 | 102 |
angular|angular-cli
| 878,607 |
<p>After reading some issues reported on the GitHub repository, I found the solution.</p>
<p>In order to update the angular-cli package installed globally in your system, you need to run:</p>
<pre><code>npm uninstall -g @angular/cli
npm install -g @angular/cli@latest
</code></pre>
<p>Depending on your system, you may need to prefix the above commands with <code>sudo</code>.</p>
<p>Also, most likely you want to also update your local project version, because inside your project directory it will be selected with higher priority than the global one:</p>
<pre><code>rm -rf node_modules
npm uninstall --save-dev @angular/cli
npm install --save-dev @angular/cli@latest
npm install
</code></pre>
<p>thanks <em>grizzm0</em> for pointing this out on <a href="https://github.com/angular/angular-cli/issues/4391#issuecomment-277199786" rel="noreferrer">GitHub</a>.</p>
<p>After updating your CLI, you probably want to <a href="https://update.angular.io/" rel="noreferrer">update your Angular version</a> too.</p>
<p><strong>Note</strong>: if you are updating to Angular CLI 6+ from an older version, you might need to read <a href="https://stackoverflow.com/questions/51926816/ng-build-prod-does-not-minify-uglify-remove-comments-since-angular-cli-6/51926817">this</a>.</p>
<p><strong>Edit</strong>: In addition, if you were still on a 1.x version of the cli, you need to convert your <code>angular-cli.json</code> to <code>angular.json</code>, which you can do with the following command (check <a href="https://stackoverflow.com/questions/50232874/angular-6-migration-angular-cli-json-to-angular-json">this</a> for more details):</p>
<pre><code>ng update @angular/cli --from=1.7.4 --migrate-only
</code></pre>
|
21,912,197 |
Setting Different error bar colors in bar plot in matplotlib
|
<p>Following <a href="https://stackoverflow.com/questions/18973404/settting-different-bar-color-in-matplotlib-python/18973430#18973430">Setting Different Bar color in matplotlib Python</a></p>
<p>I would like to change the error bar colors. I have figured out a way after a number of attempts:</p>
<pre><code>a = plt.gca()
b = a.bar(range(4), [2]*4, yerr=range(4))
c = a.get_children()[8]
c.set_color(['r','r','b','r'])
</code></pre>
<p>Is there any better way? Certainly <code>a.get_children()[8]</code> is not a general solution at all.</p>
<p><img src="https://i.stack.imgur.com/YXGrn.png" alt="enter image description here"></p>
| 21,915,157 | 2 | 0 | null |
2014-02-20 15:26:56.213 UTC
| 4 |
2017-10-06 05:41:26.323 UTC
|
2017-10-06 05:41:26.323 UTC
| null | 6,885,902 | null | 691,867 | null | 1 | 28 |
python|matplotlib
| 44,275 |
<p>If you just want to set them to a single color, use the <code>error_kw</code> kwarg (expected to be a dict of keyword arguments that's passed on to <code>ax.errorbar</code>). </p>
<p>Also, just so you know, you can pass a sequence of facecolors directly to <code>bar</code>, though this won't change the errorbar color.</p>
<p>As a quick example:</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5,
color=['red', 'green', 'blue', 'cyan', 'magenta'],
error_kw=dict(ecolor='gray', lw=2, capsize=5, capthick=2))
ax.margins(0.05)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/ULoxE.png" alt="enter image description here"></p>
<p>However, if you want the errorbars to be different colors, you'll either need to plot them individually or modify them afterwards. </p>
<p>If you use the latter option, the capline colors actually can't be changed individually (note that they're not changed in @falsetru's example either). For example:</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
colors = ['red', 'green', 'blue', 'cyan', 'magenta']
container = ax.bar(range(4), [2] * 4, yerr=range(1, 5), alpha=0.5, color=colors,
error_kw=dict(lw=2, capsize=5, capthick=2))
ax.margins(0.05)
connector, caplines, (vertical_lines,) = container.errorbar.lines
vertical_lines.set_color(colors)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/uLDh8.png" alt="enter image description here"></p>
<p>The <code>caplines</code> object in the answer above is a tuple of two <code>Line2D</code>s: One line for all of the top caps, and one line for all of the bottom caps. There's not way to change the colors of the caps individually (it's easy to set them all to the same color) without removing that artist and creating a <code>LineCollection</code> in its place.</p>
<p>Therefore, you're better off just plotting the errorbars individually in this case.</p>
<p>E.g.</p>
<pre><code>import matplotlib.pyplot as plt
x, height, error = range(4), [2] * 4, range(1,5)
colors = ['red', 'green', 'blue', 'cyan', 'magenta']
fig, ax = plt.subplots()
ax.bar(x, height, alpha=0.5, color=colors)
ax.margins(0.05)
for pos, y, err, color in zip(x, height, error, colors):
ax.errorbar(pos + 0.4, y, err, lw=2, capsize=5, capthick=2, color=color)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/2z1kj.png" alt="enter image description here"></p>
|
21,464,918 |
Django bulk update with string replace
|
<p>I am trying to update and modify a string field Django's ORM. The equivalent SQL to do this is:</p>
<pre><code>UPDATE example_table SET string_field = REPLACE(string_field, 'old text', 'new text');
</code></pre>
<p>With that query, I expect <code>old text</code> and <code>old text more text</code> to be replaced with <code>new text</code> and <code>new text more text</code> respectively, for all the entries in the <code>string_field</code> column.</p>
<p><a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#update" rel="noreferrer">Bulk update()</a> seems promising, but doesn't allow me to modify only part of the field, and <a href="https://docs.djangoproject.com/en/dev/ref/models/expressions/#f-expressions" rel="noreferrer">F() expressions</a> only implement numeric changes, not string replace. I also looked at using <a href="https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly" rel="noreferrer">raw queries</a> to run the above SQL, but that seems like a sideways hack (especially since F() exists to do the same functionality on numbers), and I couldn't get them to actually execute.</p>
<p>I ended up with this, but it seems a shame to execute all the extra queries when I know there's a one line SQL statement to do it.</p>
<pre><code>for entry in ExampleModel.objects.all():
entry.string_field = entry.string_field.replace('old text', 'new text', 1)
entry.save()
</code></pre>
<p>Does this feature not exist in Django's ORM for strings yet? Is there something I overlooked in the docs?</p>
<p>Related SO questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15319875/generate-update-query-using-django-orm">generate update query using django orm</a></li>
<li><a href="https://stackoverflow.com/questions/12030143/sql-statement-to-remove-part-of-a-string">SQL statement to remove part of a string</a></li>
</ul>
| 41,597,477 | 4 | 1 | null |
2014-01-30 18:42:13.007 UTC
| 8 |
2021-06-13 13:17:37.593 UTC
|
2017-05-23 10:30:49.21 UTC
| null | -1 | null | 2,475,775 | null | 1 | 24 |
python|django|django-orm
| 12,591 |
<p>Tested with django 1.9</p>
<pre><code>from django.db.models import F, Func, Value
ExampleModel.objects.filter(<condition>).update(
string_field=Func(
F('string_field'),
Value('old text'), Value('new text'),
function='replace',
)
)
</code></pre>
<p><strong>UPDATE Django 2.1</strong>
<a href="https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#replace" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#replace</a></p>
<pre><code>from django.db.models import Value
from django.db.models.functions import Replace
ExampleModel.objects.filter(<condition>).update(
string_field=Replace('string_field', Value('old text'), Value('new text'))
)
</code></pre>
|
21,622,193 |
Python-3.2 coroutine: AttributeError: 'generator' object has no attribute 'next'
|
<p>Quoting from <em>Python Essential Reference</em>, by David Beazley, page 20:</p>
<blockquote>
<p>Normally, functions operate on a single set of input arguments. However, a function can also be written to operate as a task that processes a sequence of inputs sent to it. This type of function is known as a <em>coroutine</em> and is created by using the <code>yield</code> statement as an expression (yield) as shown in this example:</p>
</blockquote>
<pre><code>def print_matches(matchtext):
print "Looking for", matchtext
while True:
line = (yield) # Get a line of text
if matchtext in line:
print line
</code></pre>
<blockquote>
<p>To use this function, you first call it, advance it to the first (yield), and then start sending data to it using <code>send()</code>. For example:</p>
</blockquote>
<pre><code>>>> matcher = print_matches("python")
>>> matcher.next() # Advance to the first (yield)
Looking for python
>>> matcher.send("Hello World")
>>> matcher.send("python is cool")
python is cool
>>> matcher.send("yow!")
>>> matcher.close() # Done with the matcher function call
</code></pre>
<p>Based on that information, I wrote this code:</p>
<pre><code>#!/usr/bin/python3.2
import sys
def match_text(pattern):
line = (yield)
if pattern in line:
print(line)
x = match_text('apple')
x.next()
for line in input('>>>> '):
if x.send(line):
print(line)
x.close()
</code></pre>
<p>But I get an error message like:</p>
<pre><code>Traceback (most recent call last):
File "xxx", line 9, in <module>
matcher.next() # Advance to the first (yield)
AttributeError: 'generator' object has no attribute 'next'
</code></pre>
<p>Why doesn't this code (or the code from the book, for that matter) work in Python 3.2? It seems that what is supposed to be a coroutine, is treated as a generator instead - why? What is going on here?</p>
| 21,622,696 | 3 | 1 | null |
2014-02-07 07:54:13.93 UTC
| 5 |
2022-07-19 16:48:54.593 UTC
|
2022-07-19 16:48:54.593 UTC
| null | 523,612 |
user621819
| null | null | 1 | 42 |
python|python-3.x
| 67,504 |
<p>You're getting thrown off by the error message; type-wise, Python doesn't make a distinction - you can <code>.send</code> to anything that uses <code>yield</code>, even if it doesn't do anything with the sent value internally.</p>
<p>In 3.x, there is no longer a <code>.next</code> method attached to these; instead, use the built-in free function <code>next</code>:</p>
<pre class="lang-py prettyprint-override"><code>next(matcher)
</code></pre>
|
9,216,185 |
Nodejs Passport display username
|
<p>In nodeJS I am using the passport module for authentication. I would like to show the username of the currently logged in user.</p>
<p>I tried the following code:</p>
<pre><code>passport.displayName
</code></pre>
<p>and</p>
<pre><code>Localstrategy.username
</code></pre>
<p>And for more info please also see:
<a href="http://passportjs.org/docs/profile">http://passportjs.org/docs/profile</a></p>
<p>But that is not working. Any suggestions?</p>
<p>Thanks</p>
| 9,218,855 | 5 | 0 | null |
2012-02-09 17:57:36.43 UTC
| 11 |
2019-01-24 13:07:32.96 UTC
|
2015-06-24 14:16:57.343 UTC
| null | 2,297,345 | null | 1,177,899 | null | 1 | 28 |
node.js|passport.js
| 42,541 |
<p>The user (as supplied by the verify callback), is set as a property on the request at <code>req.user</code>.</p>
<p>Any properties of the user can be accessed through that object, in your case <code>req.user.username</code> and <code>req.user.displayName</code>.</p>
<p>If you're using Express, and want to expose the username as a variable within a template, that can be done when rendering:</p>
<pre><code>app.get('/hello', function(req, res) {
res.render('index.jade', { username: req.user.username });
});
</code></pre>
|
9,022,656 |
TypeError: unhashable type: 'numpy.ndarray'
|
<p>From a text file containing three columns of data I want to be able to just take a <code>slice</code> of data from all three columns where the values in the first column are equal to the values defined in <code>above</code>. I then want to put the slice of data into a new array called <code>slice</code> (I am using <strong>Python 2.7</strong>)</p>
<pre><code>above = range(18000, 18060, 5)
data = np.loadtxt(open('data.txt'), delimiter=None)
energies = (np.hsplit(data, 3))[0]
slice = set(energies)&set(above)
</code></pre>
<p>The above comes back with:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
set(energies)&set(above)
TypeError: unhashable type: 'numpy.ndarray
</code></pre>
| 9,022,915 | 2 | 0 | null |
2012-01-26 17:39:55.083 UTC
| 5 |
2018-12-26 09:41:40.513 UTC
|
2015-09-30 15:41:13.453 UTC
| null | 2,062,965 | null | 1,171,835 | null | 1 | 69 |
python|numpy
| 384,337 |
<p>Your variable <code>energies</code> probably has the wrong shape:</p>
<pre><code>>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
</code></pre>
<p>And that's what happens if you read columnar data using your approach:</p>
<pre><code>>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
</code></pre>
<p>Probably you can simply use</p>
<pre><code>>>> data[:,0]
array([ 1., 3., 5., 8.])
</code></pre>
<p>instead.</p>
<p>(P.S. Your code looks like it's undecided about whether it's <code>data</code> or <code>elementdata</code>. I've assumed it's simply a typo.)</p>
|
33,993,461 |
PHP - remove all non-numeric characters from a string
|
<p>What is the best way for me to do this? Should I use regex or is there another in-built PHP function I can use?</p>
<p>For example, I'd want: <code>12 months</code> to become <code>12</code>. <code>Every 6 months</code> to become <code>6</code>, <code>1M</code> to become <code>1</code>, etc.</p>
| 33,993,530 | 2 | 1 | null |
2015-11-30 07:29:00.13 UTC
| 18 |
2022-01-12 00:44:46.013 UTC
|
2022-01-12 00:44:46.013 UTC
| null | 2,370,483 | null | 2,884,981 | null | 1 | 107 |
php|string
| 160,600 |
<p>You can use <a href="http://php.net/manual/en/function.preg-replace.php" rel="noreferrer">preg_replace</a> in this case;</p>
<pre><code>$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
</code></pre>
<p>$res return 6 in this case.</p>
<p>If want also to include decimal separator or thousand separator check this example:</p>
<pre><code>$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
</code></pre>
<p>$res returns "123.099" in this case</p>
<p>Include period as decimal separator or thousand separator: "/[^0-9.]/"</p>
<p>Include coma as decimal separator or thousand separator: "/[^0-9,]/"</p>
<p>Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"</p>
|
22,849,661 |
How to make Task.WaitAll() to break if any exception happened?
|
<p>I want to make Task.WaitAll() to break out if any of the running tasks throws an exception, so that I don't have to wait for 60 seconds to finish. How do I achieve such behavior? If WaitAll() cannot achieve that, is there any other c# feature or workaround?</p>
<pre><code>Task task1 = Task.Run(() => throw new InvalidOperationException());
Task task2 = ...
...
try
{
Task.WaitAll(new Task[]{task1, task2, ...}, TimeSpan.FromSeconds(60));
}
catch (AggregateException)
{
// If any exception thrown on any of the tasks, break out immediately instead of wait all the way to 60 seconds.
}
</code></pre>
| 22,851,991 | 4 | 1 | null |
2014-04-03 21:49:26.323 UTC
| 5 |
2019-12-04 17:01:31.15 UTC
|
2014-04-04 01:36:53.63 UTC
| null | 1,768,303 | null | 926,958 | null | 1 | 33 |
c#|task-parallel-library|task|async-await
| 9,247 |
<p>The following should do it without altering the code of the original tasks (untested): </p>
<pre><code>static bool WaitAll(Task[] tasks, int timeout, CancellationToken token)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
var proxyTasks = tasks.Select(task =>
task.ContinueWith(t => {
if (t.IsFaulted) cts.Cancel();
return t;
},
cts.Token,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Current).Unwrap());
return Task.WaitAll(proxyTasks.ToArray(), timeout, cts.Token);
}
</code></pre>
<p>Note it only tracks faulted tasks (those which threw). If you need to track cancelled tasks as well, make this change:</p>
<pre><code>if (t.IsFaulted || t.IsCancelled) cts.Cancel();
</code></pre>
<p><strong>Updated</strong>, waiting on the task proxies is redundant here, as pointed out by @svick in the comments. He proposes an improved version: <a href="https://gist.github.com/svick/9992598" rel="nofollow noreferrer">https://gist.github.com/svick/9992598</a>.</p>
|
7,641,130 |
Center text in table cell
|
<p>I can't seem to find the answer to my issue. I have a table with two rows and two columns (like the code shown below), how do I center align the text in specific cells. I would like to center align the text in one or two of the cells - not all the cells. </p>
<pre class="lang-html prettyprint-override"><code><div style="text-align: center;">
<table style="margin: 0px auto;" border="0">
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
</code></pre>
| 7,641,142 | 2 | 0 | null |
2011-10-03 21:57:41.237 UTC
| 1 |
2017-07-10 17:44:59.747 UTC
|
2017-07-10 17:44:59.747 UTC
| null | 4,370,109 | null | 973,738 | null | 1 | 36 |
html|html-table|alignment|center
| 159,309 |
<p>I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:</p>
<pre><code>.ui-helper-center {
text-align: center;
}
</code></pre>
<p>And then add the <code>ui-helper-center</code> class to the table cells for which you wish to control the alignment:</p>
<pre><code><td class="ui-helper-center">Content</td>
</code></pre>
<hr>
<p><strong>EDIT</strong>: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.</p>
<p>See <a href="https://stackoverflow.com/questions/7641130/center-text-in-table-cell/7641141#7641141">Gabe's answer</a> for how to include the CSS rule into your page.</p>
|
31,414,106 |
Get list of Excel files in a folder using VBA
|
<p>I need to get the names of all the Excel files in a folder and then make changes to each file. I've gotten the "make changes" part sorted out. Is there a way to get a list of the <code>.xlsx</code> files in one folder, say <code>D:\Personal</code> and store it in a String Array.</p>
<p>I then need to iterate through the list of files and run a macro on each of the files which I figured I can do using:</p>
<pre><code>Filepath = "D:\Personal\"
For Each i in FileArray
Workbooks.Open(Filepath+i)
Next
</code></pre>
<p>I had a look at <a href="https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba">this</a>, however, I wasn't able to open the files cause it stored the names in <code>Variant</code> format.</p>
<p>In short, how can I use VBA to get a list of Excel filenames in a specific folder?</p>
| 31,428,399 | 6 | 4 | null |
2015-07-14 18:07:03.313 UTC
| 6 |
2020-02-13 17:50:05.44 UTC
|
2018-07-09 19:34:03.733 UTC
| null | -1 | null | 5,020,807 | null | 1 | 31 |
vba|excel|excel-2010
| 235,785 |
<p>Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.</p>
<pre><code>Function listfiles(ByVal sPath As String)
Dim vaArray As Variant
Dim i As Integer
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Function
ReDim vaArray(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
vaArray(i) = oFile.Name
i = i + 1
Next
listfiles = vaArray
End Function
</code></pre>
<p>It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).</p>
|
18,878,083 |
Can I use variables on an IPython notebook markup cell?
|
<p>I have an IPython notebook and I would like to use one of my variables inside a markup cell. Is this even possible? If so, how do you do it?</p>
| 19,328,029 | 4 | 0 | null |
2013-09-18 16:57:44.737 UTC
| 12 |
2019-10-20 05:26:32.053 UTC
|
2019-10-20 05:26:32.053 UTC
| null | 6,873,133 | null | 2,748,066 | null | 1 | 77 |
jupyter-notebook|ipython
| 69,612 |
<p><strike>Currently, this is not possible, however there is a large discussion on this topic here <a href="https://github.com/ipython/ipython/pull/2592" rel="noreferrer">https://github.com/ipython/ipython/pull/2592</a>.</strike> The PR is currently closed, but a corresponding issue is opened <a href="https://github.com/ipython/ipython/issues/2958" rel="noreferrer">https://github.com/ipython/ipython/issues/2958</a> and marked as wishlist.</p>
<h2>Update</h2>
<p>In the meantime an IPython extension has appeared which allows to render python variables in markdown cells. This extension is part of the <a href="https://github.com/ipython-contrib/IPython-notebook-extensions" rel="noreferrer">IPython notebook extensions</a> and works with IPython 2.x and 3.x. For a detailed description see the <a href="https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/python-markdown" rel="noreferrer">wiki page</a>.</p>
|
19,101,361 |
iOS7 - Change UINavigationBar border color
|
<p>Is it possible to change the grey border-bottom color of the UINavigationBar in iOS7?</p>
<p>I already tried to remove to border, but this is not working:</p>
<pre><code>[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
</code></pre>
<p>Thanks!</p>
| 19,102,874 | 15 | 1 | null |
2013-09-30 18:37:36.337 UTC
| 21 |
2017-07-24 10:09:08.093 UTC
| null | null | null | null | 2,820,349 | null | 1 | 29 |
colors|border|uinavigationbar|ios7|xcode5
| 40,238 |
<p>This will help you :)</p>
<pre><code>[self.navigationController.navigationBar.layer setBorderWidth:2.0];// Just to make sure its working
[self.navigationController.navigationBar.layer setBorderColor:[[UIColor redColor] CGColor]];
</code></pre>
|
18,956,063 |
Memory usage of Docker containers
|
<p>I am using Docker to run some containerized apps. I am interested in measuring how much resources they consume (as far as regarding CPU and Memory usage).</p>
<p>Is there any way to measure the resources consumed by Docker containers like RAM & CPU usage?</p>
<p>Thank you.</p>
| 18,979,217 | 4 | 1 | null |
2013-09-23 09:38:52.5 UTC
| 3 |
2022-04-29 11:37:13.193 UTC
| null | null | null | null | 577,598 | null | 1 | 42 |
memory|resources|cpu-usage|measurement|docker
| 24,436 |
<p>Update: See @Adrian Mouat's answer below as docker now supports <code>docker stats</code>! </p>
<p>There isn't a way to do this that's built into docker in the current version. Future versions will support this via an api or plugin. </p>
<ul>
<li><a href="https://github.com/dotcloud/docker/issues/36" rel="noreferrer">https://github.com/dotcloud/docker/issues/36</a></li>
</ul>
<p>It does look like there's an lxc project that you should be able to use to track CPU and Memory.</p>
<ul>
<li><a href="https://github.com/Soulou/acadock-live-lxc" rel="noreferrer">https://github.com/Soulou/acadock-live-lxc</a></li>
</ul>
|
36,835,615 |
Difference between input-group and form-group
|
<p>What is the difference in use between the css classes <code>input-group</code> and <code>form-group</code> in Bootstrap?</p>
| 36,837,392 | 2 | 2 | null |
2016-04-25 08:38:06.8 UTC
| 22 |
2019-06-12 13:12:28.28 UTC
|
2019-06-12 13:12:28.28 UTC
| null | 2,440 | null | 5,520,621 | null | 1 | 68 |
html|twitter-bootstrap|twitter-bootstrap-3
| 49,572 |
<p>Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to the text-based inputs. For example, you can add the $ symbol, @ for a Twitter username, or anything else as required.</p>
<p>Form groups are used to wrap labels and form controls in a div to get optimum spacing between the label and the control. </p>
<p>Therefore, use both form-group and input-group as required. Do wrap your label and input in a form-group tag. If any of your input field required to prepended/appended with text/button, wrap the control with input-group. Below is the example, combining both of them. Hope this helps</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<body>
<div class="container-fluid justify-content-center">
<form role="form" class="pt-3">
<div class="form-group row">
<label for="inputfield1" class="col-sm-2 control-label">Generic input</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputfield1" placeholder="Generic input..." />
</div>
</div><!-- .form-group -->
<div class="form-group row">
<label for="inputfield2" class="col-sm-2 control-label">Money value</label>
<div class="input-group col-sm-10">
<span class="input-group-prepend input-group-text">$</span>
<input type="text" class="form-control" id="inputfield2" placeholder="Money value..." />
<span class="input-group-append input-group-text">.00</span>
</div>
</div><!-- .form-group -->
<div class="form-group row">
<label for="inputfield3" class="col-sm-2 control-label">Username</label>
<div class="input-group col-sm-10">
<span class="input-group-prepend input-group-text">@</span>
<input type="text" class="form-control" id="inputfield3" placeholder="Username..." />
</div>
</div><!-- .form-group -->
</form>
</div>
</body></code></pre>
</div>
</div>
</p>
|
40,847,472 |
Why @Nonnull annotation checked at runtime?
|
<p>I have a function with following signature</p>
<pre><code>public static String myFunction(@Nonnull String param)
</code></pre>
<p>When I call it with param as null, I get the following exception:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Argument for @Nonnull parameter 'param' of com/MyClass.myFunction must not be null
at com.MyClass.$$$reportNull$$$0(MyClass.java)
</code></pre>
<p>javax.annotation.Nonnull supposed not to be checked at runtime.</p>
<p>Who actually throws the exception and why?</p>
<p>P.S. I run Tomcat server in debug mode from IntelliJ IDEA 2016.3 with Oracle JDK 1.8.0_102</p>
| 40,847,858 | 1 | 2 | null |
2016-11-28 15:06:47.16 UTC
| 10 |
2019-09-05 05:43:05.8 UTC
| null | null | null | null | 3,004,779 | null | 1 | 58 |
java|intellij-idea|non-nullable
| 14,288 |
<p>When you compile your project in IntelliJ IDEA, it instruments the bytecode of compiled classes to add runtime checks for various flavors of <code>@Nonnull</code> annotations. This behavior is controlled by the option:</p>
<p>Settings | Build, Execution, Deployment | Compiler | [x] Add runtime assertions for not-null-annotated methods and parameters.</p>
<p><a href="https://i.stack.imgur.com/lP8Rf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lP8Rf.png" alt="Screenshot of "Add runtime assertions for notnull-annotated methods and parameters."></a></p>
|
18,278,774 |
Search Git remote all branches for file contents
|
<p>Is it possible to search all of my Git remote branches for specific file contents (not just a file, but contents within them)?</p>
<p>My remotes are on GitHub, in case that helps...</p>
| 18,279,145 | 2 | 0 | null |
2013-08-16 17:14:11.173 UTC
| 10 |
2019-06-20 17:06:24.347 UTC
|
2019-06-20 17:03:39.18 UTC
| null | 63,550 | null | 418,864 | null | 1 | 21 |
git|github
| 11,049 |
<p>You can try this:</p>
<pre><code>git grep 'search-string' $(git ls-remote . 'refs/remotes/*' | cut -f 2)
</code></pre>
<p>That will search all remote branches for <code>search-string</code>. Since the symbolic reference <code>HEAD</code> is mirrored, you may end up searching the same commit twice. Hopefully that's not an issue. If so, you can filter it out with:</p>
<pre><code>git grep 'search-string' \
$(git ls-remote . 'refs/remotes/*' | grep -v HEAD | cut -f 2)
</code></pre>
<p>If you need to dig through your entire history, you can also try:</p>
<pre><code>git grep 'search-string' $(git rev-list --all)
</code></pre>
|
1,053,396 |
Updating report parameters based on parameter selection? (SSRS)
|
<p>I've created a report in SSRS with two report parameters. I'd like the second to update it's values based on the selection in the first. The first is a list of sales agents, and the second is a list of distributors. Each agent can have many distributors.</p>
<p>So if the report user selects an agent, I'd like only their distributors to show in list for the second parameters. Obviously the parameter values will come from a query, but I don't know how to make it rebind the list once they select an agent.</p>
| 1,053,407 | 4 | 0 | null |
2009-06-27 18:46:18.313 UTC
| 9 |
2016-09-14 16:54:53.893 UTC
|
2016-09-14 16:54:53.893 UTC
| null | 3,347,858 | null | 1,365 | null | 1 | 11 |
sql-server-2005|reporting-services
| 35,916 |
<p>This works automagically if you order your parameters and datasets correctly</p>
<ul>
<li>First, set up a primary (report) dataset, then a dataset for each parameter dropdown. Code the <code>WHERE</code> clause in the datasets to make the dependencies correct across parameter variables</li>
<li>Secondly, order your parameters in the Report | Parameters menu so that the <em>first</em> variable/parameter you want the user to fill in is at the top, and make the second dataset depend on that parameter. Follow this ordering through the parameters; the final parameter(s) should be the one(s) the actual report dataset depends on.</li>
<li>Repeat for subsequent parameters</li>
</ul>
<p>This will work if your <code>WHERE</code> clause in the second and subsequent datasets have variables that SSRS knows are populated from earlier parameters.</p>
<p>As an example, I have three datasets from the venerable <code>pubs</code> database (sample in 2000).</p>
<p><code>pubslist</code> is used to populate the @p parameter, and looks like this:</p>
<pre><code> select pub_id, pub_name from publishers
</code></pre>
<p><code>titleslist</code> populates the @t parameter, and looks like this:</p>
<pre><code> select title_id, title from titles where pub_id = @p
</code></pre>
<p>Finally, <code>reportdataset</code> looks like this:</p>
<pre><code> select title, price, ytd_sales from titles where title_id = @t
</code></pre>
<p>The order of the parameters in the <code>Report | Report Parameters</code> menu is crucial; because the datasets must be executed in the order shown above, and the @t parameter is in a dataset that relies on the @p parameter being set first, we move @p to the top of the list.</p>
<p>Now, SSRS evaluates the dataset needed to fill the dropdown for the first parameter with labels. It relies on a dataset that doesn't need a parameter, so can be produced immediately.</p>
<p>Then, having got that parameter value, it can populate the second parameter's dropdown. That in turn results in the report being produced.</p>
|
1,333,922 |
CouchDB versioning strategy
|
<p>Would the following be a viable strategy for implementing versioning(using "example" as a sample document type):</p>
<p>Have one original document where the type field is named example_original.</p>
<p>Subsequent changes to the document all have type example_change and the id of example_original document as a key. The change would also carry a timestamp.</p>
<p>Keep one doc with type example_current that is the result of example_original with all example_change "applied". A new example_change document would automatically be applied to this document.</p>
<p>Finding a specific version would consist in retrieving the example_original doc and applying the desired changes (mostly up to a certain timestamp, but it could also be a number of changes).</p>
<p>I should mention that my use-case will involve a limited number of changes to the original. Most updates will consist of new original documents. While this is my current use-case I would also be interested in issues that would result if many changes where involved.</p>
<p>What pros and cons do you see in this approach?</p>
| 1,334,016 | 4 | 2 | null |
2009-08-26 11:02:44.277 UTC
| 12 |
2015-09-20 16:12:53.887 UTC
|
2009-08-26 11:46:08.807 UTC
| null | 146,325 | null | 53,943 | null | 1 | 23 |
versioning|couchdb|database-versioning|document-storage
| 12,378 |
<p>My first worry is: When "getting" a certain version, can you apply the changes to the original without modifying the database?</p>
<p>Will you ever need to delete something from the history? Are you really sure? Really, really sure? How about branches?</p>
<p>All in all, this looks like a complex strategy. Keep in mind that I've heard about CouchDB but never used it. I'd go for a more simple approach:</p>
<ol>
<li><p>When you create a document, you assign a UUID. Don't use the name or you'll run into trouble during rename operations. Add a version field that reads "1". Create a second document which contains a list of documents with the same UUID or add a "parent" pointer to the first document.</p>
<p>Having a "history document" per document allows for faster navigation of the history but parent pointers are more "safe" (since you can't easily create illegal structures with them).</p>
</li>
<li><p>When you create a new revision, reuse the UUID and assign a new, unique version. Update the history document or the parent pointer.</p>
</li>
</ol>
<p>This strategy is pretty simple to implement and allows all kinds of flexibility later. You can erase parts of the history easily, rename is simple, and you can create branches.</p>
|
10,006 |
What is the easiest way to add compression to WCF in Silverlight?
|
<p>I have a silverlight 2 beta 2 application that accesses a WCF web service. Because of this, it currently can only use basicHttp binding. The webservice will return fairly large amounts of XML data. This seems fairly wasteful from a bandwidth usage standpoint as the response, if zipped, would be smaller by a factor of 5 (I actually pasted the response into a txt file and zipped it.). </p>
<p>The request does have the "Accept-Encoding: gzip, deflate" - Is there any way have the WCF service gzip (or otherwise compress) the response?</p>
<p>I did find this <a href="http://www.vistax64.com/indigo/113763-wcf-client-j2ee-server-using-gzip.html" rel="noreferrer">link</a> but it sure seems a bit complex for functionality that should be handled out-of-the-box IMHO.</p>
<p>OK - at first I marked the solution using the System.IO.Compression as the answer as I could never "seem" to get the IIS7 dynamic compression to work. Well, as it turns out:</p>
<ol>
<li><p>Dynamic Compression on IIS7 <strong>was</strong> working al along. It is just that Nikhil's Web Developer Helper plugin for IE did not show it working. My guess is that since SL hands the web service call off to the browser, that the browser handles it "under the covers" and Nikhil's tool never sees the compressed response. I was able to confirm this by using Fiddler which monitors traffic external to the browser application. In fiddler, the response was, in fact, gzip compressed!!</p></li>
<li><p>The other problem with the System.IO.Compression solution is that System.IO.Compression does not exist in the Silverlight CLR.</p></li>
</ol>
<p>So from my perspective, the EASIEST way to enable WCF compression in Silverlight is to enable Dynamic Compression in IIS7 and write no code at all.</p>
| 10,162 | 4 | 1 | null |
2008-08-13 16:08:43.68 UTC
| 13 |
2017-06-14 11:14:01.457 UTC
|
2009-07-08 07:18:28.38 UTC
|
caryden
| 24,874 |
caryden
| 313 | null | 1 | 24 |
wcf|silverlight|compression|gzip
| 19,644 |
<p>If you are using IIS7, take a look at the <a href="http://blogs.iis.net/ksingla/archive/2006/06/13/changes-to-compression-in-iis7.aspx" rel="noreferrer">Compression Module</a>. This allows you to configure compression for HTTP requests to your server.</p>
|
23,702,982 |
how to get selected value for Kendo DropDownList
|
<p>I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:</p>
<pre><code>@model KendoApp.Models.SelectorViewModel
</code></pre>
<p>The ViewModel is defined as:</p>
<pre><code>public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
</code></pre>
<p>and in My view I have:</p>
<pre><code>@(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
</code></pre>
<p>This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?</p>
| 23,709,341 | 7 | 1 | null |
2014-05-16 19:13:49.003 UTC
| 2 |
2021-06-02 12:11:26.643 UTC
| null | null | null | null | 195,356 | null | 1 | 14 |
kendo-ui|kendo-dropdown
| 104,598 |
<p>Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:</p>
<pre><code>@(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
</code></pre>
<p>This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.</p>
<p>BUT should you need to use the hidden field for some reason, put it there, <a href="http://demos.telerik.com/kendo-ui/web/dropdownlist/events.html" rel="nofollow">subscribe the the select event</a> of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.</p>
<p>It's your choice :)</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.